How to add a custom user agent in the header using a webview and Xamarin Forms

I am writing an app using Xamarin Forms and wanted to control the user agent for my webview. It’s a little hacky way to have the website render differently when it see that it’s my app coming in without having to use session cookies or other crap like that.

It was pretty easy once I found the code, but finding the code was the pain. Well, Add this renderer to your IOS project.

Snippet

using Foundation;
using PrazeMeApp.iOS.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
 
[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace PrazeMeApp.iOS.Renderers
{
    public class MyWebViewRenderer : WebViewRenderer
        {
            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject("myuseragentgoeshere"), NSObject.FromObject("UserAgent"));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);
            base.OnElementChanged(e);
            }
        }
    }

 

Happy Coding!

Xamarin PCL – How to URL Encode since there is no HttpUtility

Looking for the HTTPUtility class? Ha, you don’t get it. PCL doesn’t have it. Fret not, though, you can still URL Encode.

It’s easy, just in a different spot.

How to URLEncode in Xamarin Forms PCL

var encodedData = System.Net.WebUtility.UrlEncode(stuffToEncode);

Now you know, and now hopefully I will remember!

Happy coding!

Visual Studio 2015 error “Object reference not set to an instance of an object”

This fixed my razor intellisense problem and the error after installing the latest ASP.NET tools.

Here is how to fix it.

Delete the contents from the following folders:
C:\Users{user}\AppData\Local\Microsoft\VisualStudio
C:\Users{user}\AppData\Local\Microsoft\VSCommon

Navigate to the command line now and run devenv from either of these paths:
[x64] C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
[x86] C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE

run devenv /resetuserdata from the command prompt.

Thanks to fka for the steps!

https://stackoverflow.com/questions/34084003/visual-studio-2015-error-object-reference-not-set-to-an-instance-of-an-object/34085345#34085345

Happy Coding!

Value was either too large or too small for a UInt32. TFS Error

I got this error in Visual Studio 2015 checking in to TFS.
“Value was either too large or too small for a UInt32.”

WTF? Turns out it is because I had an open sql query file that wasn’t saved and it get angry.

Really stupid error that should read :” You have an saved file, please save all files before checking in”

Wow. That would have taken the developer a small minute. Oh yeah, this is probably an unhandled exception, caught higher up and presented to us as an amazing insight into what was wrong.

Anyway, Save All before checking in and you will be fine.

Happy Coding!

Where is Inspect.exe for UI Access?

Stupid SDK doesn’t give any details on where the SDK path is, etc.

Well, Install the Windows 8.1 SDK with the options. You have plenty of disk space, so don’t whine.

Here is the path for the 64 bit version.

C:\Program Files (x86)\Windows Kits\8.1\bin\x64

 

Happy Coding!

Force rebind on a WPF control or view by resetting the DataContext without using null!

I had an issue where I wanted to force a datacontext to rebind everything. The RaisePropertyChanged(“”) wasn’t working and I like to keep things simple.

I was setting the DataContext = null then setting it back to the desired object right after to force a rebind. This worked well but really pissed off some of the controls. Not everyone appreciates a null databind.

So, what to do. I remember working with virtualization and the DisconnectedItem, a hidden magical gem that Microsoft just finally let us have public access to in 4.5, had magical powers with databinding. It cast a spell that made everyone calm and happy.

The null databinding on the DataContext was causing major slowdowns in the app as all the controls got angry. So I switched the DataContext=null to DataContext = DisconnectedItem.

All was right in the world again and the application became fast again.

Confused, well I am tired. Anyway, here it is in the before and after and it should then make sense. Edited for brevity.

private static object disconnectedItem = null;
 
        private void UpdatePropertiesView()
        {                   
                    newView.DataContext = null;
                    newView.DataContext = SelectedNode.Node;                               
        }

Snippet

private static object disconnectedItem = null;
 
        private void UpdatePropertiesView()
        {
                    if (disconnectedItem == null)
                        disconnectedItem = typeof(System.Windows.Data.BindingExpressionBase).GetField("DisconnectedItem", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                    newView.DataContext = disconnectedItem;//force rebind, but gentler.
                    newView.DataContext = SelectedNode.Node;                               
            }
        }

 

The reason I am doing this is because the Node object didn’t change, but the properties on it did.(a lot of them).

Happy Coding!

