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!

Convert a .CRT to a .PFX for code signing!

I was trying to sign my code but my cert came as a crt and no one seems to play well with those. I imported into my the Certificate Store then tried to export. The PFX option was greyed out.

How freaking annoying. Well I followed the steps from this guy and it started working again like magic.

Awesome:

Link: https://weikingteh.wordpress.com/2010/11/22/unable-to-export-an-installed-certificate-to-pfx/

Unable to export an installed certificate to .pfx

If you’re trying to export an installed certificate into the .pfx format but the option is greyed out like when I was working with it for vPro provisioning, then it might be due to missing private keys. In my case, I’ve received a provisioning certificate from Comodo where I purchased it but was not able to export it to .pfx format which is required by the Out-of-Band Service Point in SCCM. If you are one of those that have this same experience, what you need to do is to recover the private key. To do this, type in certutil –repairstore my “<serialnumber>”.

How do you locate your serial number? Simply double-click on the certificate that you would like to export, go to the Details tab and note down the Serial Number found there. Once the command completed successfully, attempt to export the certificate again and you’ll see now that you are able to select to export the private key and the .pfx format option is now enabled.

 

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!

The type initializer for +’System.Windows.PresentationSource’ threw an exception.

I had an issue with a 3rd party control. I couldn’t blame them too much since the issue only happened in the WPF control hosted in a MFC C++ application. brutal for sure.

Why host WPF in C++? That is a question for another time, but let’s just say its an app written in the early 90’s and still has been rewritten, just bolted on and refactored.

Well, I created the test application and it worked great on my machine at home. I loaded it into my work computer and blammo, it threw up on the get handle call. WTF?

If you step into the .NET source(slow but very helpful), you get this.

System.Runtime.Versioning.BinaryCompatibility.ParseTargetFrameworkMonikerIn/toEnum in the call stack. and  NULL parameter exception.

Turns out through some goofiness in VC++, it will insert a null value in a manifest.

The fix is really easy. Delete all the files in your AppData\Local\Temp folder under your profile.

Here is a link to a guy who wrote about it in much more detail, but man that was non-intuitive fix. It worked though, so I am happy!

Thanks Microsoft for stealing another hour of my life. Thanks Telerik for being there to steal a week trying to reproduce bugs in your silly slow controls.

Happy coding!

 

How to display a different value in a WPF combobox based on selection

I couldn’t figure out a great way to title this post. Anyway, the issue I had was having a (none) value in the combobox but when it is selected show a blank combo. Those were the requirements and I wanted to do an easy solution without having to write a converter. Here is the solution using a simple style. Note, the StringResources line is where the source of the (none)string lives, You could just hard code this to your string if you aren’t pulling from a resource file.

Snippet

    <!-- Style for a combobox so that if the none value is picked, it will show up as a blank string.-->
    <Style TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="Margin" Value="0,2,0,2"/>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Margin="0">
                        <TextBlock.Style>
                            <Style TargetType="TextBlock">
                                <Style.Setters>
                                    <Setter Property="Text" Value="{Binding}"/>
                                </Style.Setters>
                                <Style.Triggers>
                                    <MultiDataTrigger><!-- handle the display struct-->
                                        <MultiDataTrigger.Conditions>
                                            <Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem},FallbackValue={x:Null}}" Value="{x:Null}"/>
                                            <Condition Binding="{Binding Text}" Value="{x:Static StringResources:WorkProgram.NoneValue}"/>
                                        </MultiDataTrigger.Conditions>
                                        <MultiDataTrigger.Setters>
                                            <Setter Property="Text" Value=" "/>
                                        </MultiDataTrigger.Setters>                                        
                                    </MultiDataTrigger>                                  
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Hapy coding!