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

Tuesday, May 04, 2010

* Windows Search : Saving Search results to text file

In Windows 7, when you perform search using Windows Explorer, there is no direct way of exporting the results to a text file.

Here is a small trick to copy them to a text file.

1 - Open Windows Explorer and search for what you want
2 - When the search results populate, select all (Ctrl + A)
3 - Hold the Shift key and Right Click on the search results
4 - Select "Copy as Path" (this option only shows up when you hold shift before the right click)
5 - Paste into a notepad window, Excel spreadsheet, etc...
The results will be formatted as:
"\path\to\first\item"
"\path\to\second\item"
...

Thanks Tarek Ayna.

Wednesday, April 21, 2010

* Free folder size management tool – Folder Size

Having folder size not available in default view of Windows Explorer is always a challenge during investigation of disk space.

Here is a free tool which you can use to find out how your disk space is utilized.

image 

Download Folder Size tool

Monday, January 21, 2008

* Visual Studio Tip : Manage your 'using' statements

Visual Studio editor provides a tool using which you can manage your 'using' statements. You can do following :

  • Remove the unnecessary 'using' statements automatically.
  • Sort the 'using' statements.

Here is how you can execute the tool :

Right click on editor and go as shown on context menu :

image

Or you can do like this :

Edit -> IntelliSense -> Organize Usings

Visual Studio : How to create temporary projects

Friday, September 21, 2007

* Assembly Version vs Assembly File Version

.NET framework provides opportunity to set two different types of version numbers to each assembly.

Assembly Version : This is the version number used by framework during build and at runtime to locate,link and load the assemblies. When you add reference to any assembly in your project, it is this version number which gets embedded. At runtime, CLR looks for assembly with this version number to load. But remember this version is used along with name, public key token and culture information only if the assemblies are strong-named signed. If assemblies are not strong-named signed, only file names are used for loading.

Assembly File Version : This is the version number given to file as in file system. It is displayed by Windows Explorer. Its never used by .NET framework or runtime for referencing.

So, how do you best make use of these file numbers available. This is one way of using it, if you guys know a better way .. let me know.

Attributes in AssemblyInfo.cs

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Providing a (*) in place of absolute number makes compiler increase the number by one every time you build.

Suppose you are building a framework assembly for your project which is used by lot of developers while building the application assemblies. If you release new version of assembly very frequently, say once every day, and if assemblies are strong named, Developers will have to change the reference every time you release new assembly. This can be quite cumbersome and may lead to wrong references also. A better option in such closed group and volatile scenarios would be to fix he 'Assembly Version' and change only the 'Assembly File Version'. Use the assembly file version number to communicate the latest release of assembly. In this case, developers will not have to change the references and they can simply overwrite the assembly in reference path. In central/final release builds in make more sense to change the 'Assembly Version' and most keep the 'Assembly File Version' same as assembly version.

Tuesday, April 24, 2007

* Visual Studio Tip : How to change the default assembly information

New project creation in Visual Studio takes place based on Project Templates provided by Visual Studio or custom templates created.

When we create a new console application using the default project template provided by Visual Studio, the assembly.info is generated by default with some data like Company & Copyright information which is populated using information provided at time of installation.

If you want to change this default generated data, here is the trick.

The default project templates are stored in equivalent of following folder in Visual Studio 2005 installation area :

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates.

Suppose if you want to change the default values for C# console application, change the assembly.info file located in following folders:

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\ConsoleApplication.zip

D:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplatesCache\CSharp\Windows\1033\ConsoleApplication.zip

Other Posts

Wednesday, March 21, 2007

* Visual Studio : How to create Project Item Templates

Before continuing with this post, pls go through the following two posts in sequence as they form the basis for this post.

  1. Accelerating development using Visual Studio Templates
  2. Increasing Productivity/Discipline using Project Templates

Consider a scenario where a company is into developing lot of console based utilities and want to display the copyright notice as soon as any of the utility is executed. A definite requirement will be to have a consistent copyright text in all utilities.