PS: Yes, I am adding a check to see if the datacontext is the same so I can skip the null set entirely in those instances…..

 

 

System.InvalidOperationException with RadRichTextbox from Telerik in WPF

If you have an HTML document that you import into the RadRichTextbox that has images and you are hosting WPF within MFC (c++), then you are probably running into this issue. Right along with all the people who have a steering wheel on the right side of the car driving around in the States. Yeah, all 1 of us.

Anyway, it’s an issue for us but here is the work around since Telerik will probably be slow to fix it, if they do. Quick backstory, they  load the images using WebClient instead of loading from disk. Better yet, they use the async methods on the webclient with a callback. We all know how much WPF loves stuff from other threads.

Here is the fix.

Snippet

  {//.........some function some where in time.
  var formatter = new HtmlFormatProvider();//The thing you use to load your html
    formatter.ImportSettings.LoadImageFromUrl += ImportSettings_LoadImageFromUrl;
    var doc = formatter.Import(html);//html is your variable with your html....from whereever
    boxxy.Document = doc;//boxxy is my richtextbox instance
}
 //the meat and potato's 
void ImportSettings_LoadImageFromUrl(object sender, LoadImageEventArgs e)
{           
    using (var file = new FileStream(e.Url, FileMode.Open))
    {
        e.ImageElement.UriSource = null;//prevent them from trying to load in background
        e.ImageElement.Init(file, Path.GetExtension(e.Url));//load from our stream
        e.ImageElement.ImageSource.Freeze();//prevent cross thread issue by freezing it.
    }
    e.Handled = true;
}

 

Happy Coding!

FIX: TabControl in WPF Shows wrong tab if Active Tab is Invisible

You want to dynamically show or hide tabs in WPF. Say, some only show up if a certain option is set. Well, it shows anyway if its the first tab. Stupid. Here is an attached property to fix that.

Based on code from http://www.codeproject.com/Articles/349140/WPF-TabControl-focus-behavior-with-invisible-tabs

 

