The Shift trick!

Though I am really ashamed of this late realization ,but till date I never knew how to run a command prompt to the present directory path. So for lesser mortals like me,this is how you do it. As simple as this.

All you need to do is press SHIFT while right clicking on a empty space in the window. And lo you have it ! You will get the option “Open command window hereSmile.

 

image

TimezoneInfo and DateTime

Until recently what used to be a headache for most of us is finally put out of misery by MS after framework 3.5.Yes there is code to finally get the datetime based on a given timezone and back as even i stumbled upon it a few months back. For eg if you have concerned about the various timezones and their datetimes in US which has several as follows.

//Eastern Standard Time (GMT-05:00) Eastern Time (US & Canada)
//Central Standard Time (GMT-06:00) Central Time (US & Canada)
//Mountain Standard Time (GMT-07:00) Mountain Time (US & Canada)
//Pacific Standard Time  (GMT-08:00) Pacific Time (US & Canada)
//Alaskan Standard Time (GMT-09:00) Alaska
//Hawaiian Standard Time (GMT-10:00) Hawaii
//US Mountain Standard Time (GMT-07:00) Arizona

you can infact convert a DateTime to any other datetime in the world by passing in the timezone they are located in and then you can convert them to UTC or to local and vice versa.Lots of interesting stuff that we can really make our hands dirty.All thanks to the new TimezoneInfo class that has been introduced.You can even get the TimeZoneInfo.BaseUtcOffset of a given location and then find out the difference between that place and local time or UTC for that matter.You can even add datetime offset to the UTC date and get the datetime of a given place.

Let look at an easy example of how we achieve this.

Code Snippet
  1. TimeZoneInfo timeZoneInfo;
  2. DateTime testdate = DateTime.Parse(“3/2/2011 1:00:00 AM”);
  3. DateTimeOffset offset;
  4. DateTime utcdate = testdate.ToUniversalTime();
  5. //Set the time zone information to US Mountain Standard Time -arizona
  6. timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“US Mountain Standard Time”);
  7. //Get date and time in US Mountain Standard Time
  8. DateTime dateTime = TimeZoneInfo.ConvertTime(testdate, timeZoneInfo);
  9. //Print out the date and time
  10. Console.WriteLine(dateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));
  11. //Mountain Standard Time
  12. timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“Mountain Standard Time”);
  13. //Get date and time in US Mountain Standard Time
  14. dateTime = TimeZoneInfo.ConvertTime(testdate, timeZoneInfo);
  15. ////Print out the date and time
  16. Console.WriteLine(dateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));
  17. //==============================================================================================
  18. //Set the time zone information to US Mountain Standard Time -est
  19. timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“Eastern Standard Time”);
  20. //Get date and time in US Mountain Standard Time
  21. dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo);
  22. //Print out the date and time
  23. Console.WriteLine(dateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));
  24. //================================================================================================
  25. //Set the time zone information to US Mountain Standard Time -cst
  26. timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“Central Standard Time”);
  27. //Get date and time in US Mountain Standard Time
  28. dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo);
  29. //Print out the date and time
  30. Console.WriteLine(dateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));
  31. //================================================================================================
  32. //Convert it back to UTC
  33. DateTime utcDateTime = dateTime.ToUniversalTime();
  34. //Print out the date and time
  35. Console.WriteLine(utcDateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));
  36. //==============================================================================================================================
  37. Datetime newOffsetDate = testdate.Add(timeZoneInfo.BaseUtcOffset);
  38. Console.WriteLine(utcDateTime.ToString(“yyyy-MM-dd HH-mm-ss t\\M”));

In case if you are wondering if there is support for DST,yes there is!I just made a sample app for you guys to play around and tinker with.(currently it has only US timezones) Click me to Download!

**Note—Always use UTC as the datetime to be stored in DB.

How to a run the ASP worker process under another user credential

Well i discovered this when i had to debug a service on a server on which i no permissions.Since it was a WCF call and was hosted on the IIS,i figured i needed a cheat.So this is what i did.Before i start with the details let me tell you the environments that i have been using.VS-Studio –2008 dotnet stack on Windows XP(sp3).And i was using IIS 5.1 on my machine which is an XP.So here goes.

First change the username and password in the machine.config under the processModel tag as shown below.

Code Snippet
  1. <system.web>
  2.     <processModel autoConfig="true" userName="username" password="******"/>
  3.     <httpHandlers/>

And i tried adding permission to the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files folder too.

That resulted in an error which gave an “Failed to access IIS metabase” error .So finally i figured MetaAcl tool needs to be downloaded from the following location

http://download.microsoft.com/download/5/7/3/57316f36-ded6-41f0-b694-8b0102ade818/metaacl.exe

This has a metaacl.vbs script which adds permission to the users.You need to add the file to the following folder c:\Inetpub\Adminscripts and then go this folder from the command prompt.Then run the command

c:\Inetpub\Adminscripts>cscript metaacl.vbs IIS://LOCALHOST/W3SVC
                                     mydomain\mydomainaccount RW

 

