Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Monday, October 15, 2012

Visual Studio not automatically building application on pressing F5 key


Recently I was facing one issue with Visual Studio 2010. When I change some code in Visual Studio 2010 and hit F5, it is not building application and running old compiled version. Every time I want to debug an application, I have to first manually build application and then hit F5  key to debug my application. Usually visual studio automatically builds application on hitting F5 key.

I found interesting solutions from internet to resolve this issue. You need to open the Configuration Manager from Debug Dropdown or right click on Solution and open Configuration Manager Window. Now click on Build Checkbox.


Another solution would be useful if your Project is out of date or you have installed newer version. Go to Tool -> Option -> Project and Solutions -> Build and Run from Visual Studio. Now select “Always build” or “Prompt to build” option of “On Run, when project are out of date”.


Hope this small Tip might help you to fix this issue.

See Also –

Sunday, September 16, 2012

Logical Operators (Bitwise and Boolean) in C#


C# provides many operators which are widely used in various applications depending upon their use. This operators are very basic and everyone knows about it but few thing i wanted to highlight in this post which might not known to many developers. So In this post i will explain few important things about Logical and Bitwise AND/OR/XOR operators with example.

Logical AND (&&) Operator

Logical AND performs Boolean operation with two expression and returns true if both expressions are true and returns false if any one expression is false. If first expression is false then it will not check another expression and returns falseLet’s have a look on below code snippet.

int x = 3;
int y = 0;

if ((y > x) && (x / y > 0))
    Console.WriteLine("Logical AND Operation");


The above code will run and compile successfully. In above code second expression seems to throw Dividebyzero exception but first expression returns false so it will not evaluate second expression and assume that first expression is false so entire expression is false.


Logical OR (||) Operator

If we perform logical OR in above example, if first expression is true then it will not evaluate second expression. In logical OR any one expression must be true if first expression is true then others will be skipped.

Note - The disadvantage of logical operators are if second expression doesn’t evaluate then there might be possibility for bug in application. These types of bugs are difficult to find. Sometimes logical operators are called as short circuit operators as well.

Bitwise AND (&) operator

Bitwise operator can operate on integral and Boolean expression. They can operate with two operands and both operands must be evaluated. If first expression returns false even though it will evaluates second expression. Let's have a look on below code.

int x = 3;
int y = 0;

if ((y > x) & (x / y > 0))
    Console.WriteLine("Bitwise AND Operation");

The above code will throw an exception because bitwise (&) AND evaluates both expressions and as per above code second expression throws dividebyzero exception. This above example shows bitwise Boolean condition. There are four possible values for Boolean bitwise AND (&) operations.

Bitwise AND (&)
Expression 1
Expression 2
Result
True
True
True
True
False
False
False
True
False
False
False
False

Similarly we can perform bitwise AND on integral numbers as well. This bitwise AND on integral numbers will first convert numbers into binary and then perform AND operations on it. Let’s have a look on below code.

int x = 5;  // Binary Equivalent  - 0101
int y = 7;  // Binary Equivalent  - 0111

//   0101
// & 0111
//  -----
//   0101

int result = x & y; //output  = 5

The above code demonstrates bitwise AND (&) operation between variable x and y. The binary equivalent of x is 0101 and y is 0111. Now bitwise AND (&) operation will perform AND between binary values of x and y as displayed in commented code above. The result will return 5 in decimal number.

Bitwise OR (|) operator

Similarly we can perform Bitwise OR between two operands like bitwise AND. Bitwise OR performs OR operation on binary equivalent numbers. Let’s have look on below code which is modified version of above code.

int x = 5;  // Binary Equivalent  - 0101
int y = 7;  // Binary Equivalent  - 0111

//   0101
// | 0111
//  -----
//   0111

int result = x | y; //output  = 7

In above code Bitwise OR will be applied to the binary equivalent numbers of x and y values. Below is the table which explains bitwise OR results between two expressions.

Bitwise OR (|)
Expression 1
Expression 2
Result
True
True
True
True
False
True
False
True
True
False
False
False

Bitwise Exclusive OR (^) operator

Bitwise Exclusive OR can be applied to two operands and behave similar to Bitwise AND/OR. This performs XOR operation between binary equivalent numbers. Below table explains bitwise XOR results between two expressions.

Bitwise XOR
Expression 1
Expression 2
Result
True
True
False
True
False
True
False
True
True
False
False
False


Usage of Bitwise Operators

Bitwise operators are used in multiple places and also called as fundamental operators on computers. Below are few areas where bitwise operators majorly used.
  • Low level programming
  • Hardware device drivers creation
  • Creating protocols
  • Communicating with ports and sockets
  • Graphics driver
  • Gaming
  • Communicating with physical devices
  • Encryption
  • Data Compression

Hope this post helps you to understand basic concept of Logical and Bitwise Operators in Dotnet. Please leave your feedback in comments section below.

Monday, July 9, 2012

