Wednesday, June 21, 2017

IIS problems

Some commands to help troubleshoot windows hosted web applications 

URL reservations: 

netsh http show urlacl
netsh http delete urlacl url=https://+:443/
netsh http add urlacl url=https://+:443/ user=everyone

Firewall

netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=443 remoteip=any action=allow

Certificates

delete cert
netsh http delete sslcert ipport=0.0.0.0:44347

Add cert
netsh http add sslcert ipport=0.0.0.0:44347 certhash=d4e23174e12ec96e8d3b7cacf7a4f83da9c08e12 appid={214124cd-d05b-4309-9af9-9caa44b2b74a}

Network 
netstat -a -n -o | findstr 443
netstat -ab  | findstr 443

Apppool
Look at the app pools status
c:\Windows\System32\inetsrv\appcmd.exe list apppools

Check event viewer

In my case i found the following error
An error occurred while using SSL configuration for endpoint 127.0.0.1:443.  The error status code is contained within the returned data.


Monday, June 12, 2017

Git tips

git config push.default current
Pushing to the server with he same branch name automatically

Some usefull aliases 
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.brb branch -b
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'

Sunday, June 4, 2017

DateTime parsing in .NET

Good percentage of bugs and test failures comes from the way date is parsed.
Popular example, a unit test is created, runs on local machine without any problems, then on the test agents, sometimes it passes, and other times fails.
Usually this happens when there is a date stored in UTC for example, then we parse it without specifying date kind, which may change the time value in some cases.

Example below for different ways to parse date, and the effect of that on a time comparison.
Whenever the parsed date kind is local, and the time is adjusted, the comparison is not as we expect.
In the below examples, i am comparing the dates checking if less than 8:40 and expecting all to be true. Some of the them the comparison was giving false, due to time adjustment.

namespace DateParsing
{
    using System.Globalization;
    using System.Xml;

    class Program
    {
        static void Main(string[] args)
        {
            Parse("2017-06-01T08:33:49Z");
            Parse("2017-06-01T08:33:49");
            Parse("2017-06-01T08:00:00.0000000Z");
            ParseByFormat("2017-06-01 08:33:49", "yyyy-MM-dd HH:mm:ss");
            Console.ReadKey();
        }

        private static void Parse(string dateString)
        {
            Console.WriteLine("========== input string is: {0} ===============", dateString);
            var date1 = DateTime.Parse(dateString);
            PrintDate(date1, "Using parse, no date style");
            var date2 = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            PrintDate(date2, "Using parse, Adjust to universal style");
            var date3 = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
            PrintDate(date3, "Using parse, Assume universal style");
            var date4 = XmlConvert.ToDateTime(dateString, XmlDateTimeSerializationMode.Utc);
            PrintDate(date4, "Using XmlConvert, SerializationMode UTC");
        }

        private static void ParseByFormat(string dateString, string format)
        {
            Console.WriteLine("========== input string is: {0} ===============", dateString);
            var date1 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
            PrintDate(date1, "Using parse exact, no date style");
            var date2 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            PrintDate(date2, "Using parse exact, Adjust to universal style");
            var date3 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
            PrintDate(date3, "Using parse exact, Assume universal style");
            var date4 = XmlConvert.ToDateTime(dateString, format);
            PrintDate(date4, "Using XmlConvert, SerializationMode not specified");
        }

        static void PrintDate(DateTime date, string format)
        {
            DateTime x = new DateTime(2017, 06, 01, 08, 40, 00);
            Console.WriteLine("Date is {0}, date kind is {1}, {2}", date, date.Kind, format);
            Console.WriteLine("{0} < than {1} is {2} ", date, x, date < x);
        }
    }
}


========== input string is: 2017-06-01T08:33:49Z ===============
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, no date style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using parse, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01T08:33:49 ===============
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse, no date style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01T08:00:00.0000000Z ===============
Date is 01/06/2017 09:00:00, date kind is Local, Using parse, no date style
01/06/2017 09:00:00 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:00:00, date kind is Utc, Using parse, Adjust to universal style
01/06/2017 08:00:00 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:00:00, date kind is Local, Using parse, Assume universal style
01/06/2017 09:00:00 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:00:00, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:00:00 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01 08:33:49 ===============
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse exact, no date style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse exact, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse exact, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using XmlConvert, SerializationMode not specified
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

Wednesday, May 31, 2017

string.Format with params trap

Lately i have seen this code

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }

The code compiles and runs without problems, and if p is passed as a single string, would work fine. If someone knows that it should be a single string.
If someone else is using the same method he might fall into a trap assuming that the params is optional, which would also compile but would give exception during runtime.

Ex:
        static void Main(string[] args)
        {
            var message = "Error occurred, details: {0}";
            LogError(message, "details");
            LogError(message);
        }

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }

It would compile and run, but would give an error

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Another developer might assume that he can pass multiple params, which would only take the first one and ignore the others

Ex:
        static void Main(string[] args)
        {
            var message = "Error occurred, details: {0}";
            LogError(message, "details");
            LogError(message, "details", "more details ");
        }

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }


Would output:
Error occurred, details: details
Error occurred, details: details

Registering all ocx files

I had an old app that is using windows controls ocx libraries, like comctl32.ocx, comdlg32.ocx And others
The program was complaining about missing comctl32.ocx, then i did register it with the below command, running it in elevated command prompt 
regsvr32 c:\Windows\SysWOW64\comctl32.ocx

Starting the app again it complained about another missing ocx. 


In that case it might be better to register all the ocx files in the SysWOW64 folder by running the below command

forfiles /p "c:\Windows\SysWOW64" /m *.ocx /c "cmd /c regsvr32 @file"

Monday, January 16, 2017

Namespace and extending twitter bootstrap