using System;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
namespace Seekford
{/// <summary>Behaviors for TabControl.
    /// </summary>
    public class TabControlBehavior
    {
        /// <summary>Whether to focus the first visible tab.
        /// </summary>
        /// <remarks>Setting the FocusFirstVisibleTab
        /// attached property to true will focus the next visible tab when
        /// the current selected tab's Visibility property is set to Collapsed or Hidden.</remarks>
        public static readonly DependencyProperty FocusFirstVisibleTabProperty =
            DependencyProperty.RegisterAttached("FocusFirstVisibleTab", typeof(bool),
                typeof(TabControlBehavior),
                new FrameworkPropertyMetadata(OnFocusFirstVisibleTabPropertyChanged));
        /// <summary>Gets the focus first visible tab value of the given element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns></returns>
        public static bool GetFocusFirstVisibleTab(TabControl element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            return (bool)element.GetValue(FocusFirstVisibleTabProperty);
        }
        /// <summary>Sets the focus first visible tab value of the given element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="value">if set to <c>true</c> [value].</param>
        public static void SetFocusFirstVisibleTab(TabControl element, bool value)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            element.SetValue(FocusFirstVisibleTabProperty, value);
        }
        /// <summary>Determines whether the value of the dependency property <c>IsFocused</c> has change.
        /// </summary>
        /// <param name="d">The dependency object.</param>
        /// <param name="e">The  instance containing the event data.</param>
        private static void OnFocusFirstVisibleTabPropertyChanged(
                DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var tabControl = d as TabControl;
            if (tabControl != null)
            {
                // Attach or detach the event handlers.
                tabControl.IsSynchronizedWithCurrentItem = true;
                if ((bool)e.NewValue)
                {
                    var collection = tabControl.Items as INotifyCollectionChanged;
                    if (collection != null)
                    {
                        collection.CollectionChanged +=
                          new NotifyCollectionChangedEventHandler(TabControl_Items_CollectionChanged);
                    }
                }
                else
                {
                    // Disable the attached behavior.
                    var collection = tabControl.Items as INotifyCollectionChanged;
                    if (collection != null)
                    {
                        collection.CollectionChanged -=
                          new NotifyCollectionChangedEventHandler(TabControl_Items_CollectionChanged);
                    }
                    // Detach handlers from the tab items.
                    foreach (var item in tabControl.Items)
                    {
                        TabItem tab = item as TabItem;
                        if (tab != null)
                        {
                            tab.IsVisibleChanged -=
                              new DependencyPropertyChangedEventHandler(TabItem_IsVisibleChanged);
                        }
                    }
                }
            }
        }
        /// <summary>Handles the CollectionChanged event of the TabControl.Items collection.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see
        ///    cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/>
        ///    instance containing the event data.</param>
        static void TabControl_Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // Attach event handlers to each tab so that when the Visibility property changes of the selected tab,
            // the focus can be shifted to the next (or previous, if not next tab available) tab.
            var collection = sender as ItemCollection;
            if (collection != null)
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                    case NotifyCollectionChangedAction.Remove:
                    case NotifyCollectionChangedAction.Replace:
                        // Attach event handlers to the Visibility and IsEnabled properties.
                        if (e.NewItems != null)
                        {
                            foreach (var item in e.NewItems)
                            {
                                TabItem tab = item as TabItem;
                                if (tab != null)
                                {
                                    tab.IsVisibleChanged +=
                                      new DependencyPropertyChangedEventHandler(TabItem_IsVisibleChanged);
                                }
                            }
                        }
                        // Detach event handlers from old items.
                        if (e.OldItems != null)
                        {
                            foreach (var item in e.OldItems)
                            {
                                TabItem tab = item as TabItem;
                                if (tab != null)
                                {
                                    tab.IsVisibleChanged -=
                                      new DependencyPropertyChangedEventHandler(TabItem_IsVisibleChanged);
                                }
                            }
                        }
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        // Attach event handlers to the Visibility and IsEnabled properties.
                        foreach (var item in collection)
                        {
                            TabItem tab = item as TabItem;
                            if (tab != null)
                            {
                                tab.IsVisibleChanged +=
                                  new DependencyPropertyChangedEventHandler(TabItem_IsVisibleChanged);
                            }
                        }
                        break;
                    case NotifyCollectionChangedAction.Move:
                    default:
                        break;
                }
                // Select the first element if necessary.
                if (collection.Count > 0 && collection.CurrentItem == null)
                {
                    foreach (var item in collection)
                    {
                        if ((item as TabItem).Visibility == Visibility.Visible)
                        {
                            collection.MoveCurrentTo(item);
                            break;
                        }
                    }
                }
            }
        }
        /// <summary>Handles the IsVisibleChanged event of the tab item.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see
        ///   cref="System.Windows.DependencyPropertyChangedEventArgs"/>
        ///   instance containing the event data.</param>
        static void TabItem_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            TabItem tab = sender as TabItem;
            if (tab != null)
            {
                //ensure active tab is visible
                TabControl tabControl = tab.Parent as TabControl;
                if (tabControl != null)
                {
                    bool goforward = true;
                    while (tabControl.SelectedItem == null || (!(tabControl.SelectedItem as TabItem).IsVisible))
                    {
                        if (goforward)
                        {
                            goforward = tabControl.Items.MoveCurrentToNext();
                        }
                        else
                        {
                            if (!tabControl.Items.MoveCurrentToPrevious())
                                break;//nothing is visible
                        }
                    }
                }
            }
        }
    }
}

 

Happy Coding

How to run a batch file with administrator priveleges with automatic elevation

Do you have build scripts that require you run commands elevated. Do you forget to click run as admin then you get errors halfway through a 20 minute build?

Well, I did all the damn time. I found this script change and it works awesome so I figured I would share with the class.


if _%1_==_payload_ goto :payload

:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^(“Shell.Application”^) >> “%vbs%”
echo UAC.ShellExecute “%~s0”, “payload %~sdp0 %*”, “”, “runas”, 1 >> “%vbs%”
“%temp%\getadmin.vbs”
del “%temp%\getadmin.vbs”
goto :eof

:payload
echo %~nx0: running payload with parameters:
echo %*
echo —————————————————
cd /d %2
shift
shift
rem put your code here
rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
rem SEEKFORD – added code for build. I left in above for guys that need params in this blog post.
@cd /d “%~dp0”
set msbuilddir=C:\program Files (x86)\MSBuild\12.0\Bin
“%msbuilddir%\msbuild” “%CD%\SSI.Build” /t:Build /p:Configuration=Debug;ReferencePath=%CD%\..\bin
goto :eof

 

This is a modified version that I got from here (thanks to Alois Mahdal) that adds in how to build using msbuild.

Happy Coding! or emmm.. Happy Building!!