File System Watcher class in .Net (C#)


Sometime you might need to monitor changes like files added, deleted, renamed for particular folder. To do so, .net provides FileSystemWatcher class to monitor such kind of activity for particular folder or file.

FileSystemWatcher class provides some events which are fired when some action done to the folder like file created, deleted, renamed etc. You can also specify filter to file system watcher if you want to watch only text file or music files etc. It also provides an option to include subdirectories to watch or monitor.

Let’s have a look on below code snippet

void FileSystemWatcherDemo_Loaded(object sender, RoutedEventArgs e)
{
    //creates an instance of FileSystemWatcher
    FileSystemWatcher watcher = new FileSystemWatcher();
    //set folder or file path to watch
    watcher.Path = @"D:\Temp\Test";
    //watches txt files only
    watcher.Filter = "*.txt";
    //enable watching subdirectories also
    watcher.IncludeSubdirectories = true;

    watcher.Created += new FileSystemEventHandler(watcher_Created);
    watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
    watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
    watcher.Changed += new FileSystemEventHandler(watcher_Changed);
           
    //starts watching/monitoring folder or file
    watcher.EnableRaisingEvents = true;
}

void watcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File changed - {0}, change type - {1}", e.Name, e.ChangeType);
}

void watcher_Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine("File renamed - old name - {0}, new name - {1}", e.OldName, e.Name);
}

void watcher_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File deleted - {0}", e.Name);
}

void watcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File created - {0}, path - {1}", e.Name, e.FullPath);
}

Output –
File created - Text2.txt, path - D:\Temp\Test\Text2.txt
File created - Text1.txt, path - D:\Temp\Test\Text1.txt
File renamed - old name - Text2.txt, new name - Text3.txt
File deleted - Text3.txt

As per above code, I have chosen Test folder to monitor file system changes. After running this application, if I add, delete, rename any text file to this folder, it will notify FileSystemEvent to raise respective event and the code written in respective event handler will execute.

See Also - 

Tuesday, April 17, 2012

How to use Pre-build and Post-build Events in Visual Studio?



Many of you might aware about Build Events feature of Visual Studio. In this post i will explain little bit about Pre-build and Post-build events and their usage.

Sometimes you might need to execute some additional tasks just before and after building your Visual Studio solution. So for this Visual Studio provides nice way to do that using Build Events. You can specify commands inside pre-build and post-build command line. You can find build events tab inside project properties.


As mentioned in above image, you can specify almost all DOS commands inside pre-build and post-build event as per your requirement. Post-build event gives you more control over Pre-build command line execution. You can decide when to execute post-build event from given three options displayed in above image.

Let’s try to understand with simple example.



On successful build I want to copy my executable to some specific folder on my local drive. So in above example I have used xcopy command to copy files from one directory to another. In above example I have used ‘$(ProjectDir)’ macro which will gives me the current project directory. There are more macros available to use for various purposes see below image. These macros can be used to specify location of project or solution, project name, extension, output directory, configuration name etc.



You can use this feature in many scenarios like processing or executing batch file, copy assemblies to specific location, generate resources file using tool like resgen.exe etc. This is really nice and useful feature provided by visual studio.

Hope you liked this small tip. Please leave your feedback in comments section.


See Also – 

Tuesday, April 10, 2012

How to modify/create build configurations in Visual Studio?



In project life cycle you might need to create or access various builds like Development, Testing, User Acceptance Testing, Production etc. Visual Studio provides Configuration Manager Toolbar to change, create or access builds. By default solution has two builds Debug and Release.

Typically debug build is used to debug and detect errors (compile-time and runtime) from solution or project. Once project or solution development is complete and ready to deploy than project or solution should be built in Release mode. Release builds enables code optimization and enables fast execution of program.

You can also change or create new configuration using configuration dropdown available on standard toolbar.


For add or change configuration you can select configuration manager from any of the drop down. If sometimes configuration or platform drop downs are not visible on standard tool bar of visual studio in such case you can add those externally by clicking on customize menu item of tools menu.


The Configuration Manager Dialog will appear.


Similarly you can open Configuration Manager Dialog from right click of your solution and click on Configuration Manager (below image).

You can change or edit configuration and platform for each project under solution.


The same configuration used to develop application to choose correct config file or connection string or other configuration specific task. Let’s have a look on below code.

#if DEV
        Console.WriteLine("DEV Configuration...");
#elif QA
        Console.WriteLine("QA Configuration...");
#endif

As per above code, based on selected configuration either DEV or QA the appropriate code will execute. One more thing, by default Debug and Release configuration added with project and during compilation it will create Debug and Release folder under Bin folder located at solution folder. If we added new configurations in our case DEV and QA then respective folder will get created under solution’s Bin folder and respective resource and assembly will be added to that.



Monday, April 9, 2012

How to build Solution or Project from command line (Batch File)?


Sometimes you might need to build multiple solutions or complex project in particular sequence. In such case you can build your project or solutions using command line or batch file. In this post I will explain simple way to build project or solution using command line tool or creating batch file.