Using customized bootstrap styles can sometimes conflict with other bootstrap styles that are not customized, for example this could happen if you have a frame and you are loading a web component inside of it inside a page.

Possible solution to avoid conflicts is to namespace twitter bootstrap

Lets take example html with bootstrap styling

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <ul class="nav nav-pills" role="tablist">
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
        <li role="presentation"><a href="#">Profile</a></li>
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

To namespace bootstrap styles:
Create a new less file, and paste the below inside. "mybt" below is the custom namespace i am using

.mybt {
    @import "bootstrap-3.3.7/less/bootstrap";
}

After that compile this less file
lessc mybt.less mybt.css

And now after referencing mybt.css the html would use mybt and the bootstrap styles like below

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="mybt.css">
</head>
<body>
    <ul class="mybt nav nav-pills" role="tablist">
        <li role="presentation" class="mybt active"><a href="#">Home <span class="mybt badge">42</span></a></li>
        <li role="presentation" class="mybt"><a href="#">Profile</a></li>
        <li role="presentation" class="mybt"><a href="#">Messages <span class="mybt badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

Another option is to extend bootstrap styles
to extend it, create new less file with below:

@import "bootstrap-3.3.7/less/bootstrap";

.my-nav:extend(.nav) {}
.my-nav-pills:extend(.nav-pills) {}
.my-badge:extend(.badge) {}

Extending will work if you have only few styles that you are using.

Sunday, January 8, 2017

Setup Blocked By Group Policy

I was trying to setup my printer, cannon MG3650 on my computer, everything was going well, setup has finished, but i wasn't able to print.
I opened printers, to find the status of the printer as following "Setup Blocked By Group Policy"
Searching online i found couple of posts to change the group policy and how to check the resultant policy.
I checked the group policy setting by doing the below
Start > Run, type in gpedit.msc and press OK. Go to Computer Configuration > Administrative templates > System > Device Installation > Device Installation Restrictions
Made sure that all was not configured.
I then checked the resultant policy
Start > Run, type in rsop.msc and there the device restriction was set as enabled.
I searched on how to change this policy, couldn't find a place to change it.

Then i looked into the registry. by doing Start > Run, type in regedit and press Ok. I found the below key:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\DeviceInstall\Restrictions

And i found a key inside called DenyUnspecified

I removed this key, then checked the resultant policy, the restriction wasn't enabled. Repeated the printer setup again, and this time it finished successfully and it worked fine after. 

Friday, December 16, 2016

Custom cast support for objects


We are working with Hashtables a lot in a project, where we need to convert objects into hashtable and from hashtables

A way to do this is by adding custom casting in the class to the class type, and to add a method to convert to hashtable.

Example

   public class MyClass
    {
        public string Name;
        public int Id;
        public string Description;

        public static explicit operator MyClass(Hashtable hashtable)
        {
            MyClass mt = new MyClass();
            mt.Description = hashtable["Description"].ToString();
            mt.Id = int.Parse(hashtable["Id"].ToString());
            mt.Name = hashtable["Name"].ToString();
            return mt;
        }

        public Hashtable ToHashtable()
        {
            var hashtable = new Hashtable();
            hashtable["Name"] = "name";
            hashtable["Id"] = 1;
            hashtable["Description"] = "description";
            return hashtable;
        }
    }
Then simply we can do something like:
Hashtable hashtable = myClass.ToHashtable();

And 
MyClass casted = (MyClass) hashtable;
Example usage:
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass
            {
                Description = "description",
                Id = 1,
                Name = "name"
            };

            Hashtable hashtable = myClass.ToHashtable();
            Console.WriteLine("Hashtable: ");
            Console.WriteLine(hashtable["Name"]);
            Console.WriteLine(hashtable["Id"]);
            Console.WriteLine(hashtable["Description"]);


            MyClass casted = (MyClass) hashtable;
            Console.WriteLine("MyClass: ");
            Console.WriteLine(casted.Id);
            Console.WriteLine(casted.Description);
            Console.WriteLine(casted.Name);

            Console.ReadKey();
        }

Wednesday, December 14, 2016

Error CA2000 call System.IDisposable.Dispose on object

My code looked like


this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));

and i was getting the below style cop error

Severity Code Description Project File Line Suppression State
Error CA2000 In method 'MyMethod()', call System.IDisposable.Dispose on object 'new HttpResponseMessage(HttpStatusCode.OK)' before all references to it are out of scope. Catalog.Common.UnitTests code.cs 72 Active

To overcome this, if it is in single method, you can suppress the error

[SuppressMessage("Microsoft.Reliability",
                 "CA2000:DisposeObjectsBeforeLosingScope",
                 Justification = "Your reasons go here")]
OR you can change the code to be like below

this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.Run(() => { return new HttpResponseMessage(System.Net.HttpStatusCode.OK); }));

Wednesday, March 11, 2015

Recovering partition after initializing by mistake

I recently re installed windows, i have 2 drives, i have removed the second drive to keep the data safe.
After the installation i have connected my hard drive. I didn't find the drive appearing in file explorer. When i opened Computer Management-> Disk Management, i received message saying that the drive is not initialized, so i followed the steps to initialize it, thinking that this will restore the drive and the data, then i found that the drive now has the state of un-allocated and the next available options is to create volumes, then i realized that i may have destroyed my data.
Looking online i found some forums talking about something similar and that MiniTool Partition wizard have recovery wizard that can recover the drive
http://www.sevenforums.com/hardware-devices/288692-disk-1-unknown-not-initialized-unallocated.html

I gave it a try, downloaded the free tool from http://www.partitionwizard.com/download.html, then selected the drive, started the recovery wizard, did the quick scan, and voila, the partition was recovered. That was really great tool that saved my data.