Now to get the consistency and ease of clubbing copyright notice to each utility, the requirement is to provide the teams with a artifact which they can easily integrate into their utility. The steps below will show how this can be achieved using the Project Item templates.

  • Create a console application using the default 'Console Application' Project template available with Visual Studio.
  • Add a new class file to the project using Add -> New item . Name the file as CopyRight.cs
  • Add the following code to CopyRight.cs file
using System;
using System.Collections.Generic;
using System.Text;

namespace MyCompany
{
class CopyRight
{
public static void Print()
{
Console.WriteLine("My Company's Copyright Notice");
}
}
}








  • Modify the code of Program.cs to contain the following code where in the start of main method the copyright class method is called to display the copyright message.
using System;
using System.Collections.Generic;
using System.Text;

namespace ProjectItemTemplate
{
class Program
{
static void Main(string[] args)
{
MyCompany.CopyRight.Print();
}
}
}








  • Build & execute the project to make sure its working fine.

  • Go to File -> Export Template. Select Item Template.

  • Select the CopyRight.cs item in the next screen.

  • Select the references based on requirement on next screen.

  • On next screen, change template name to Copyright. Click Finish. Its done.

  • To check whether we have successfully created an item template, create a new console application.

  • In solution explorer, go to Add -> New Item -> My Templates. You will a new template called Copyright. Add it to the project and you will see that Copyright.cs has been added to the project.


Above scenario may not be the best to demonstrate the true power of Project Item Templates but they definitely help in increasing productivity and bringing discipline to the project.



~tata & take care~



Other Posts



Tuesday, March 20, 2007

* Accelerating development using Visual Studio Templates

Visual Studio templates are a very efficient way of accelerating development by providing a startup infrastructure for new project creation and new item creations during the project. An excellent example of this is the 'Console Application' project template available in the new project dialog box of Visual Studio.

When a new project is created using the 'Console Application' project template, all the mandatory & common things required by any console applications are created automatically and developer can directly jump to writing the code specific to his/her application. Two of the mandatory actions completed by the template are :

  • Setting the project output type as 'Console application'
  • Generating the skeleton code for 'main' class which is entry point for the application.

While Visual Studio comes with most commonly used project templates, custom project templates can also be developed.

There are basically two types of templates :

  • Project Templates : Available in the 'New Project' dialog box
  • Project Item Templates : Available in the 'Add New Item' dialog box in the solution explorer.

The main components of a template are :

  • The .vstemplate file which contains the metadata for the template like whether its a project template or a project item template.
  • The files which will be added to the project when the template is used like code, resource, etc files.

To read the detailed walkthrough on how to create a Project Template, pls go to following post.

I will cover the creation of project item template in my next post on this.

~tata & take care~

Other Posts

* Visual Studio : How to create Temporary Projects

By default when a new project is created, New dialog box requires a physical location where the project files will be saved automatically. But if you are into trying lot of language features or create lot of temporary projects, everytime creating a new project will create lot of files which may never be used again.

Visual Studio supports creation of temporary projects which means at the time of creation of new project, you are not required to provide folder path and you can decide to save the project at later point of time if required.

To enable temporary project creation support, the following setting needs to be changed :

Visual Studio 2005 -> Tools -> Options -> Projects & Solutions node -> General -> Clear the check box 'Save new projects when created'

Whether temporary project can be created depends on the template used for creation of project. The project template may or may not support the creation of temporary project.

~tata & take care~

Other Posts

Thursday, February 08, 2007

* .NET Tip #7 : ASP.NET Dynamic Code compilation trick

ASP.NET by default provides two folders from where code is recognized automatically by asp.net runtime without registering the assemblies.

The bin folder can be used to place your compiled assemblies. Any changes in these assemblies are automatically loaded by the runtime.

ASP.NET provides for another folder called App_Code folder where directly source code files can be placed which get compiled at runtime whenever accessed. They are also accessible from all the pages of the web application. Very useful for maintaining volatile custom code without compiling it every time. Runtime invokes the appropriate compiler based on the language in source code. You can't place different languages source code in directly app_code folder but by creating different subfolders, different language sources can be maintained in dedicated subfolders. The config element used to configure this is <codeSubDirectories>.

Other Posts

Thursday, February 01, 2007

