Search This Blog

Thursday, December 22, 2016

Concatenating strings with different writing systems / orientations (RTL, LTR) and forcing the resulting one's orientation to one of them

If you are facing problems in concatenating strings with different writing systems/orientations into a single one (those that are RTL are all moved to the beginning of the string, for instance) - you can find a solution to the problem here.

Basically, you need to prepend to the strings you want to manually change the orientation the unicode character that specifies the orientation of the following piece of text. If you have RTL and LTR strings and do not want the LTR strings to be positioned at the beginning, rather in their proper positions, prepend the unicode character \u200E.

Sunday, December 18, 2016

Reset Visual Studio "Look at these file types" value

private static void Main(string[] args)
{
    RegistryKey regKey = null;

    try
    {
        //HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\Find
        regKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\14.0\Find"true);

        var filters = regKey.GetValueNames().Where(v => v.StartsWith("Filter"));
        foreach (var filter in filters)
        {
            regKey.SetValue(filter, string.Empty);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Registry clear for filter keys failed. {0}", ex.Message);
        return;
    }
}

Tuesday, December 6, 2016

Reading Windows Registry values in c#

An example I wrote for retrieving any windows registry value, and return its string representation (some values are stored as byte arrays, some as 4-byte or 8-byte numbers, etc)


private static bool GetRegistryKeyValue(string keyFullPathWithoutRoot, string subKey, out string valueAsStr, RegistryHive rootNode = RegistryHive.LocalMachine, RegistryView registryView = RegistryView.Registry64, bool getNumericValuesInHexaNotation = truebool displayMessageBoxUponErrors = false)
{
    //search a registry key for a given subkey, if found return its value in a textual representation

    /*
     * Note:
     * The Wow6432 registry entry indicates that you're running a 64-bit version of Windows.
     * The OS uses this key to present a separate view of HKEY_LOCAL_MACHINE\SOFTWARE for 32-bit applications that run on a 64-bit version of Windows.
     */


    RegistryKey root = RegistryKey.OpenBaseKey(rootNode, registryView);
    RegistryKey registryKey = null;
    object subKeyValue = null;
    valueAsStr = null;

    try
    {
        //read key
        registryKey = root.OpenSubKey(keyFullPathWithoutRoot);

        if (registryKey != null)
        {
            //get subKey value type (binary, dword, etc)
            RegistryValueKind subKeyValueKind = registryKey.GetValueKind(subKey);
            subKeyValue = registryKey.GetValue(subKey);
            switch (subKeyValueKind)
            {
                case RegistryValueKind.Binary:
                    byte[] byteArray = (byte[])subKeyValue;
                    valueAsStr = string.Join(" ", byteArray.Select(b => b.ToString()));
                    break;

                case RegistryValueKind.DWord:
                    int dword = (int)subKeyValue;
                    valueAsStr = getNumericValuesInHexaNotation ? Convert.ToString(dword, 16).ToUpper() : dword.ToString();
                    break;

                case RegistryValueKind.QWord:
                    long qword = (long)subKeyValue;
                    valueAsStr = getNumericValuesInHexaNotation ? Convert.ToString(qword, 16).ToUpper() : qword.ToString();
                    break;

                case RegistryValueKind.String:
                    valueAsStr = (subKeyValue ?? string.Empty).ToString();
                    break;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to read {keyFullPathWithoutRoot}\\{subKey} key from registry. {ex.Message}");
        return false;
    }

    return true;
}
private static void TestRegistryReads()
{
    List<Tuple<stringstring, RegistryView>> keys = new List<Tuple<stringstring, RegistryView>>
    {
        new Tuple<stringstring, RegistryView>(@"SOFTWARE\Khronos\OpenCL\Vendors""IntelOpenCL32.dll", RegistryView.Registry32),
        new Tuple<stringstring, RegistryView>(@"HARDWARE\ACPI\FACS""00000000", RegistryView.Registry64)
    };

    foreach (var key in keys)
    {
        string value;
        if (GetRegistryKeyValue(key.Item1, key.Item2, out value, RegistryHive.LocalMachine, key.Item3, displayMessageBoxUponErrors: true))
        {
            Console.WriteLine("---------------------");
            Console.WriteLine($"Key: [{key.Item1}]  SubKey: [{key.Item2}], SubKeyValue: [{value}], Architecture: [{key.Item3.ToString()}]");
        }
    }
}

Sunday, November 27, 2016

Editing windows registry to Force WebBrowser control use the latest IE version installed in local machine

Here's the C# code I used for this task:

private void EditRegistryToFixIEWebBrowserCompatibility()
       {
           string installedIEVersion = string.Empty;
           int hostAppKeyValue = 0;
           //name of the application that hosts the WebBrowser object being invoked. If you are in debugging mode, the extension should be ".vshost.exe" instead of ".exe".
           var hostAppKeyName = Assembly.GetExecutingAssembly().GetName().Name + ".exe";

           //registry key for Feature Browser Emulation
           RegistryKey regKeyFBE = null, regKeyInstalledIEVersion = null, regKeyHostApp = null;

           try
           {
               //search for Feature Browser Emulation key in relevant windows architecture
               if (Environment.Is64BitOperatingSystem)
               {
                   regKeyFBE = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION"true);
                   regKeyInstalledIEVersion = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer"true);
               }
               else
               {
                   //For 32 bit machine
                   regKeyFBE = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION"true);
                   regKeyInstalledIEVersion = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\"true);
               }

               //get current IE installed version
               installedIEVersion = Convert.ToString(regKeyInstalledIEVersion.GetValue("svcVersion"))?.Split('.').FirstOrDefault();
               int.TryParse(installedIEVersion, out hostAppKeyValue);
               hostAppKeyValue *= 1000;
           }
           catch (Exception ex)
           {
               MessageBox.Show("Registry creation of Feature Browser Emulation key failed for Internet Explorer failed. {0}", ex.Message);
               return;
           }

           #region Search for registry key

           try
           {
               //search for a dword with a key named like our app's exe (if its value is lower than the current installed IE version, discard
               hostAppKeyValue = Math.Max(hostAppKeyValue, Convert.ToInt32(regKeyFBE.GetValue(hostAppKeyName)));
           }
           catch (Exception)
           {
               MessageBox.Show($"{hostAppKeyName} key does not exist. Creating...");
               regKeyHostApp = regKeyFBE.CreateSubKey(hostAppKeyName);
               int.TryParse(installedIEVersion, out hostAppKeyValue);
               hostAppKeyValue *= 1000;
           }

           #endregion

           // Need to set the minimum IE version currently supported by Google Maps's api - multiplied by 1000
           regKeyFBE.SetValue(hostAppKeyName, unchecked(hostAppKeyValue), RegistryValueKind.DWord);

           try
           {
               //Check for the key after adding
               hostAppKeyValue = Convert.ToInt32(regKeyFBE.GetValue(hostAppKeyName));
           }
           catch (Exception ex)
           {
               MessageBox.Show("Registry creation of Feature Browser Emulation key failed for Internet Explorer failed. {0}", ex.Message);
               return;
           }
       }

Thursday, November 24, 2016

C# WebBrowser facing errors when navigating into a page that makes use of (the new 3.25) google maps api

Problem:

I have a win forms application that makes use of a System.Forms.WebBrowser object, which in turn navigates to a given html that contains several javascript files that makes an api for drawing areas/polygons / adding text labels, among other things, on top of google maps. The problem is that google recently upgraded their api to v3.25, in which they do not support anymore IE versions lower than 10. My WebBrowser object was always emulating an IE 7 browser (not clear why, because after creating a blank winforms project and adding a single WebBrowser into it, to navigate into a page like the mentioned above - but this time hosted locally - the user agent string displayed (after adding alert(this.navigator.userAgent); into the onload event of the body html element) contained no "compatible; MSIE 7;" or alike, rather a rv.11 (referring to IE 11)).
Having the WebBrowser running an emulation of IE 7 was causing javascript errors (Google's api stopped supporting IE versions prior to 10).

Solution:

The solution that finally worked was this one.

Summary:

  1. Make sure you have IE 10 or higher installed on the machine serving the uri WebBrowser is to navigate to.
  2. Add the registry values as indicated in the link above - do not forget, when adding the DWORD, to use a key with the exact .exe file where the WebBrowser instance is invoked.
I added another post containing the C# code for fixing this issue (another post because I wanted a post that would catch a closer-to-the-exact-issue title).

Update: The approach above was found to be incomplete, due to part of Google API being deprecated some versions from now (which was still available to 3.4). Make sure you do not make use of MarkerImage, like below.

Click here for google's reference on it, but here's the summary:


Tuesday, November 22, 2016

Find in Visual Studio Find Results (further search)

I was wondering if it was possible to further search the results of a Find Results window in Visual Studio. I googled it but did not arrive to any relevant answer.

I then played a bit with it and ended up figuring out that it is possible - it is built in, and it's quite simple: just click CTRL + F inside the Find Results window.



Thursday, October 13, 2016

Xamarin Forms Real Time Designer / Previewer

I have been trying what is available out there, at the moment, with regards to a real time UI designer for Xamarin forms.

The outcome of my research is:
  1.  Tried Xamarin's Previewer - am stuck with the designer showing a gray box containing  "XFPageRendererView". You can find other users facing the same issue. I tried to follow what they did to overcome it, but without success. Actually none of the solutions presented is really clear. It's worth mentioning a major drawback of this option: you must have a Mac running (at least in the current state of things, this seems to be a bug, not yet fixed) , to which you will connect to as the Mac Agent in Visual Studio, otherwise the previewer does not seem to respond. Like Gorilla Player, requires you to code your UI using XAML.
  2. Xamarin Forms Player - there is a nuget package, it is a headache to install, because it will (may) conflict with several of your other nuget packages - my workaround here was to manually install all the depencencies/missing ones, one by one, in the Droid project. Still, after being all set and ready to go, I could not go passed the Window with the Connect button. No idea how to proceed from there, what am I supposed to do, how do I finally see the preview. No suceess, followed the docs/the site, to no avail.
  3. Last and only working option - Gorilla Player. Setup consists of installing a program both in the desktop and in the device. But that's all. Just follow the instructions from the site, and things move smoothly. Drawback: you are forced to code your UI using XAML.

Sunday, October 9, 2016

Silverlight NumericUpDown and BusyIndicator dlls missing

If you are facing the messages

The type or namespace name 'NumericUpDown' could not be found (are you missing a using directive or an assembly reference?)

or

The type or namespace name 'BusyIndicator' could not be found (are you missing a using directive or an assembly reference?)

You are likely missing the installation of Silverlight's toolkit. Install the one that matches the silverlight version you are using.

Thursday, October 6, 2016

Find out which mySql version you are using without using the command line

Most posts will tell you to run something in the mysql command line, but in case you do not have it installed, like me (I have only an sql editor installed), function VERSION can give you that from the Sql Editor you are using:

Simply run  a SELECT VERSION()

Tuesday, September 27, 2016

Setting up a Xamarin development enviroment in Visual Studio 2015

In this post, I will keep track of all the important steps I followed in order to successfully build, deploy and run a HelloWorld Xamarin.Forms application, both in an emulator as well in a physical device - plus successfully debugging it as well.

I had lots of trouble and in doing that under Windows 7, where much of the goals mentioed above were not accomplished at all.

On the other hand, after moving to a fresh new Windows 10 installation on a formatted drive, everything changed dramatically. Installing Visual Studio with Xamarin Cross Platform component was all I did to achieve running the app both in an emulator and device, plus debugging.

So here is the check-list, as I am aware of:

  1. Operational System: Windows 10 (it seems, by googling, possible to do all this in Windows 7, but from my experience, it adds lots of difficulties, such as the absence of Hyper-V virtualization server (hindering emulation) - weighed against the smooth experience of doing it in Windows 10 - must make you consider upgrading your OS very seriously.
  2. Installing Visual Studio 2015 marking the Xamarin Cross-Platform components box.

Debugging:
  1. Make sure the debugger selected in the project's properties is Xamarin, in order to successfully debug.

      2. Make sure your Hyper-V instance setting for Processor -> Compatibility "Migrate to a physical computer..." is selected.



In addition, make sure you follow the Visual Studio Output window under Xamarin and Xamarin Diagnostics, to be aware of any problems.



In order to debug an Adroid device, remember that you must enable the Developer Options mode, which is achieved by clicking 7 times in Build Number under the About entry. There, you must select "USB Debugging".

To view logs from the Android side, you can issue the following
in the Android Adb Command Prompt (the one to the right of Android SDK icon in the visual studio Xamarin toolbar).

adb logcat -d > logcat.txt

Monday, September 26, 2016

Permanently run Visual Studio in admin mode


Right click in your VS shortcut -> Properties -> Advanced -> Run as administrator.


Wednesday, August 24, 2016

Unable to debug Silverlight Application

I was unable to successfully debug my silverlight application until I came across the this answer from StackOverflow (worth checking the one above it as well, although it was the 2nd that fixed my issue).

Monday, August 22, 2016

Fixing error Silverlight.Csharp.Targets was not found

If you are facing build errors where some (likely projects that rely on Silverlight) of your projects are not being loaded into the solution, here's what worked for me (I used Visual Studio 2015, but the same should work for 2010):

(The solution is based on what was proposed here).


  1. Go do Programs and Features, select your Visual Studio installation, and run a Modify (if not present, you may be forced to go with Repair). Check the checkbox that mentions Silverlight
  2. Afterwards, when reopening Visual Studio to see if the project(s) is/are correctly loaded - you will be prompted to install Silverlight Developer - the pop-up will include the download link as well. Download, install, and you are (hopefully) done.

Wednesday, August 17, 2016

Visual Studio Web Development Extensions

http://webtooling.visualstudio.com/extensions/web-development

Going up one level, you get into http://webtooling.visualstudio.com, that overviews what visual studio offers in covering the technologies being used today.

P.S.: PowerTools has historically given me freezing problems, making it not an option.

P.S. II: The power tools issue mentioned above is gone after moving to Windows 10 (recommend, by the way, seems to give benefits on many other fronts, like Xamarin development, for example).

Wednesday, August 10, 2016

Javascript learning resources

I found in Felix Kling's stackoverflow profile 3 really interesting links about learning javascript.

Eloquent JavaScript (free online edition)
You don't know JavaScript (free online edition)
quirksmode.org - especially DOM and event handling

I was surprised to find the sources look very good and are free.

Tuesday, August 9, 2016

Linq OrderBy vs ThenBy - composite ordering calling OrderBy multiple times over is not what you want to do

Do not apply multiple order by linq operators one over the output of the other - the results will not be what you want.



var sequence = new[]
{
    new {a = 10, b = 20, c = 301, d = 1},
    new {a = 1000, b = 50, c = 30, d = 0},
    new {a = 50, b = 10, c = 1130, d = 1},
    new {a = 5, b = 0, c = 130, d = 0},
};

var o1 = sequence.OrderBy(s => s.a);
var o2 = sequence.OrderBy(s => s.b);
var o3 = sequence.OrderBy(s => s.c);

var fluentSyntaxSort = sequence.OrderBy(s => s.a).OrderBy(s => s.b).OrderBy(s => s.c);

var thenBy = sequence.OrderBy(s => s.a).ThenBy(s => s.b).ThenBy(s => s.c);

Console.WriteLine("3 order bys EACH ON THE ORIGINAL sequence");
foreach (var o in o1)
    Console.WriteLine(o);
foreach (var o in o2)
    Console.WriteLine(o);
foreach (var o in o3)
    Console.WriteLine(o);

Console.WriteLine("\nFluent syntax:");
foreach (var o in fluentSyntaxSort)
    Console.WriteLine(o);

Console.WriteLine("\nThenBy:");
foreach (var o in thenBy)
    Console.WriteLine(o);

Output:


Monday, August 1, 2016

.NET's built in methods to convert between distinct numeric representations (supports 2, 8, 10 and 16 only)

Here's something that few seem to know about, but that more than often we are in need of: the .NET's Convert methods can convert to/from the following numeric representations 2, 8, 10, 16.

            var binary = Convert.ToString(30, 2); // 11110
            var bits = binary.ToCharArray().Select(c => byte.Parse(c.ToString())); // a collection of the bits stored in 'binary' above
            var hexa = Convert.ToString(100, 16); //64
            var octa = Convert.ToInt64(12.ToString(), 8); //10 (decimal representation of 12 in base 8 = 10)

Thursday, July 28, 2016

System.Console Right-To-Left Writing

I accidentally revisited this topic today, and was able to answer my "Can .NET's System.Console be configured to print Right To Left?" question from a year ago - here.


Thursday, July 7, 2016

Dealing with EF Connection Timeouts/Connection lost issues using Connection Resilience/Retry Logic built in support (EF onwards)

Upon facing connection timeouts/connection lost issues in working with EF, instead of trying brute force methods such as wrapping your connection instance in a for statement or alike, the best practice is to use Connection Resilience/Retry Logic (EF onwards) support, which provides more sophisticated retry strategy implementations, shipped in.

Rethrowing exceptions to preserve the stack while changing the exception's message?

A (deleted) question I posted yesterday, on the topic.

http://stackoverflow.com/q/38228681/1219280



Sunday, July 3, 2016

Adding objects from different schemas using Entity Framework with Oracle

At first, it looked like there was is no Entity Framework support to adding objects (say, tables) created in schemas other than the one used in the database connection.

But turned out it is possible. Stackoverflow will list some "workarounds" , but there is no need to - because SO lists one post that gives the exact solution for this problem, and it looks great.

Summarizing it:

You can either add more schemas under which search for objects to add during the creation of the Ado.net object (while adding the connection) - or by modifying the existing connection in the Server Explorer in Visual Studio.



If you are adding the ADO.NET object, you need the connection definition window above - and if you already have your ADO.NET object there, go to Visual Studio -> View -> Server Explorer, search for the desired connection under Data Connections and right click it. Then choose Modify. You will get the window above.

The steps to follow are:
  1. Select the Filter tab
  2. Click the 3 dots singled out, and add the schemas you want to be included by EF when searching for objects to add to the model.
  3. After you are done with step 1, click the Update button singled out in the screenshot.
That's it. You can right click your edmx file, click Update Model From Database, and you will now have, under Tables, the tables listed by their schema.

Tuesday, June 7, 2016

Deep clone example

Deep-cloning example:

 public class RechivHafrasha : IEqualityComparer<RechivHafrasha>
    {
        public decimal Schum { getset; }
        public decimal? Shiur { getset; }
 
        //public int? Status { get; private set; }
        public int Sug { getset; }
 
        public decimal Sachar { getprivate set; }
        public string MisparMezaheReshuma { getset; }
 
        public string MisparMezaheReshumaKodem { getset; }
 
        public RechivHafrasha()
        {
        }
 
        public RechivHafrasha(decimal schumHafrasha, decimal? shiurHafrasha, /*int? status,*/ int sugHafrasha, decimal sachar, string misparMezaheReshuma, string misparMezaheReshumaKodem)
        {
            Schum = schumHafrasha;
            Shiur = shiurHafrasha;
            //Status = status;
            Sug = sugHafrasha;
            Sachar = sachar;
            MisparMezaheReshuma = misparMezaheReshuma;
            MisparMezaheReshumaKodem = misparMezaheReshumaKodem;
        }
 
        /*
        * לצורך השוואת בין רשומות מאוחדות, כדי לא לשלוח כפילויות לפירעון
        */
 
        public string ID
        {
            get
            {
                return string.Format("{0}{1}{2}{3}{4}{5}",
                    this.Schum,
                    this.Shiur,
                    this.Sug,
                    this.Sachar,
                    this.MisparMezaheReshuma,
                    this.MisparMezaheReshumaKodem);
            }
        }
 
        public bool Equals(RechivHafrasha x, RechivHafrasha y)
        {
            return x.ID.Equals(y.ID);
        }
 
        public int GetHashCode(RechivHafrasha obj)
        {
            return obj.ID.GetHashCode();
        }
 
        public RechivHafrasha ShallowCopy()
        {
            var shallowCopy = this.MemberwiseClone() as RechivHafrasha;
            return shallowCopy;
        }
 
        public override string ToString()
        {
            return string.Format("[{0},{1},{2},{3},{4},{5}]", Schum, Shiur, Sug, Sachar, MisparMezaheReshuma, MisparMezaheReshumaKodem);
        }
    }
 
 
 
 
            List<RechivHafrasha> list = new List<RechivHafrasha>
            {
                new RechivHafrasha(10, 0.5m, 1, 1000, "7d2d272d7268326""2d2862g2g2d"),
                new RechivHafrasha(100, 0.7m, 2, 900, "7d2d272d7268326""2d2862g2g2d"),
                new RechivHafrasha(1000, 0.2m, 5, 80, "7d2d272d7268326""2d2862g2g2d"),
                new RechivHafrasha(10000, 0.41m, 4, 500, "7d2d272d7268326""2d2862g2g2d"),
                new RechivHafrasha(100000, 0.11m, 1, 15, "7d2d272d7268326""2d2862g2g2d")
            };
 
            List<RechivHafrasha> c1 = list.ToList();
            List<RechivHafrasha> c2 = new List<RechivHafrasha>(list);
            List<RechivHafrasha> c3 = list.ConvertAll<RechivHafrasha>(z => z.ShallowCopy());
 
            list[1].Schum = 0;
 
            Console.WriteLine(string.Join(",\n", list));
            Console.WriteLine();
            Console.WriteLine(string.Join(",\n", c1));
            Console.WriteLine();
            Console.WriteLine(string.Join(",\n", c2));
            Console.WriteLine();
            Console.WriteLine(string.Join(",\n", c3)); 
Output:

Sunday, May 22, 2016

Improving performance in working with EF



I stumbled across a SO post about performance, where the main hindrance was Entity Framwork/DB operations.

Here's a summary of the suggested approaches for performance improvement:

  •  Using Dapper or raw ADO.NET components.
  • Disabling EF change auto detection and validation on save flags.
  • Using BulkInsert
  • Instead of adding new entities inside a loop, collect all the entity objects to be added into a collection - and one you are finished issue a single [entity].AddRange(collection) to push all the new entities into the EF object (and afterwards performing a SaveChanges). It is stated that this is performance-wiser.
I myself was familiar with the 2nd and 3rd suggestions. Should give Dapper and AddRange a try.

Some performance comparison tests for the above can be found in the web, here is a nicely presented one.

See also Performance considerations for EF 4, 5 and 6.

Monday, April 4, 2016

Web Development Fundamental Concepts

I found today concise yet very good descriptions of fundamental concepts in web development, by the Mozilla Developer Network.
A must for any web developer (I stumbled across this way too late, I admit).

https://developer.mozilla.org/en-US/Learn/Common_questions

You will find great articles clarifying what is the internet, a web server, web pages, web sites and more.

Update:
Web Fundamentals from Google.

Monday, February 22, 2016

C# Regex Positive Lookbehind

An example of positive lookbehind (Matches a group before the main expression without including it in the result):

            var str = @"System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ApplicationException: MQException is caught. Reason code: 2033, completion code: 2. ---> CompCode: 2, Reason: 2033
                       --- End of inner exception stack trace ---
                       at Multiconn.ZZZ.Web.Services.Port.EndProcess(IAsyncResult asyncResult)
                       at Multiconn.ZZZ.Demo.K.M.E(IAsyncResult asyncResult, WsEsParams1Response& result1, MyType result3)
                       --- End of inner exception stack trace ---";

            Regex r = new Regex(@"(?<=Reason code: )\d+");

            foreach (Match m in r.Matches(str))
                Console.WriteLine(m.Value);

Sunday, February 21, 2016

Impefect Content-Type http response headers

Have you heard about perfect and imperfect http headers ?

Well, I just did.
Take a look here, a topic that developed from here.