Tuesday, December 7, 2010

Notepad - Right to Left

Today, while typing in notepad I faced a strange problem, my typing order just got reversed. I was typing fro m left to write and it changed to right to left. After some googling i found that it  is due to s accidental pressing of notepad shortcut Cntrl+RightShift.

So if You want to right to left in Notepad then use shortcut:
Cntrl+RightShift Key

if You want to left to right in Notepad then use shortcut:
Cntrl+LeftShift Key

As per following Wiki Link:
http://en.wikipedia.org/wiki/Notepad_%28software%29
Notepad supports both left-to-right and right-to-left based languages, and one can alternate between these viewing formats by using the right or left Ctrl+Shift keys to go to right-to-left format or left-to-right format, respectively.

Monday, December 6, 2010

LINQ - Beginners Tutorial-2

Here we will start using some advance operators and will write code as lambda expressions as well as comprehension query.

Input:
string[] names = { "Ajay", "Vijay", "Karan", "Farhan", "Pooja", "Geeta", "Dia" };

Lambda Expression:
IEnumerable tp = names.Where(n => n.EndsWith("a"))
                            .OrderBy(n=> n.Length)
                            .Select(n => n.ToUpper());


Comprenesion Query:
IEnumerable tp = from n in names
                         where n.EndsWith("a")
                         orderby n.Length
                         select n.ToUpper();  
 

Enumerate result:
foreach (string str in tp)
{
     Console.WriteLine(str);
}


Output:
DIA
POOJA
GEETA

Main Points:
1. We have option to use either lambda expressions or comprehension query to get the desired result.
2. Compiler converts comprehension query to lambda expression.

Sunday, December 5, 2010

LINQ - Beginners Tutorial-1

What is LINQ?
LINQ stands for Language integrated Query, that allows us to query local object collection or remote data source.

Using LINQ we can query any collection implementing IEnumaerable interface. To use LINQ in code we need to use Sysrtem.Linq namespace.

First Example:
string[] names = { "Ajay", "Vijay", "Karan", "Farhan", "Pooja", "Geeta" };
IEnumerable tp = names.Where(n => n.EndsWith("a"));
foreach (string str in tp)
{
Console.WriteLine(str);
}


Here we have taken a string array in first line of code, fnames that contains 6 names.
In second line of code we write a Linq to get the names ending with "a".

Output:
Pooja
Geeta

Main Points:
1. Linq data has two parts, sequence and elements. Here names is a sequence and array members are elements.
2. Linq doesn't alter the input sequence. So result will always be in the order it was input.
3. Linq always return an IEnumerable result.
4. "n => n.EndsWith("a")" is a lambda expression that filters the result for us.

Monday, September 20, 2010

Enable a hard disabled Excel 2003 Add-In

Follow following steps to enable a hard disabled Excel 2003 Add-In

1. Launch Excel.
2. On the Help menu, click About Microsoft Office Excel.
3. Click Disabled Items.
4. Select the add-in and click Enable.
5. Click Close.

Enable a hard disabled Excel 2007 Add-In

Follow following steps to enable a hard disabled Excel 2007 Add-in.

1. Launch Excel.
2. In the application, click the Microsoft Office Button. Click Excel Options button.
3. In the categories pane, click Add-ins. In the Manage box, click Disabled Add-ins, and then click Go.
4. Select the add-in and click Enable.
5. Click Close.

Friday, June 11, 2010

How Platform target: switch works?

Platform Target
Platform target switch is used to generate assemblies for 32 bit, 64 bit or for both (that can be used on 32 as well as 64 bit machine)

Switch:
x86: Generate assemblies for 32 bit platform.
x64: Generate assemblies for 64 bit platform.
Any CPU : Generate assemblies for 32 bit as well as 64 bit platform.

Example:
Lets suppose I have some exe's and dll's generated using these switches.

EXE                                 DLL                                       Switch
Myx86.exe                       Myx86.dll                                - x86
Myx64.exe                       Myx64.dll                                - x64
MyAnyCPU.exe               MyAnyCPU.dll                       - Any CPU

Running exe on 32 bit machine:

Myx86.exe will act as 32 bit application and can refer Myx86.dll and MyAnyCPU.dll but will give exception for Myx64.dll

Myx64.exe will give an exception.

MyAnyCPU.exe will act as 32 bit application and can refer Myx86.dll and MyAnyCPU.dll but will give exception for Myx64.dll

Running exe on 64 bit machine:

Myx86.exe will will act as 32 bit application and can refer Myx86.dll and MyAnyCPU.dll but will give exception for Myx64.dll

Myx64.exe will act as 64 bit application and can refer Myx64.dll and MyAnyCPU.dll but will give exception for Myx86.dll

MyAnyCPU.exe will act as 64 bit application and can refer Myx64.dll and MyAnyCPU.dll but will give exception for Myx86.dll

Thursday, June 10, 2010

Window Form Event Order

Application Startup Events

Control.HandleCreated

Control.BindingContextChanged

Form.Load

Control.VisibleChanged

Form.Activated

Form.Shown

Application Shutdown Events

Form.Closing

Form.FormClosing

Form.Closed

Form.FormClosed

Form.Deactivate

Monday, May 31, 2010

Thread Safe Singleton Pattern

namespace Organization
{
    class Employee
    {
        // Cretae a static object of the class   
       private static Employee _employee = null;
       private static object padlock = new object();
       
        // This method will  be called whenever an instance of the class will be needed
        public static Employee GetInstance()
        {
     lock(padlock)
     {
            if (_employee == null)
            {
                _employee = new Employee();
            }
     }
     return _employee
}
      
        // Default constructor is specified as private, so that it coldnot be used from outside
        private Employee()
        {
        }
    }
}

Singleton Design Pattern

namespace Organization
{
    class Employee
    {
        // Cretae a static object of the class 
        private static Employee _employee = null;
     
       // This method will  be called, whenever an instance of the class will be needed
        public static Employee GetInstance()
        {
            if (_employee == null)
            {
                _employee = new Employee();
            }
            return _employee;
        }

       // Default constructor is specified as private so that it could not be used from outside
        private Employee()
        {
        }
    }
}

Thursday, May 27, 2010

Saving User Preferences in C#.net Application

Preview:
In some applications we want to store the user preferences, like size and location, of the .net application. Not even store the user preference we required to give some option to user to change his preferences.

Where to store:
There are many options to achieve this. Either we can use XML file to store these settings in and can read these settings while launching of the application or we can use settings file that is inbuilt XML file to store user settings.

XML is a better option if we want control those options at the customer end without launch of the application. Also XML can be stored on any custom path either opted by developer or opted by user to store things.

Settings file is can't be customized, once it is deployed on user's machine, neither by user nor by developer. It is also an XML file but inbuilt in project. Settings store in this file support a vast range of data types. We are using here string and Boolean type only.

Settings File:
Settings file is there in the project itself. You can open the settings file either from the Properties/Settings.settings or you can open it from project properties and settings tab. It has a very friendly UI. We can add the settings easily into this settings file. Figure 1.1 shows the settings file from the Properties folder and Fig 1.2 shows the settings file opened from project>>properties>>settings.













Fig 1.1 Properties/Settings.settings














Fig 1.2  project properties and settings tab


How to load settings:
Here is the method that can be written while loading of the application to set the location ans the start position of it. This is a well documented and self explanatory method. We have handled the FirstLaunch of the application using an Boolean variable "FirstLaunch ". If application is launched first time then set thelocation to center of screen.



















Fig 1.3  Load settings

How to update settings: 
When user has finished the changed in the application or when he is closing the application we can update the settings using following method. Saving all the settings (Size and Location here) and set the FirstLaunch to false.















Conclusion:
Here we have seen that it is very easy to use the Settings file in the .net application. How we can accommodate the settings file in the project for reading and for updating the user preferences.

Tuesday, May 25, 2010

The process account used to run ASP.NET must have read access to the IIS metabase

If you get following error while deploying the WCF service:

Error: The process account used to run ASP.NET must have read access to the IIS metabase (e.g. IIS://servername/W3SVC).
Follow following command to overcome this problem:

Monday, May 10, 2010

Copy files and folder from source location to destination location

Copy files/folders from old folder to new Folder recursively.
private static void MoveAll(string pobjSource, string pobjTarget)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(pobjTarget) == false)
{
Directory.CreateDirectory(pobjTarget);
}
foreach (string filename in Directory.GetFiles(pobjSource, "*.*"))
{
File.Copy(filename, Path.Combine(pobjTarget, Path.GetFileName(filename)));
}
// Copy each subdirectory using recursion.
foreach (string objSourceSubDir in Directory.GetDirectories(pobjSource))
{
MoveAll(objSourceSubDir, Path.Combine(pobjTarget, Path.GetFileName(objSourceSubDir)));
}
}

Wednesday, March 24, 2010

Static Readonly vs Constant

Static ReadOnly >> Static readonly is a class level variable that can't be accessed using the class object. It's value can bedefined at the runtime using any expression or any run time variable only in the static constructor of the class.

Constant >> Constants are also class level variables as they are implicitly static but they can be set only once (at the time of declaration only). You can't set a constant at the runtime.

If you want to define your field at design time then you must use constant but if the value of the field is decided at the runtime then you have the only option to use Static readonly.

Generating incremental file name

Following code could help you in getting Incremental or Unique file name.

If file abc.txt already exist than following function will return abc1.txt, if abc1.txt exists than abc2.txt and so on.

public static string GetIncrementalFilename(string FileName)
{
int count = 0;
string Name = "";

if (System.IO.File.Exists(FileName))
{
System.IO.FileInfo f = new System.IO.FileInfo(FileName);
if (!string.IsNullOrEmpty(f.Extension))
{
Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
}
else
{
Name = f.FullName;
}

while (File.Exists(FileName))
{
count++;
FileName = Name + count.ToString() + f.Extension;
}
}
return FileName;
}

How to truncate leading zeros from a String?

The common functionality a .Net developers uses is to extracting integer/numeric value from a string having leading ZEROS.

Suppose we have a a string "00025" and we want to get only 25 of it.

Example:
Int32 intOutValue;
bool blnParsed;
String strNumber = "00025";

blnParsed= Int32.TryParse(strNumber , out intOutValue);

Output:
blnParsed=true
intOutValue = 25

Convert, Parse and TryParse Methods - Comparing String to Number Conversion Methods

.Net provides several different ways to extract integers from strings. In this article, I will present the differences between Parse, TryParse and ConvertTo.

Parse: This function takes a string and tries to extract an integer from it and returns the integer. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException. Finally, if the string value is null, it throws ArgumentNullException.

Int32 intValue = Int32.Parse(str);

Convert: This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception. If the string is not a numerical value, the method throws FormatException. If the extracted number is too big, it throws OverflowException.

Int32 intValue = Convert.ToInt32(str);

TryParse: This function is new in .Net 2.0. Since exception handling is very slow, TryParse function returns a boolean indicating if it was able to successfully parse a number instead of throwing an exception. Therefore, you have to pass into TryParse both the string to be parsed and an out parameter to fill in. Using the TryParse static method, you can avoid the exception and ambiguous result when the string is null.

bool isParsed = Int32.TryParse(str, out intValue);

Examples:

string str1 = "1234";
string str2 = "1234.65";
string str3 = null;

string str4 = "999999999999999999999999999999999999999999";
int intValue;
bool isParsed;

intValue= Int32.Parse(str1); //1234
intValue= Int32.Parse(str2); //throws FormatException
intValue= Int32.Parse(str3); //throws ArgumentNullException
intValue= Int32.Parse(str4); //throws OverflowException

intValue= Convert.ToInt32(str1); //1234
intValue= Convert.ToInt32(str2); //throws FormatException
intValue= Convert.ToInt32(str3); //0
intValue= Convert.ToInt32(str4); //throws OverflowException

isParsed= Int32.TryParse(str1, out intValue); //isParsed=true 1234
isParsed= Int32.TryParse(str2, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str3, out intValue); //isParsed=false 0
isParsed= Int32.TryParse(str4, out intValue); //isParsed=false 0