* Debugging and Profiling .NET Applications

Debugging or Troubleshooting an application in production environment can become nightmare if the application has not been instrumented well.

The .NET framework namespace System.Diagnostics provides following classes : Trace, Debug, and TraceSource for tracing and debugging applications.

The Trace and Debug classes ae identical in the functionality they provide except that Trace is part of Release build by default while Debug statements are removed from Release build.

Before seeing Tracing into action lets understand some important components of Tracing framework.

  • Listeners : Trace output is collected by objects called listeners which redirect it to the configured device like console, flat file etc.
  • Switches : Switches allow to enable, disable or filter tracing outputs. These can be configured through the .config file. There are basically three types of switches BooleanSwitch, TraceSwitch and SourceSwitch. One of the ways to filter trace output is TraceLevel where it can have values from 0 to 4. 0 means Off and 4 means Verbose Messages.

So all the tracing data after getting filtered using switches goes to listeners which redirect them to configured output.

Lets look at an example now :

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using System.Diagnostics;
   5:   
   6:  namespace TracingSample
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:              TraceSource ts = new TraceSource("TracingSampleSource");
  13:              ts.TraceEvent(TraceEventType.Error,1,"Error message");
  14:              ts.TraceEvent(TraceEventType.Information,2,"Info Message");
  15:              ts.Flush();
  16:              ts.Close();
  17:          }
  18:      }
  19:  }






The config file for this program looks like this :



 

<configuration>
<system.diagnostics>
<sources>
<source name="TracingSampleSource"
switchName="sourceSwitch"
switchType="System.Diagnostics.SourceSwitch">
<listeners>
<add name="myListener"/>
<add name="console" type="System.Diagnostics.ConsoleTraceListener" />

</listeners>
</source>
</sources>
<switches>
<add name="sourceSwitch" value="Information"/>
</switches>
<sharedListeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="myListener.log">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error"/>
</add>
</sharedListeners>
</system.diagnostics>
</configuration>






 



The code usage is fairly simple, create an instance of TraceSource, logged two events using it where one is of Error type while other of Info type.



Its the configuration ability which makes this framework so powerful. The source has been configured to send messages to two listeners 'myListener' which redirects the messages to a log file called myListener.log and console. At source level the messages have been filtered using sourceSwitch switch while at listener level it has been configured for Error messages only.



The outputs of the two listeners are as follows :



Log File



TracingSampleSource Error: 1 : Error message



Console output :



TracingSampleSource Error: 1 : Error message
TracingSampleSource Information: 2 : Info Message



Other Posts



 

Thursday, January 18, 2007

* .NET Tip #6 : Strong Named Assemblies Unleashed

An assembly which doesn't have a strong name is identified by only its file name. A strong named assembly gets a globally unique identity which consists of following four attributes : file name, version number, culture information (if provided) and a public key.

The steps required to strong name an assembly are :

1. Create a public-private key pair using a tool called Strong Name tool (Sn.exe)

2. Enable the strong naming of assembly during build using Project -> Properties Page or adding following attribute to AssemblyInfo.cs [assembly: AssemblyKeyFileAttribute(@"keypair.snk")]

When an assembly is strong named, development environment signs the hash of the file containing assembly's manifest with the private key. This is stored in the portable executable (PE) file. Also the public is embedded in the manifest of the strong named assembly as below :

.publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$..............
00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........
FF ED CD 9D 17 C1 AA 3A B0 AD 8A FA 94 C1 88 DD // .......:........
8F 49 65 AE 87 FC D6 51 F7 CE 80 6B FD FA C0 F8 // .Ie....Q...k....
10 F7 E1 E2 18 4F 10 06 F0 97 10 52 06 16 A7 D5 // .....O.....R....
F8 AC F7 C6 4A B4 62 19 1B AE 1B 3B B4 F8 19 3F // ....J.b....;...?
33 9C 4E A7 7A 8F BF BB 54 3C B9 D6 E5 EE 3C 06 // 3.N.z...T<....<.
F2 05 98 AB 7A 21 21 23 2D 0A 94 93 30 23 1B E0 // ....z!!#-...0#..
47 25 82 46 B3 B2 F2 E0 F7 94 77 A7 23 A4 11 DC // G%.F......w.#...
0F F8 17 31 B8 9D 06 5B 78 5F C3 81 7E 7E AD AB ) // ...1...[x_..~~..

