TextBox Autocomplete – Crash AccessViolationException – Workaround

It seems a nogo, but there’s a bug with AutoCompletion on Winforms since years. (.net7 here)
The only way to make it work is to set the source only once.
If you try to have a dynamic Suggestion, you could set :

Text_OnChanged(object e)
{
AutoCompleteStringCollection.AddRange("hello");
// CRASH AccessViolationException
}

It will crash with AccessViolationException.

Based on my Winforms TextBox.cs reading, I found an elegant solution.

1. Set private field _fromHandleCreate to true after HandleCreated

public class MyTextBox : TextBox
{
    FieldInfo? fiFromHandleCreate = typeof(TextBox).GetField("_fromHandleCreate",
                                                        BindingFlags.Instance |
                                                        BindingFlags.NonPublic |
                                                        BindingFlags.SetField |
                                                        BindingFlags.GetField);

    protected bool IsFromHandleCreate
    {
        get => (bool)fiFromHandleCreate.GetValue(this);
        set => fiFromHandleCreate.SetValue(this, value);
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        IsFromHandleCreate = true; //important to not destroy AutoComplete handle, avoid flickering 
    }
}

2. Redefine AutoCompleteStringCollection

The main trick is there’s always at least one element : String.Empty, because when the collections is cleared, Autocompletion is disconnected from the Textbox (and recreation bring bug)
The second trick is to set RemovedItem to String.empty instead of removing them
The third trick is to occupate empty Slot when Adding to reduce memory consumption

    /// <summary>
    /// Make AutoCompleteStringCollection dynamic
    /// </summary>
    public class MyAutoCompleteStringCollection : AutoCompleteStringCollection
    {
        static readonly string EmptyEntry = String.Empty;//space magic string
        public MyAutoCompleteStringCollection()
        {
            this.Add(EmptyEntry);//never delete this entry
        }

        FieldInfo? fidata = typeof(AutoCompleteStringCollection).GetField("data",
                                                        BindingFlags.Instance |
                                                        BindingFlags.NonPublic |
                                                        BindingFlags.SetField |
                                                        BindingFlags.GetField);
        /// <summary>
        /// base.data private field
        /// </summary>
        protected ArrayList Data
        {
            get => (ArrayList)fidata.GetValue(this);
            set => fidata.SetValue(this, value);
        }

        /// <summary>
        /// base.Clear is Evil => it disconnect the Autocompletion....:(
        /// </summary>
        public new void Clear()
        {
            var vData = this.Data;
            vData.RemoveRange(1, this.Count-1);

            //notify
            if (this.Count>1)
                base.OnCollectionChanged(new System.ComponentModel.CollectionChangeEventArgs(System.ComponentModel.CollectionChangeAction.Refresh, null));
        }

        /// <summary>
        /// Remove but without removing the String.Empty rentry
        /// </summary>
        /// <param name="value"></param>
        public new void Remove(string value)
        {
            int index = IndexOf(value);
            if (index > 0) //keep String.Empty
                base[index] = string.Empty; // clean slot + notify
        }
        /// <summary>
        /// RemoveAt but without removing the String.Empty rentry
        /// </summary>
        public new void RemoveAt(int index)
        {
            if (index > 0)//keep String.Empty
                base[index] = string.Empty; // clean slot + notify
        }

        /// <summary>
        /// Add to an unoccuped slot or a new one
        /// </summary>
        public new void Add(string text)
        {
            int index = -1;
            for (int i = 1; i < Count; i++)
            {
                if (this[i] == string.Empty)
                {
                    index = i;
                    break;
                }
            }
            if (index > 0)
                base[index] = text; // occupate the slot + notify            
            else
                base.Add(text); // add+notify
        }

        /// <summary>
        /// AddRange with efficient slot occupating
        /// </summary>
        /// <param name="values"></param>
        public new void AddRange(string[] values)
        {
            var vData = this.Data;

            int cpt = 0;
            for (int x = 0; x < values.Length; x++)
            {
                int index = -1;
                for (int i = 1; i < Count; i++)
                {
                    if (vData[i] == string.Empty)
                    {
                        index = i;
                        break;
                    }
                }
                if (index > 0)
                {
                    vData[index] = values[x]; // occupate the slot                
                    cpt++;
                }
                else
                    break;
            }

            //Send last part via AddRange
            if (cpt < values.Length)
                vData.AddRange(values.Skip(cpt).ToArray());

            if(values?.Length>0) //notify
                base.OnCollectionChanged(new System.ComponentModel.CollectionChangeEventArgs(System.ComponentModel.CollectionChangeAction.Refresh, null));

        }

    }

Et voilà !
Stephane

Posted in Non classé | Tagged , | Leave a comment

The solution for validating an email address (RFC compliant) in .net C#

It’s a common question : “How can I validate one email address” ?