For more info go to the following KB article in MSDN.(http://support.microsoft.com/kb/326902)

Custom Configuration Designer!

There has many a time that i have posted on tools, that makes life so much simpler,in order that we can can have the extra time to fall in love with C#!So many of us hate to see Xml. Lets admit it ,not many are in awe of the beauty called xml and have burnt their fingers and are not comfortable with it.But next time when you hear that you have to create a custom configuration,don’t fear as we have tools in place to handle that.Thanks to the wonderful tool called Configuration Section Designer.I wouldn’t have ventured into it had not i made a silly mistake which took my entire day and i began to question the logic of creating all these with mere hands and why not get it automated?

You can install the Configuration Section Designer from here.Once you download the plug-in and install it ,it fits perfectly well with VS-2008. and VS-2010 folks ,your version is yet to be out.But once you have installed the Custom Configuration Designer you can see that you will get a project like the snapshot available for you to play around!

 

 

Once you have created the Custom Configuration ,you will get a default custom Section designer diagram which will be empty .Go to the properties and enter the values in Namespace and XmlSchemaNamespace as follows.

 

 

Once you are done naming your namespace as well as the xml schema namespace, you can go ahead and drag and drop the Config Section, Config Section Group, Configuration Collection  as well as Configuration Element.Here is sample that I have created.Its really simple isn’t it?

 

 

And you can add custom classes to the existing predefined system types for your elements as well as the attributes as well as mention if it required and to make a certain attribute Key for a Config Collection.And then all you need to do is build it .

 

Start a Windows Service Automatically after Install

Recently i came across a situation wherein i had to host a WCF service as a Windows Service.Only after i installed the service using InstallUtil –i  “assembly name”,did i realize my folly that i had a misconception regarding the term “Automatic”.What i am referring to the ServiceInstaller.StartType property.The main intent of this property is to start the Service automatically on start of Windows.

Code Snippet
  1. this.serviceInstaller1.StartType =
  2.      System.ServiceProcess.ServiceStartMode.Automatic;

 

So what do i do in run the service while installation?All you need to do add the event AfterInstall for the ServiceInstaller and then call the ServiceController from the eventhandler to start the service.

Code Snippet
  1. [RunInstaller(true)]
  2.     public partial class ServiceInstaller : Installer
  3.     {
  4.         public ServiceInstaller()
  5.         {
  6.             InitializeComponent();
  7.             ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
  8.             ServiceInstaller serviceInstaller = new ServiceInstaller();
  9.             //Specifies the type of account that should be used for the service.
  10.             processInstaller.Account = ServiceAccount.LocalSystem;
  11.             //Specifies the name of the service that is installed.
  12.             serviceInstaller.DisplayName = "Josh Service";
  13.             //Gives the description of the Installed service.
  14.             serviceInstaller.Description = "this is a Win Service";
  15.             //It tells which is the service that should be installed.
  16.             serviceInstaller.ServiceName = "MyService";
  17.             //It specifies the Start type of the service.
  18.             serviceInstaller.StartType = ServiceStartMode.Automatic;
  19.             this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
  20.             Installers.Add(processInstaller);
  21.             Installers.Add(serviceInstaller);
  22.         }
  23.  
  24.         void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
  25.         {
  26.             ServiceController sc = new ServiceController("MyService");
  27.             sc.Start();
  28.         }
  29.     }

 

Trivia:

The  service on local computer started and then stopped. Some Services stop automatically if they are not in use by another services or programs.”

You are all used to debugging and would have most likely than not used the “attach to process ” to debug your service implementation.But what do you do when you get Errors or have to debug the Windows Service installer itself?Bingo, we can always write “System.Diagnostics.Debugger.Launch();” in the OnStart() method and start debugging.Also you can write the errors to the EventLog or dump the Exception to a Log after putting in place a simple try catch!

Max Length of Command Line Arguments

What started out as an experiment,caught me by surprise in VS.The max length that i can pass to as a Command Line Arg is 4096 characters(4K).ie if i enter 11111…. 4196 times.After that Ting!

image

As i did my experiment in Win-7 this was the limit.More search on this topic led me to this Kb article.http://support.microsoft.com/kb/830473.

Summary:

1) If you run this application through command prompt:

If you are running Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. If you are running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters.

Please refer to this page for more information: http://support.microsoft.com/kb/830473/en-us

2) If you run this application by CreateProcess():

See the description of lpCommandLine parameter:

[in, out] The command line to be executed. The maximum length of this string is 32K characters. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters.

Please refer to this page for more information: http://msdn2.microsoft.com/en-us/library/ms682425.aspx

Uninstall IE9 Beta?

For those who are not happy with the IE9 Beta version(or for that matter any MS updates on your system) or have a issue/bug with the same can remove it from your WIN-7 with the following easy steps.

1.Go to the control panel and click on add/remove programs or go to run and hit “appwiz.cpl” and your list of programs pops on screen

2.Next you will find “View Installed Updates on your left hand side”.Click on it and you will find all the updates that you have made post your installation of the Windows 7.