When an assembly references this strong named assembly its manifest will contain the public token of the public key of the referenced strong named assembly

.assembly extern StrongAssembly
{
.publickeytoken = (89 A8 29 AB 81 32 88 38 ) // ..)..2.8
.ver 1:0:0:0
}

This PublicKeyToken is the hash of the public key and can be calculated using same tool as shown below

D:\Vikas\vikas\tech\code\StrongName\StrongAssembly>sn -Tp strongassembly.dll

Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.

Public key is
0024000004800000940000000602000000240000525341310004000001000100ffedcd9d17c1aa
3ab0ad8afa94c188dd8f4965ae87fcd651f7ce806bfdfac0f810f7e1e2184f1006f09710520616
a7d5f8acf7c64ab462191bae1b3bb4f8193f339c4ea77a8fbfbb543cb9d6e5ee3c06f20598ab7a
2121232d0a949330231be047258246b3b2f2e0f79477a723a411dc0ff81731b89d065b785fc381
7e7eadab

Public key token is 89a829ab81328838

The strong naming assembly provides two advantages :

1. As strong names are globally unique, it protects applications from name spoofing.

2. When runtime loads the referenced assembly it generates the hash of the contents of strong assembly and compares it with the hash stored in PE of strong assembly by decrypting it with public key. The same value of both hashes ensures that assembly has not been tampered.

However, no level of trust is associated with a strong name but ensures integrity of the assembly.

Other Tips

.NET Partial Types

.NET Namespace Alias

* .NET Tip #5 : How to use an Application Configuration File to target a .NET Framework Version

Suppose the application has been built against version (x).

The version of the framework which application runs on is determined by following steps :

1. If the version (x) is present, the application runs on that version.

2. If the version (x) is not present and config file does not specify the version in <supportedRuntime> element, the application runs on latest version that is present but not older than version (x).

3. If the version (x) is not present and config file specifies a version in <supportedRuntime> element, the application runs on latest version that is specified and present on the computer.

A sample config file entry :

<?xml version ="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v1.1.4322" />
  </startup>
</configuration>

If you dont want your application to run on the latest version incase the version (x) is not present, you can use element <requiredRuntime>.

Other Tips

Static Classes

.NET Namespace Alias

Tuesday, January 16, 2007

* CSharp Tip #4 : .NET Iterators

Iterators have been introduced in .NET 2.0. Iterator is used to enable support for foreach operation on a class or struct.

The iterator code uses the yield return statement to return each statement in turn. Multiple iterators can be implemented on a class. Each iterator must have a unique name and can be invoked by client code in a foreach statement as follows : foreach (int x in SampleClass.IteratorName)

Consider the following sample code which shows how to use iterators and how to have multiple iterators on same class.

 

using System;
using System.Collections.Generic;
using System.Text;

namespace VikasGoyal.Iterators
{
class Program
{
static void Main(string[] args)
{
SampleClass sc = new SampleClass();
Console.WriteLine("Version Numbers");
foreach (string i in sc.GetVersions())
{
Console.WriteLine(i);
}
Console.WriteLine("Version Names");
foreach (string i in sc.GetNames())
{
Console.WriteLine(i);
}
}
}

class SampleClass
{
string[] versions ={ "1.0", "2.0", "3.0" };
string[] names ={ "First", "Second", "Third" };

public System.Collections.IEnumerable GetVersions()
{
for (int i = 0; i < versions.Length; i++)
{
yield return versions[i];
}
}

public System.Collections.IEnumerable GetNames()
{
for (int i = 0; i < names.Length; i++)
{
yield return names[i];
}
}
}
}
OUTPUT
Version Numbers
1.0
2.0
3.0
Version Names
First
Second
Third



Wednesday, January 10, 2007

* CSharp Tip #3 : .NET Partial Types

.NET languages now support distributed definition of classes which means a single class can be defined at multiples places/files and gets compiled into one during compilation. The keyword used to implement this feature is partial.