There are 0b10 (2) types of developers : lazy and ignorant.

  1. Lazy people always wins, because they do not reinventing the wheel, they prefer to search already done API.
  2. Ignorant people will probably use Regexp (I love regexp but not in this case) or write a new algorithm, they could spend few hours or days to implement the full RFC, good luck !

So the code is obvisouly server side, and in .net :

try
{
   new HttpRequestMessage().Headers.From = "mail@foo.com";
   //here the mail is valid
}
catch(FormatException ex)
{
// here the email is invalid
}
Posted in Non classé | Leave a comment

WinRT Apps : Slow Compilation when you add WinRT components : Solution

PROBLEM

When you create a Blank WinRT project (W8 or WP8.1) with Visual Studio, if you compile as it, it takes : 2 seconds => great !

BUT, if you just add a simple WinRT component library (winmd) as reference and build, it takes 12 to 15 seconds… => wt….???! (if you add a DLL, there is no problem)

Well, it’s not a good start for a project, I didn’t find anything on the Internet about this issue, but I’m sure some developers will burn their computer if they have this issue (maybe they already bought a new CPU ;) ?)

WHY ?

If you verbose the MSBuild log, you can see this line

> 10179 ms GenerateAppxManifest 1 calls

Ok GenerateAppXManifest is the CPU eater ! We have to found the solution…

SOLUTION

The Solution I found is to override the value AppxHarvestWinmdRegistration to false for MSBUILD in your App csproj, and to fill your AppxManifest .xml Extensions section as it was generated before in the Debug/Release directory – before this hack :) -.

1. open your project.csproj, and add :

<PropertyGroup>   
<AppxHarvestWinmdRegistration >false</AppxHarvestWinmdRegistration> 
</PropertyGroup> 
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />

2. Then, you have to update your AppxManifest.xml like it was before in the Debug/Release dir for the Extensions section (specially if you use the Background Audio or anything which communicate with the external process) :

<Package....

<Extensions>
 <Extension Category="windows.activatableClass.inProcessServer">
 <InProcessServer>
 <Path>CLRHost.dll</Path>
 <ActivatableClass ActivatableClassId="BackgroundAudioTask.MyBackgroundAudioTask" ThreadingModel="both" />
 </InProcessServer>
 </Extension>
 </Extensions>

Have a nice coding day !

@poppyto

Posted in Non classé | Leave a comment

Solution to Empty Emulator List (plus 0x80070002) in Windows Phone SDK 8

Sometimes, Visual Studio fails and you can’t do anything. You can repair or reinstall but in this case it’s not works.

PROBLEM : You can’t see any Emulators on Visual Studio :

and when you try to compile it throws 0x80070002  (File not found exception) :

SOLUTION :

So there are missing files, I catch them with ProcMon and by using MultiTargetingConnectivity API (this is THE api which throws 0x80070002) They are here in this location C:\Users\[Your User]\AppData\Local\Microsoft\Phone Tools\CoreCon\11.0

They are :
– Microsoft.ServiceCategories.xsl,
– Microsoft.VisualStudio.ServiceCategories.xsl
– Microsoft.XDE.ServiceCategories.xsl
 Microsoft.TypeMaps.xsl

It can be difficult to retreive these files (I repaired reinstall SDK 8 with no luck, trying to remove 11.0 directory and reinstall etc) so as I’m a nice guy, you could find the directory 11.0 zipped here : Download the full directory 11.0, extract here and copy/paste the missing file in your directory.

Have a nice coding day :)
Stephane

Posted in Non classé | Leave a comment

Solution for blurry rendering with DirectX11 on Windows Phone 8

If you experienced a global blurry rendering on your screen when you use DirectX11 on your Windows Phone 8, you probably fails a thing :

The swapchain size must be the screen size (means portrait), not the landscape size.

So  :

swapChainDesc.Width = 800;//
swapChainDesc.Height = 480; // blurry rendering !

swapChainDesc.Width = 480;//
swapChainDesc.Height = 800;  // perfect rendering !

That’s all, take care !1

Posted in Non classé | Leave a comment

Solution for Error ERROR_DLL_INIT_FAILED while Loading winmd file in Windows RT

If you experienced the Exception : Error in the DLL (Exception from HRESULT: 0x8007045a (ERROR_DLL_INIT_FAILED))

The solution is simple : You have to remove the main function.
(I know, why the fonction “main” is called with DLL? idk :))

Posted in Non classé | Leave a comment

Solution for Error CO_E_ERRORINDLL while Loading winmd file in Windows Phone 8

If you experienced the Exception : Error in the DLL (Exception from HRESULT: 0x800401F9 (CO_E_ERRORINDLL))

The solution is simple :

You Must Add the _WINRT_DLL flag in the compiler definitions.

Posted in Non classé | Leave a comment

Windows Phone Store 8 shows neutral titles instead of localized titles

Dear you,