image

3.Search through the updates (hint:it will be under Microsoft Windows separator) and click on uninstall to remove IE9 and you will be reverted to the default IE8.

image

**Note.You can also find the turn windows feature on/off on your left hand too.Use it sagaciously to install which ever feature turns you on/off!

image

Shortcuts in Visual Studio

As i have self professed earlier, i am a rather lazy coder.So i thought if i had a few newbie Dotnet brethren down there somewhere,who might find the following interesting.(Pros this is just a cakewalk for you!)I am just jotting down some of my favorite Dotnet shortcuts,though there are a few exhaustive hundreds of them.Here are some of them.

Ctrl + “.” ——–Adds the references, ie it opens the tag window and we can just hit Enter when it pops up.

image

Ctrl+K+C and Ctrl+K+U ——Comments and Uncomments code

Ctrl + ”-” and Ctrl +Shift + “-”————Used for navigating backward and forwards

Ctrl +X or Ctrl + L ————No need to select the entire line and do a shift+home or shift +end,stay anywhere on the line and just do it.It cuts the entire line.Similarly for Ctrl + C.

F7 ————-Changes from Design view to Code view or vice versa

F12 ———Go to definition

Shift + F12—— Find all references

Ctrl +M+L and Ctrl + M + O ——– Collapse and expand definitions.

Ctrl +Shift +V ——- To rotate the pasted items in the clipboard.ie you can get prevously copied snippets!only 20 at a time.

Ctrl + U and Ctrl +Shift +U—— to make the variables lowercase or uppercase.

Ctrl + R + E ——- if you have missed writing a property with prop + tab + tab,dont worry,first click on that line and type this shortcut which basically opens the encapsulate method smart window.

Alt + Ctrl + P —– Opens the Attach Process Window

Ctrl + D + P ——- View all the attached processes.You can individually detach each process here.Pretty useful especially if you want to detach one and add another

image

Alt + Ctrl + Q or Context  + Q——opens QuickWatch

Ctrl + K + D ———–Formats(sets proper indentation) the entire code in the current file .Or else just got to the last curly braces and just remove it and add it again.Voila its done!

Ctrl +Shift+F10 —– set the execution point to the current line

Ctrl +Shift+F9 —– removes all breakpoints

Alt + Ctrl + I —– command window

In addition to the hundreds of shortcuts that you have,we can create more by going to Tools->Options->Environment->Keyboard and then specify the shortcut that you want.My Fav one, is the one that we are all used to doing with the mouse..File.OpenContainingFolder(i just assigned the Alt+O)

image

Trivia..try running this from Run/Command Prompt..(try this at ur own risks).Later you can go to the prompt and try out other switches like ”devenv /nospash”.

“devenv.exe /resetuserdata”.(the switch kinda gives away the clue!)

For the exhaustive set of C# shortcuts download the pdf from the following location.

http://www.microsoft.com/downloads/details.aspx?FamilyID=92CED922-D505-457A-8C9C-84036160639F&displaylang=en

COPS….FxCop..!

This is going to be a small introduction to FxCop(FxCop is an application that looks into assemblies and recommends changes in design, localization, performance, and security improvements .Professionals who already know it,can please move over!When i first used this tool i didnt know that it would exist in the Microsoft Visual Studio tools.Now though it does ,thought it doesnt come installed and you would need to install it.It is located in Its located in  C:\Program Files\Microsoft SDKs\Windows\v6.0A\FXCop.(alternatively you can download from here..download).Once you have download it its pretty easy to start off.

Click on new project like shown below

image

Click on add target for analysis, and add the assembly you want to test for static code analysis.

clip_image002

And then click on Analyse button ..that it..over!You can see myriad rules which play havoc over your seemingly robust and secure code.This tool is meant for people who live the doctrine of MS rules and are ready to give their right hand for it!You can play with the various rules and ignore them if you want them.You can even create your own rules and analyse your code based on it.

image

But then we have the code analysis tool also!For the less informed,you can configure it when you click project properties and we have a tab for it which deals with it.

image

So whats the difference?They each have the same basic subset of rules they cover; but, each has some distinct rules that the other doesn’t catch.

OEM Vs Retail Copy of Windows

Recently i wanted to move my OEM copy of Windows 7 professional to another system as my laptop crashed,but the following were the startling relevelations.

OEM versions of Windows 7 are identical to Full License Retail versions except for the following:

– OEM versions do not offer any free Microsoft direct support from Microsoft support personnel

– OEM licenses are tied to the very first computer you install and activate it on

– OEM versions allow all hardware upgrades except for an upgrade to a different model motherboard

– OEM versions cannot be used to directly upgrade from an older Windows operating system

Some links to read more on the licensing issues.

http://social.answers.microsoft.com/Forums/en-US/w7install/thread/fae7b2ab-c530-45e6-aeb3-cc55cf7b9231

FAQS

http://oem.microsoft.com/script/ContentPage.aspx?pageid=552846#faq3