Devenv allows you to build your solution or project using command line. It also allows related multiple operations such as clean solution, rebuild solution or deploy solution etc. To execute commands, you need to open Visual Studio command prompt available inside visual studio tools under all programs of start menu. You can find multiple options available with devenv using below command.

Devenv /?

Let’s start with simple example which builds solution using command prompt.

Devenv  TestConsoleApplication.sln /Build Debug



The above command builds TestConsoleApplication solution in Debug configuration mode. To build this solution with Release mode you just need to write Release instead of Debug in above code.

Similarly you can clean and rebuild solution using below code.

Devenv  TestConsoleApplication.sln /Clean

Devenv  TestConsoleApplication.sln /Rebuild Debug

We can also build specific project with project build configuration along with solution.

Devenv  TestConsoleApplication.sln /Build Debug /Project TestConsoleApplication/TestConsoleApplication.csproj /ProjectConfig Debug


Below command opens solution from command prompt and runs the application. If any exception occurred while running application it will log the same in MyErrorLog.txt file.

Devenv /Run TestConsoleApplication.sln /out D:/Temp/MyErrorLog.txt

The above command runs the application and log exception if any into separate file mentioned with /out switch.

We can also reset Visual Studio’s setting using below line of code. This is nice and great feature which can be useful when something is missing from IDE or IDE is not working property. This will restore back all the default settings of Visual Studio’s IDE.

Devenv /ResetSettings

MSBuild.exe

For build related task, it is recommended by Microsoft to use Msbuild.exe. Msbuild.exe builds project or solution with specified options. You can find multiple options using below help command.

msbuild.exe /?

To build solution using msbuild you can use below line of code.

MSBuild TestConsoleApplication.sln /p:Configuration=Release /p:Platform=”Any CPU”


You can also perform multiple task like Rebuild, Clean etc using MsBuild.

You can also create batch file to build your application. Below is the sample code of batch file to build your application using devenv.

BuildSolution.Bat
@Echo OFF
Echo "Building solution/project file using batch file"
SET PATH=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\
SET SolutionPath=d:\Temp\TestConsoleApplication\TestConsoleApplication.sln
Echo Start Time - %Time%
Call Devenv %SolutionPath% /Build Debug
Echo End Time - %Time%
Set /p Wait=Build Process Completed...


You can also create batch file to build solution using MSBuild.exe file similar above mentioned batch file with just little change.

BuildSolution.Bat
@Echo OFF
Echo "Building solution/project file using batch file"
SET PATH=C:\Windows\Microsoft.NET\Framework\v4.0.30319\
SET SolutionPath=d:\Temp\TestConsoleApplication\TestConsoleApplication.sln
Echo Start Time - %Time%
MSbuild %SolutionPath% /p:Configuration=Release /p:Platform="Any CPU"
Echo End Time - %Time%
Set /p Wait=Build Process Completed...


See Also - 

Sunday, February 26, 2012

Hot to get list of all AppDomains inside current process?



In my earlier post, I have explained how to create AppDomain inside process and how we can share data between AppDomains. As per request from one of you, in this post I am going to explain how we can get list of all AppDomains inside process.

To enumerate all the AppDomains inside process we can use class called CorRuntimeHost. This class is available inside mscoree namespace and can be added externally from C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscoree.tlb location. This class provides EnumDomains method which is used to enumerate AppDomains inside process. The NextDomain method of this class is used to get next available AppDomain if no AppDomain found, sets domain to null. 

Let’s have a look on below code snippet.

AppDomain.CreateDomain("AppDomain 1");
AppDomain.CreateDomain("AppDomain 2");
AppDomain.CreateDomain("AppDomain 3");

List<AppDomain> appDomains = new List<AppDomain>();

IntPtr handle = IntPtr.Zero;
CorRuntimeHost host = new CorRuntimeHost();
try
{
    host.EnumDomains(out handle);
    while (true)
    {
        object domain;
        host.NextDomain(handle, out domain);
        if (domain == null)
            break;
        appDomains.Add((AppDomain)domain);
    }
}
finally
{
    host.CloseEnum(handle);
}

foreach (AppDomain appDom in appDomains)
{
    Console.WriteLine(appDom.FriendlyName);
}

Output –
AppDomain 1
AppDomain 2
AppDomain 3


How to get specific AppDomin from process?

We can get specific AppDomain using the same code but with little modification. Let’s have a look on below code.

public void GetAppDomain(string name)
{
    IntPtr handle = IntPtr.Zero;
    CorRuntimeHost host = new CorRuntimeHost();
    try
    {
        host.EnumDomains(out handle);
        while (true)
        {
            object domain;
            host.NextDomain(handle, out domain);
            AppDomain myAppDomain = domain as AppDomain;
            if (myAppDomain == null)
                break;
            if (myAppDomain.FriendlyName.Equals(name))
            {
            Console.WriteLine("AppDomain Name - {0}", myAppDomain.FriendlyName);
            }
        }
    }
    finally
    {
        host.CloseEnum(handle);
    }
}

See Also –