Consider the following code :

using System;
using System.Collections.Generic;
using System.Text;

namespace VikasGoyal.PartialClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Math.add(3,2));
            Console.WriteLine(Math.subtract(3, 2));
        }
    }
    partial class Math
    {
        public static double add(double num1, double num2)
        { return num1 + num2; }
    }
    partial class Math
    {
        public static double subtract(double num1, double num2)
        { return num1 - num2; }
    }
}

The class definition of Math has been distributed into two but at compile time it gets aggregated into one and the client for the class sees it as a single class. The definition can be distributed to multiple files also. This feature provides advantage mainly in two scenarios :

1. In large projects separating a class over multiple files allows multiple programmers to work simultaneously.

2. When the code is generated the generated class can be enhanced without touching the generated code. This simplifies the maintenance.

Partial keyword works on class, struct and interface definitions but its not available on delegate or enumeration declarations. The following of types are merged at compile time :

* XML Comments

* interfaces

* generic-type parameter attributes

* class attributes

* members

 Partial types can make a significant contributions in designing classes if properly used.

Tuesday, January 09, 2007

* CSharp Tip #2 : .NET Namespace Alias

Consider the below code :

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using FrmwkSystem = System;
   5:   
   6:  namespace VikasGoyal.NameSpace_Qualifier
   7:  {
   8:      class Program
   9:      {
  10:          public class System { }
  11:   
  12:          const int Console = 11;
  13:          const int number = 22;
  14:   
  15:          static void Main(string[] args)
  16:          {
  17:              Console.WriteLine(number); // compile error as Program.Console is visible
  18:              System.Console.WriteLine(number); //compile error as Program.System is visible.
  19:              global::System.Console.WriteLine(number); //OK
  20:              FrmwkSystem::Console.WriteLine(number); //OK
  21:          }
  22:      }
  23:  }






 



The Line 17 and 18 will compilation error because of the names used by local class although in general there is nothing wrong with these lines.



In single program such situations are rare but in multi developer environment where lot of people are working on same program such kind of deadlock situations can occur. Namespace Alias comes to rescue in such situations. As seen from Line 19 and 20, there are two ways of solving such conflicts using Namespace Alias Qualifier (::). For Framework classes directly global can be used but for custom classes if required keyword using can be used to resolve names.

* CSharp : Understanding Nullable Types

Nullable Types are instances of the System.Nullable struct introduced in .NET 2.0. Null means value undefined or value not known. Reference types by design support storing null but values types have been designed to store only the range of values they are made for. They don't have capacity to store null. But many times there may be situation where we don't know the value to store in value type e.g. in case of database fields where some fields may be empty of null.

To support such requirements Nullable types have been introduced. Nullable types are supported using a Nullable Generic Structure in System Namespace.

public struct Nullable<T> where T : struct

The following struct can be used in following two ways :

Nullable<int> x = new Nullable<int> (100);

or

int? x = 100;

The two main properties of this struct are HasValue and Value.

HasValue indicates whether the current instance has a value. True if the instance has a value & false if has no value. The value in the object can be accessed by property Value.

The operator ?? can be used to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type.

e.g. int? x= null; int y = x ?? 1; y will be assigned a value of 1.

Monday, January 08, 2007

* CSharp Tip #1 : Static Classes

In .NET Framework 1.x, Static Classes are created by defining a class with a private constructor with one or more static members so that instance of the class cannot be created using new operator.

In .NET Framework 2.0 the need for such a private constructor is avoided by using a static keyword along with the class definition. Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values.

using System;
using System.Collections.Generic;
using System.Text;

namespace VikasGoyal.StaticClasses
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(StaticClass.getName());
Console.WriteLine(StaticClass.getName());
Console.WriteLine(StaticClass.getName());
}
}
static class StaticClass
{
private static string name;
static StaticClass()
{
name = "Vikas Goyal";
Console.WriteLine("In Constructor");
}
public static string getName()
{
return name;
}
}
}
OUTPUT
In Constructor
Vikas Goyal
Vikas Goyal
Vikas Goyal