I experienced a bug in the Windows Phone 8 Store : I localized my app titles with the AppResLib.dll (& mui) and the tiles title were ok in the phone but the WP8 Store shown only the neutral language title. (on WP7 Store only, it looks ok!)

SOLUTION

In the WMAppManifest.xml (WP8) or in the project settings (WP7), you have to uncheck generic language codes (as “fr”,”it”,”de”) and check all the sub-language codes like “fr-FR”,”fr-BE”,”it-IT”, etc. If you check both generic and sub-languages, this will not working.

CONCLUSION

For the moment : don’t ever use the generic language codes (if you used them in your old WP7 app, this will appears Ok on WP7 Store but incorrectly on WP8 Store)

That’s all and this works !

Complete thread here.

Posted in Non classé | Leave a comment

Avoid IIS locks/hangs because of static contents, and improve the IIS performances !

The best asp.net programmed web site could be not VERY fast. I mean, you could be dissapointed by the performances of your website if your IIS configuration is not optimized.

The problem

You have a website with the runAllManagedModulesForAllRequests property setted to true in web.config.
What this means ? Every requests will be handled by ASP.net ! So static contents will also be handled by ASP.net !

Real Situation

You published a new page with a big flv (30Mo) and a lot of people try to watch it simultaneously (like 20/30 people) : your IIS will be locked for a good while ! If you look at the process manager, you could see the CPU around 25%, and a lot of Threads in queue !
Because ASP.net is buffering every request in the Thread Pool and it is saturating. As you know the ASP.net Thread Pool max is by default 25 (you can change it) !

Wrong Solution

You could upgrade the Thead Pool max, but it’s the wrong solution, because you will consume so much more memory and ASP.net is delivering files after buffering (you have to wait a lot of time before downloading a huge file).

Good Solution

You have to disable runAllManagedModulesForAllRequests in the sub-directory like this :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer> 
<modules runAllManagedModulesForAllRequests="false"/>
<staticContent>
<mimeMap fileExtension="." mimeType="application/octet-stream" />
</staticContent> 
</system.webServer> 
</configuration>

This will disable ASP.net for this subapplication.
The only problem is : you have to create a sub application (not a subdirectory) to do that.

So if your directory is /content and you don’t want to update all your ResolveUrl stuff:

– rename /content as /content2
– create a sub-application named “content” with the directory C:\website\content2
– add the web.config file

It should be working. To be sure, upload a huge file (like 2Go) in content2 (the real directory) and try to download it by :
– http://website/content/hugefile.zip
– http://website/content2/hugefile.zip

The first URL /content should deliver the file instantaneously, and the the second should take a huuuge time

Benefits

If all your static contents are not handled by ASP.net, you could feel a very very fast website, a general CPU decrease, even if there is a lot of people connected.

Stephane

Posted in Non classé | Leave a comment

Resolve the “‘Microsoft.Advertising.WinRT.UI.winmd’ contains duplicate types names”

Hi everybody,

I recently had an issue with the Microsoft Advertising SDK for WinRT.
I can’t compile without an error  (I found a tip – remove reference/compile/add reference/compile – but I can’t compile for making an app package).

The famous error is :

error APPX1712: The .winmd file ‘Microsoft.Advertising.WinRT.UI.winmd’ contains duplicate type names. Type ‘Microsoft.Advertising.WinRT.UI.AdControl’ is already registered with the in-process server ‘CLRHost.dll’.

1>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\AppxPackage\Microsoft.AppXPackage.Targets(803,9): error APPX1712: The .winmd file ‘Microsoft.Advertising.WinRT.UI.winmd’ contains duplicate type names. Type ‘Microsoft.Advertising.WinRT.UI.XamlAdControl_XamlTypeInfo.XamlMetaDataProvider’ is already registered with the in-process server ‘CLRHost.dll’.

What the hell is ? It’s just a bogous statment, my project is maybe not typical : I use some library, and it seems the compiler does not like that.

HOW TO RESOLVE ?

I found a lot of posts on The Internet and non solve this issue. I spent a lot of time to find this :

1. Open with notepad the SDKManifest.xml in C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSAdvertisingXaml\6.1\SDKManifest.xml with administrator rights
2. Edit this line   <File Reference = “Microsoft.Advertising.WinRT.UI.winmd” >
3 .Modify by <File Reference = “Microsoft.Advertising.WinRT.UI.winmd” Implementation=”Microsoft.Advertising.WinRT.UI.winmd” >
4. Recompile  and enjoy

That’s all, everything works perfect after that ;)

EDIT

Unfortunately, this works but the certification kit fails with that stuff (I mean advertising load in the DLL).

How to do : I referenced the SDK in the EXE, and Loaded in the DLL by Reflection the Type (Microsoft.Advertising.WinRT.UI.AdControl) referenced in the EXE.
Just a crappy stuff because of a bogus SDK : but it works and certification kit is happy !

Stephane

Posted in Non classé | Leave a comment