namrata's profileNashaPhotosBlogListsMore Tools Help

Blog


    December 12

    License Compiler ( Lc.exe .Net FrameWork Tools )

    We create a lot of coontrols every day but generally we never bother about licensing them. Licensing only comes into the picture when we need to share our controls with others.

    Let us today create a licensed control then we will use lc.exe and embed the license in our assembly.

    1) Open a new peoject Windows Control Library.

    2) Add a new control to it. Could be inheriting from control or usercontrol.

    3) There are a few thing that we need to do to make our licensed component.

    4) Add LicenseProvider Class attribute giving the type of license provider we are using. LicFileLicenseProvider comes with the .Net Framework.

    [LicenseProvider(typeof(LicFileLicenseProvider))]

    5) Add a private license object to our class

    private License license;

    6) Validate the license in our constructor

    license = LicenseManager.Validate(typeof(Ctrl1),this);

    7) At last Dispose the license in the dispose method by overriding the dispose method.

    if( disposing )

    {

    if(license == null)

    {

    license.Dispose();

    license=null;

    }

    }

    8) Your class should like this in the end

    using System;

    using System.Collections;

    using System.ComponentModel;

    using System.Drawing;

    using System.Data;

    using System.Windows.Forms;

    namespace CL

    {

    [LicenseProvider(typeof(LicFileLicenseProvider))]

    public class Ctrl : System.Windows.Forms.Control

    {

    private License license;

    public Ctrl()

    {

    license = LicenseManager.Validate(typeof(UserControl1),this);

    }

    protected override void OnPaint(PaintEventArgs pe)

    {

    base.OnPaint(pe);

    }

    protected override void Dispose( bool disposing )

    {

    if( disposing )

    {

    if(license == null)

    {

    license.Dispose();

    license=null;

    }

    }

    base.Dispose( disposing );

    }

    }

    }

    9) Compile the project.

    10) Create a new Windows application which will act as a host to our control. Name it LicCtrlClient.

    11) Create a file called LicCtrlClientlic.txt which will hold the entire list of components and the dll name.

    LicCtrlClientlic.txt contents

    CL.Ctrl

    CL.UserControl

    CL.dll

    12) Compile .licenses file for licCtrlClient

    lc /target:licCtrlClient.exe /complist:LicCtrlClientlic.txt /i:CL.dll

    13) <application.exe>.licenses file will be generated.

    14) You can use your language compiler or al to embed this file in your exe.

    Soapsuds.exe -- Imp. Tool (.Net Framework Tools Series)

    Today we gonna discuss Soapsuds tool.

    Soapsuds is shipped with .Net Framework and is used by .Net remoting Client Applications to generate xml schema, proxy class or assembly for there HTTP Remoting Server. Client App can use this proxy class or assembly as a reference to the remoting server object.

    Confused???

    Let us take an example and look into it.

    Step 1: Create a remoting HTTP server.
    Step 2: Generate WSDL for HTTP Server using IE.
    Step 3: Use soapsuds to create proxy class, xml schema and assembly.
    Step 4: Crete a remoting client that uses the proxy class or assembly.   
    Step 5: Checking out some imp options of soapsuds.

    Step 1:

    1) Create a new console application called Remoting Server.
    2) Add a class called Calc, which will hold our calculation services.
    3) Our Calc class should be inherited from "MarshalByRefObject"
    4) Add four methods to this class Add, Del, Mul, Div as shown in the code below.

    using System;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;

           public class Calc:MarshalByRefObject
           {
                   public int Add(int i , int j)
                   {
                           return i+j;
                   }
                   public int Del(int i , int j)
                   {
                           return i-j;

                   public int Mul(int i , int j)
                   {
                           return i*j;
                   }
                   public int Div(int i , int j)
                   {
                           return i/j;
                   }
           }

    5) Add another class called ClassMain which will hold function Main() as follows :

    using System;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;

    class ClassMain
           {
                   /// <summary>
                   /// The main entry point for the application.
                   /// </summary>
                   [STAThread]
                   static void Main(string[] args)
                   {
                           HttpChannel httpChannel = new HttpChannel(8765);
                           ChannelServices.RegisterChannel(httpChannel);
                           RemotingConfiguration.ApplicationName ="MyRemotingApp";
                     RemotingConfiguration.RegisterWellKnownServiceType(typeof(Calc),"MyCalc",WellKnownObjectMode.Singleton);
                           Console.WriteLine("Server started ..... ");
                           Console.ReadLine();
                   }

           }

    6) Our Http Remoting Server is now ready which will work on port 8765. This is a Singleton server i.e. only object will be  created and this object will server to all the clients.

    7) Compile the application and create the executable.
    8) Run the executable and you should get a message "Server started". The server executable should be running hence forth throughout the example.

    Step 2:

    1) Open IE and type the below link to generate the WSDL.

           http://localhost:8765/MyRemotingApp/MyCalc?WSDL

    I have attached MyCalc.xml file with this mail. You check out the generated WSDL.

    Step 3:

    1) See that the server is running (Run the executable).
    2) Go to the VS.NET command prompt and type soapsuds /? . This will list all the available options.

    Input Sources (only one can be specified)
    -urlToSchema(-url):[SchemaUrl]
    -types:[type1,assemblyname[,serviceEndpoint]][;type2,assemblyname[,serviceEndpoint]][...]
    -inputSchemaFile(-is):schemafile Input Schema File
    -inputAssemblyFile(-ia):assemblyfile

    Input Options
    -inputDirectory(-id):directory     Location of input dlls.
    -serviceEndpoint(-se): Url for Service Endpoint placed in Wsdl file

    Output Options
    -outputSchemaFile(-os):schemafile
    -outputDirectory(-od):directory for generated source files
    -outputAssemblyFile(-oa):assemblyfile

    Generate Options
    -GenerateCode(-gc)  (equivalent to "-od:.")

    Other Options
    -WrappedProxy(-wp) Create wrapped proxy (default)
    -NoWrappedProxy(-nowp)   No wrapped proxy
    -proxyNamespace(-pn)  Namespace on generated proxy (Only used for interopNamespaces)
    -StrongNameFile(-sn):filename   Use strong name to build assembly

    Connection Information Options
    -username(-u):username
    -password(-p):password
    -domain(-d):domain
    -httpProxyName(-hpn):name
    -httpProxyPort(-hpp):number

    Note : After these options there are some examples given about the usuage of the tool. Check them out.

    3) -url := URL , -gc := Generate Code, oa:= output assembly and os:output schema are few important options that we will be  using.

    4) Now we will generate code (proxy class),proxy assembly and xml schema for our remoting server.

    5) Lets generate code using for our remoting http server using the server URL. We will using this further with our client application to reference our remoting server. The below code should generate a class named Remotingserver.cs .

        soapsuds -url:
    http://localhost:8765/MyRemotingApp/MyCalc?WSDL -gc

    6) After generating code now we will create an assembly named MyServer.dll for our http remoting server.

        soapsuds -url:
    http://localhost:8765/MyRemotingApp/MyCalc?WSDL -oa:MyServer.dll

    7) Now we will generate xml schema for our server object.

        soapsuds -url:
    http://localhost:8765/MyRemotingApp/MyCalc?WSDL -os:MyServer.xml

    Step 4:

    1) Create an client console application which will communicate with our server.
    2) Add Class called Client.cs and in the Main write code to communicate with our server object.

    using System;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
    using RemotingServer;

    namespace RemotingClient
    {
           /// <summary>
           /// Summary description for Client
           /// </summary>
           class Client
           {
                   /// <summary>
                   /// The main entry point for the application.
                   /// </summary>
                   [STAThread]
                   static void Main(string[] args)
                   {

                           HttpChannel httpChannel = new HttpChannel();
                           ChannelServices.RegisterChannel(httpChannel);
                           RemotingServer.Calc obj = new Calc();
              obj =(RemotingServer.Calc)Activator.GetObject(typeof(RemotingServer.Calc),                 
        "http://localhost:8765/MyRemotingApp/MyCalc");
                           Console.WriteLine(((RemotingServer.Calc)obj).Add(1,2));
                           Console.ReadLine();
                   }
           }
    }

    3) In this we are opening an HTTP channel to communicate with our remote object. Our remote object is a SAO i.e. Server activated
    object. Finally we are calling the Add function, which should return us 3.

    4) First we will add our proxy class i.e. RemotingServer.cs to our application. Add compile the project.

    Note: There should not be any reference to any remoting server dll's in our project. The only addition should be Remoting server  class, which will communicate with the remote object.

    5) Result 3 should be displayed.

    6) Stop the application and remove the proxy class RemotingServer.cs. NOW ADD reference to MyServer.dll and compile the project and execute it.

    7) Result 3 should be displayed.

    8) This way we can use either the proxy class or the proxy dll to communicate with our remoting object.

    Step 5 :

    Let us now check out some other important options of soapsuds.

    1) Generating xml schema, assembly and code for a particular type in the assembly.

           soapsuds -types:Calc.MyServer,MyServer -gc
           soapsuds -types:RemotingServer.Calc,MyServer -os:MyCalc.xml
           soapsuds -types:RemotingServer.Calc,MyServer -oa:MyCalc.dll

    2) Generating code and assembly from xml schema.

           soapsuds -is:MyServer.xml -gc
           soapsuds -is:MyServer.xml -oa:MyServer1.dll

    3) You can reference these in your client application.

    What is Migpol ? (.Net FrameWork Tools Series)

    Today we will discuss migpol.exe. This tool is shipped with .NET Framework SDK.

    This tool is used to migrate security policies from one version of .NET to another version of dot net.

    When .NET Framework is installed there are two configuration files installed i.e. machine.config and security.config for each  .NET Framework version.

    . Net allows side by side installation of more than one versions of .NET Framework. Thus, if you are having version 1.0 you can install version 1.1 at the same time on the same machine.

    These config files are different for each version. So configuration setting of one version is not shared with another.

    There is no tool available in the .NET Framework which can aid to copy or migrate your machine configuration settings from your older version to your new version. you have to do the changes manually or use some third party tool.

    Fortunately .NET Framework has provided us with a tool to copy the security policy setting. (Read my article on CASPOL to know more on security policy This is a link in Mumbaiusergroup ).

    CAS has three policy levels : User, Machine , Enterprise. Migpol only migrates Enterprise and Machine level security policies.

    Hence tomorrow when you load Whidbey you can migrate your security settings from your current version of .NET to the new version.

    Note: Security migration only works between compatible Versions of .NET.

    To check out migpol options. Type migpol /? on VS.NET command prompt.

    Help screen requested

    Usage: migpol <option> <args> ...

    migpol -migrate <toVersion> <fromVersion>
       Migrate security policy.

    migpol -l[istversions]
       List all CLR versions installed on this machine.

    migpol -?
    migpol /?
    migpol -h[elp]
       Displays this screen

    You can use -l option to list all the versions of .NET installed on your machine.

            Type migpol -l

    To migrate one version to another you can use a similar command
            migpol <old version> <new version>

    .NET Framework Configuration Tool (Mscorcfg.msc)

    We have almost covered all the .NET Framework Tools except a few, which we will cover in the coming days.

    Today we will are going to check out a tool called as mscorcfg.msc. This is a .Net configuration tool, which allows you to manage .Net Framework GAC, security policies through Microsoft management console.

    You will fing this tool in

            <drive>:\WINNT\Microsoft.NET\Framework\<version>

    You also run this tool from VS.NET command prompt by typing: - mscorcfg.msc

    Run the tool using either of the above options. You will notice it has windows explorer look and feel with a tree view at the left and  a  list view on the right.

    Check out the options in the left panel and you will notice that you know some other way of configuring and managing these options except for the last option Applications.

    You should see the below options under My Computer: -

    -> Assembly Cache & Configured Assemblies:- As the name says this allows you to manage assemblies in GAC. You have options to Add Assembly, Export Assembly List  and customize your GAC view.

    -> Remoting Services :- You can use this to configure remoting communication channels.

    -> Runtime Security Policy :- Allows you to configure CASPOL at Enterprise, User and Machine levels.

    -> Applications : - Add a .NET application (.exe) to view its dependencies, configured assemblies and remoting services.

    Right the .Net application and select Fix Application to fix any dependency problems or issues with the assembly.

    You will get a dialogue giving you a few options one of which is 'Application SafeMode' . On selecting this option the tool will detect any dependency issues and update the config file (create if not present) for runtime assembly binding settings.

    Management Strongly Typed Class Generator (Mgmtclassgen.exe .Net Framework Tools Series

    Today we will discuss Management Strongly Typed Class Generator aka Mgmtclassgen.exe. This tool is used to generate an early  -  bound managed class for Windows Management Instrumentation Classes.

    What are Windows Management Instrumentation Classes ?

    Well windows SDK has a set of classes by which you can access the various devices associated to your computer like your  harddisk, memory,floppy drive, processor, sound card , mointor etc.

    You have an entire list of these classes. Check out the below link for the list

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/computer_system_hardware_classes.asp

    Creating a managed class for WMI class is very simple.

    Go to VS.Net command prompt type

           mgmtclassgen /?  /// this will list all the options.

    /N <WMINamespace>               WMI namespace containing the class.Defaults to root\cimv2
    /O <ClassNamespace>             .NET namespace in which the class isgenerated
    /L <Generated Language>         One of the following. Defaulted to CS
                                                            CS - CSharp(C#)
                                                            VB - Visual Basic
                                                            JS - JScript
    /P <FilePath>                               Output file path
    /M <Machine>                            Remote computer to connect. Defaults to the local machine
    /U <User>                                    User name
    /PW <Password>                        Password
    /?                                                   Displays this help screen

    Example : MgmtclassGen Win32_Logicaldisk /L VB /N root\cimv2 /P c:\temp\logicaldisk.vb

    Note : The help also gives an example showing how to use the tool.

    Let us now create our own managed class for SoundDevice and Desktop Monitor associated with our machine.

    Go to VS.Net and type the following command to generate a managed class forsound device

           Mgmtclassgen Win32_SoundDevice /L CS /N root\cimv2 /P soundDevice.cs

    You should get the following message

           Microsoft (R) Management Strongly Typed Class Generator Version 1.1.4322.573
           Copyright c Microsoft Corporation 1998-2002. All rights reserved.
           Generating Code for WMI Class Win32_SoundDevice ...
           Code Generated Successfully!!!!

    Use the below command to generate a managed class for desktop monitor

           Mgmtclassgen Win32_DesktopMonitor /L CS /N ROOT/CIMV2 /P DesktopMonitor.cs

    You should get the following message

           Microsoft (R) Management Strongly Typed Class Generator Version 1.1.4322.573
           Copyright c Microsoft Corporation 1998-2002. All rights reserved.
           Generating Code for WMI Class Win32_DesktopMonitor ...
           Code Generated Successfully!!!!

    Managed classes for SoundDevice and DesktopMonitor are ready !!!!

    Let use them in our application.

    Create a console application and add these two classes to the project.

    Add using WMI = ROOT.CIMV2.Win32 at the top. Here WMI is an alias to the namespace name.

    Type the following code in the static Main() for your class

                   public static void Main()
                   {
                           Console.WriteLine(WMI.SoundDevice.GetInstances().Count);

                           foreach(WMI.SoundDevice sd in WMI.SoundDevice.GetInstances())
                           {
                                   Console.WriteLine(sd.DeviceID);
                                   Console.WriteLine(sd.SystemName);
                                   Console.WriteLine(sd.Description);
                           }

                           Console.WriteLine("MONITOR");

                           Console.WriteLine("       ");

                           Console.WriteLine(WMI.DesktopMonitor.GetInstances().Count);

                           foreach(WMI.DesktopMonitor DM in WMI.DesktopMonitor.GetInstances())
                           {
                                   Console.WriteLine(DM.ScreenHeight + " " + DM.ScreenWidth);
                           }

                           Console.ReadLine();
                   }


    In the above code we displaying values of some basic properties for sound device and desktop monitor.

    CertMgr.exe (.Net FrameWork Tools Series)

    After discussing most of the security tools today we will look at certificate manager. This tool is shipped with dotnet and allows us to manage certificates on your machine.

    This tool can be used as a console application as well as a windows application.

    To check out the various options of certmgr type certmgr /?. If you type only certmgr then the windows interface will be loaded.

    Let us explore the windows interface of this application.

    The application starts by showing the "Certificates" windows dailogue. You can view 4 tabs on it namely Personal, Other people, Intermediate certification authorities and trusted root certification. All these tabs will show certificates which are registered under them.  

    You also have options to add,delete or export the certificate. Check out the advanced options which allows you to load or import a certificate FOR A LIST OF DIFFERENT PURPOSES IN DIFFERENT FORMATS.

    To view the certificate select the certificate and click on view.

    All these options which are available to you through the windows interface are also available to you through the VS.NET command prompt options.

    Let us create our own certificate and add it. Adding the certificate with the windows interface of this untility is very easy so let us try and add the certifiicate from the console.

    Let us create a certificate for a company called as Nasha.com

            makecert MyCer.cer -n "CN=Nasha.com"

    Now let us add this certificate to the default system certificate store

            certmgr -add MyCer1.cer  -s my

    Note: to add this to any other store write the store name instead of "my". "my" points to the default personal store n your machine.

    To view all the certificates in the store type the following command :--

            certmgr -all -s my ( or the store name instead of "my").

    To delete your certificate from the store use the -del option. If you want to delete all the certificates in the store use -all option along with it.

            certmgr -del -all -s my

    To save the certificate in another file use /put option. E.g. to save the certificate in the MyStoreFile.

    Type certmgr.exe -put -c -s MyStoreFile ... At the end you will be prompted from the certificate number to be copied to the mentioned file. Certificate number is any between 1 to the number certificates present in that store. If you carefully observe the output all certificates are displayed with output number. E.g.

    ===========Certificate # 1 ==========

    This utility can also be used to manage certificate trust lists (CTL) and certificate revocation lists (CRL).

    To view all the CTLs and CRLs in MyComp Store

    certmgr -all -crl -s MyComp
    certmgr -all -ctl -s MyComp

    Security Tools Part -- 2 (.Net FrameWork Tools Series)

    Yesterday we created our own certificate installed the certificate in the certificate store and even created a key container for the same.

    Today we will use this certificate to create our Software Publicers certificate and then sign our assembly with it.

    To create a software publishers certificate .net framework has provided us with cert2spc tool.

    This utility takes one or more X.509 certificates and creates a software publishers certificate (SPC).

    Let us create our SPC.

            cert2spc myComp.cer Mycomp.spc

    After creating our SPC we will now go ahead and sign our assembly.

    Go to VS.Net command prompt and type signcode a wizard will open up. This is a wizard based utility for signing your assemblies although you can use it with various options from the command prompt also.

    To check out the various options by typing signcode /?. For signing our assembly we will use the wizard.

    Type signcode and hit the Enter key to intiate the wizard.
    Go ahead and select the file that you want to digitally sign (SELECT AN EXECUTABLE FILE I.E. .exe).
    From the signing options select the Custom and click next
    Then select the select from file option and select either your .cer or your .spc file (Both are supported). Click Next.
    To select the private key you can either select the private key from the .pvk file or you can select the private from your key store.

    Note: You can extract your private key to .pvk file using makecert if you wish to store it in your machine ( but pls be careful if u are using this option). Since we had added our key to the key container in our machine we will pick up from there.

    So select the first option private key file on disk if you have .pvk file or select  private key in a CSP if you want to select it from your key container.

    We will go ahead with the second option let rest of the values be default .... select the key container as MyCompCont. The one we created yesterday.

    Select any one of the hash algo's either md5 or sha1. Click Next , Next , enter the description and web location (they are optional) and reach to the finish.  Click finish . you should get a message saying " The Digital Signing wizard was completed successfully."

    Go to Windows Explorer and check the properties of your assembly it will now show a new tab called Digital Signatures shown your digital signed certificate.    

    Let us now check whether the this assembly is trust worthy source or not.

    For that we will use an another chktrust tool that is shipped with .NET FrameWork tools.

    Go to VS.NET command prompt and run chktrust.exe with the name of your signed exe.

            chktrust.exe MyExecutable.exe

    If the trust for test root is enabled on your machine then then chk trust will succeed else it will fail. By default it should be disabled hence this chktrust should fail

    Hence when you run for your excutable ir should give u a warn pop-up saying that test root is not enabled as trusted root.

    To enable test root as a trusted root we will have to set its value to true

    Go to VS.Net command promt and run setreg as follows

            setreg.exe 1 true /// This will set test root as trusted root.

    Now re-run the above command

             chktrust.exe MyExecutable.exe

    This time it should give u a security wanring saying  " *** TEST CERTIFICATE *** " and saking you whether content from MyComp Technologies should be trusted or not. Click on yes ...

    To explore other options of chktrust and setreg type chktrust /? and setreg /?.

    Security Tools Part -- 1 (.Net FrameWork Tools Series)

    Today we look in to creating software digital certificates but we take a plunge in that we will look at certain aspects of Crytography.

    Cryptography is about keys for encryption. These keys can be symmeteric or asymmetric. When we say symmetric keys what we mean is that the same key is used for encryption and decryption. In case Asymmetric keys there are different keys for encryption and decryption like the public key and the private key. e.g. if something is encrypted with private key then it can decrypted with public key and vice-versa.

    These keys are always created as a "key-pair". Generally public key is given to everyone and private key is kept safely with oneself.

    .Net provides us with a utility called as makecert.exe to create X.509 test certificates. Now the most obivious question that comes to mind is what are these X509 certificates and what is there relation to cryptography?

    Well, X.509 certificates is a certificate issued by Certification Authorities like Verisign etc which holds the public key. This certificate ensures that the digital certificate actually belongs to the organisation u trust and not any other 3rd party.

    This concept has not been introduced with .Net infact it has used since quite some time to sign Active X controls. In .Net these certificates can be used to sign assemblies so that the client who is using these assemblies is sure of its source.

    You find more details of how to go about using X.509 certificates in .Net through code under the System.Security.Cryptograpgy.X509Cerficates Namespace

    You can go to the VS.Net command prompt and type makecert.exe this will down all the options.To view the basic options type -? option and to view the extended options type -!.

    Some of the important options are :

    -sk <keyName> Subject's key container name; To be created if not present
    -ss <store> Subject's certificate store name that stores the output certificate
    -sr <location> Subject's certificate store location. <CurrentUser|LocalMachine>. Default to 'CurrentUser'
    -n <X509name> Certificate subject X500 name (eg: CN=Fred Dews)
    -sv <pvkFile> Subject's PVK file; To be created if not present
    -b <mm/dd/yyyy> Start of the validity period; default to now.
    -e <mm/dd/yyyy> End of validity period; defaults to 2039
    -r Create a self signed certificate


    Let us create our certificate. To create a certificate it has to be issue to an authority e.g. here we are creating an certificate for a company called MyComp technologies. We want that the certificate that is created is to stored in our personal certificate store on our machine hence we give an option -ss with value as my. Along with that we also want to create a key container for the certificate called MyCompCont. Finally our command will be

    makecert -sk MyCompCont -ss my -n "CN=MyComp Technologies" MyComp.cer

    This command will create a certificate and install it in Personal Certificate Store on your machine for the current user and also create a key container named MyCompCont to store your public and private keys.

    You can also use -sv option to create a .pvk to store your private key in a file. If you do this than please be careful of not leaving your private key any where your key must be immediately backed up and delete from your machine else any one can use it easily.

    You can view the store from Microsoft Management Console using (mmc.exe).
    Run the mmc.exe
    Select the Add/Remove Snapin Option
    select the Certificate from the list of snapins.
    Then you will be presented with a choice between MyUserAccount, Computer Account etc.
    Select MyUserAccount and Add the snap in.
    Then re-select the Certificate snap in this time select the Computer Account option.
    Select your local machine in the wizard options.
    Thus now you have both Certificate (Local Computer) and Certificate for Current User in your mmc console.


    Check out Personal store for Current User. The certificates folder under it will contain the certificate.

    If you want to create a certificate for any user on the local machine then use "-sr Localmachine" option

    makecert -sk MyCompCont -ss my -n "CN=MyComp Technologies" MyComp.cer -sr LocalMachine

    Similarly you will find the certificate created in Personal store under certificates for local machine.

    The certificate file is created by any of the above options is stored at the path from where the exe is executed from the VS.Net command prompt. Go to the folder respective folder and check out your certificate file i.e. MyComp.cer.

    Fuslogvw.exe -- Excellent Tool (.Net FrameWork Tools Series)

    All us of us has had issues with assembly binding, but very few of us know about the assembly binding viewer. This is a utility tool which is packaged along with the .Net FrameWork Tools. This utility tool allows you to view all assembly bindings of an application.In case there is a failure then the failure can be logged and you can view the log later. This log gives a complete discription of the failure.

    Let us get started with fuslogvw aka Assembly binding viewer.

    1) Create three dot net projects one a class library called BindiingDLL , one a Console App called BindingConsoleClient and other one a Web Application know as WebBindingClient.

    2) The console app and the web app will have a reference to the class library.

    3) Create a method in the Class Library project called as Add which simply add's two numbers and returns the result

    public int Add (int i ,int j)

    {

    return i + j;

    }

    4) Build the DLL.

    5) In the Console App call the Add function in its main.

    [STAThread]

    static void Main(string[] args)

    {

    BindingDLL.classBind bindingObj = new BindingDLL.classBind();

    Console.WriteLine(bindingObj.Add(1,2).ToString());

    Console.ReadLine();

    }

    6) Build and execute the application. The application should run smoothly.Stop the application.

    7) For the viewer to log all the results we need to add certain keys in the registry. Most of the machine I have seen dont have these keys. If your machine has then simply change its value else create a new DWORD key named ForceLog. The value of this key should be greater than 0.

    ==> HKLM\Software\Microsoft\Fusion\ForceLog

    8) Go to VS.Net command prompt and type fuslogvw.

    9) The application starts this utility has 3 columns Application,Description and Date/Time. Click on Refresh. See that

    Default is selected at the bottom.

    10) Now rerun your application , you should be able to see an enrty for your app in the log viewer.

    11) Double click on the entry or select the entry and click on view log to view the log details.

    12) This is sample log for a successful binding.

    *** Assembly Binder Log Entry (11/17/2004 @ 6:37:35 AM) ***

    The operation was successful.

    Bind result: hr = 0x0. The operation completed successfully.

    Assembly manager loaded from:

    C:\WINNT\Microsoft.NET\Framework\v1.0.3705\fusion.dll

    Running under executable

    F:\Net\BindingConsoleClient\bin\Debug\BindingConsoleClient.exe

    --- A detailed error log follows.

    === Pre-bind state information ===

    LOG: DisplayName = mscorlib, Version=1.0.3300.0, Culture=neutral,

    PublicKeyToken=b77a5c561934e089

    (Fully-specified)

    LOG: Appbase = C:\WINNT\Microsoft.NET\Framework\v1.0.3705\

    LOG: Initial PrivatePath = NULL

    LOG: Dynamic Base = NULL

    LOG: Cache Base = NULL

    LOG: AppName = NULL

    Calling assembly : (Unknown).

    ===

    LOG: Not processing DEVPATH because this is a pre-jit assembly bind.

    LOG: Policy not being applied to reference at this time (private,

    custom, partial, or location-based assembly bind).

    LOG: Post-policy reference: mscorlib, Version=1.0.3300.0,

    Culture=neutral, PublicKeyToken=b77a5c561934e089

    LOG: Found assembly by looking in the cache.

    13) Now to log failure check the Log Failure check box.

    14) Now you can just rename the dll to BindingDLL_old.dll and RUN THE CONSOLE CLIENT APPLICATION. DO NOT BUILD THE

    SOLUTION.

    15) The binding should fail since the file is not present.

    16) The log viewer should an entry for the failure as follows

     

    *** Assembly Binder Log Entry (11/17/2004 @ 6:40:45 AM) ***

    The operation failed.

    Bind result: hr = 0x80070002. The system cannot find the file specified.

    Assembly manager loaded from:

    C:\WINNT\Microsoft.NET\Framework\v1.0.3705\fusion.dll

    Running under executable

    F:\Net\BindingConsoleClient\bin\Debug\BindingConsoleClient.exe

    --- A detailed error log follows.

    === Pre-bind state information ===

    LOG: DisplayName = BindingDLL, Version=1.0.1782.11785,

    Culture=neutral, PublicKeyToken=null

    (Fully-specified)

    LOG: Appbase = F:\Net\BindingConsoleClient\bin\Debug\

    LOG: Initial PrivatePath = NULL

    LOG: Dynamic Base = NULL

    LOG: Cache Base = NULL

    LOG: AppName = NULL

    Calling assembly : BindingConsoleClient, Version=1.0.1782.11845,

    Culture=neutral, PublicKeyToken=null.

    ===

    LOG: Processing DEVPATH.

    LOG: DEVPATH is not set. Falling through to regular bind.

    LOG: Attempting application configuration file download.

    LOG: Download of application configuration file was attempted from

    file:///F:/Net/BindingConsoleClient/bin/Debug/BindingConsoleClient.exe.config.

    LOG: Application configuration file does not exist.

    LOG: Policy not being applied to reference at this time (private,

    custom, partial, or location-based assembly bind).

    LOG: Post-policy reference: BindingDLL, Version=1.0.1782.11785,

    Culture=neutral, PublicKeyToken=null

    LOG: Attempting download of new URL

    file:///F:/Net/BindingConsoleClient/bin/Debug/BindingDLL.DLL.

    LOG: Attempting download of new URL

    file:///F:/Net/BindingConsoleClient/bin/Debug/BindingDLL/BindingDLL.DLL.

    LOG: Attempting download of new URL

    file:///F:/Net/BindingConsoleClient/bin/Debug/BindingDLL.EXE.

    LOG: Attempting download of new URL

    file:///F:/Net/BindingConsoleClient/bin/Debug/BindingDLL/BindingDLL.EXE.

    LOG: All probing URLs attempted and failed.

    17) The last option at the bottom is Custom. To activate this option you need to add a STRING key in the registry named LogPath.Set the value of this to any empty directory. The logs will be created in this folder. Please make sure that the your delete the logs regularly if you using the custom option.

    ==> HKLM\Software\Microsoft\Fusion\LogPath

    18) Close the viewer in case it is running. Rerun the viwer from VS.Net command prompt. Select the Custom option and click refresh.Again run the Console Application this time the entries will be displayed for the Custom option . Click on refresh incase you are unable to view the log entries.

    19) To use the middle option ASP.NET. This option misbehaves at times. But I have found a work around for that. Since we have now set a path to log all our errors in a custom specified folder (The folder specified in the logpath) all the errors including ASP.NET will be logged in that folder.

    20) Add a button in the web form and call the Add function from the web client.

    private void Button1_Click(object sender, System.EventArgs e)

    {

    BindingDLL.classBind bindingObj = new BindingDLL.classBind();

    Response.Write(bindingObj.Add(1,2));

    }

    21) Now execute the WEB application and Click on the Refresh button on the Viewer. CHECK THAT THE CUSTOM OPTION IS SELECTED AT THE BOTTOM.

    22) You will see a couple of entries for aspnet_wp and some unique number say "98e17ea7" which represents your web application.

    23) Double click on the your application entries to view the log. Since we have checked the log failure option if there is a binding failure with our Web App it will be logged.

    24) Again rename the BindingDLL to BindingDLL_old.dll and rerun the application. You will a similar error

     

    *** Assembly Binder Log Entry (11/17/2004 @ 11:24:57 AM) ***

    The operation failed.

    Bind result: hr = 0x80131040. No description available.

    Assembly manager loaded from:

    C:\WINNT\Microsoft.NET\Framework\v1.1.4322\fusion.dll

    Running under executable

    C:\WINNT\Microsoft.NET\Framework\v1.1.4322\aspnet_wp.exe

    --- A detailed error log follows.

    === Pre-bind state information ===

    LOG: DisplayName = BindingDLL_old

    (Partial)

    LOG: Appbase = file:///c:/inetpub/wwwroot/WebBindingClient

    LOG: Initial PrivatePath = bin

    LOG: Dynamic Base =

    C:\WINNT\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET

    Files\webbindingclient\d7b2a0d4

    LOG: Cache Base = C:\WINNT\Microsoft.NET\Framework\v1.1.4322\Temporary

    ASP.NET Files\webbindingclient\d7b2a0d4

    LOG: AppName = 98e17ea7

    Calling assembly : (Unknown).

    ===

    LOG: Processing DEVPATH.

    LOG: DEVPATH is not set. Falling through to regular bind.

    LOG: Policy not being applied to reference at this time (private,

    custom, partial, or location-based assembly bind).

    LOG: Post-policy reference: BindingDLL_old

    LOG: Attempting download of new URL

    file:///C:/WINNT/Microsoft.NET/Framework/v1.1.4322/Temporary ASP.NET

    Files/webbindingclient/d7b2a0d4/98e17ea7/BindingDLL_old.DLL.

    LOG: Attempting download of new URL

    file:///C:/WINNT/Microsoft.NET/Framework/v1.1.4322/Temporary ASP.NET

    Files/webbindingclient/d7b2a0d4/98e17ea7/BindingDLL_old/BindingDLL_old.DLL.

    LOG: Attempting download of new URL

    file:///c:/inetpub/wwwroot/WebBindingClient/bin/BindingDLL_old.DLL.

    LOG: Assembly download was successful. Attempting setup of file:

    c:\inetpub\wwwroot\WebBindingClient\bin\BindingDLL_old.DLL

    LOG: Entering download cache setup phase.

    WRN: Comparing the assembly name resulted in the mismatch: NAME

    ERR: The assembly reference did not match the assembly definition found.

    ERR: Setup failed with hr = 0x80131040.

    ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

    25) To log failures for satellite assemblies create a DWORD key called LogResourceBinds and set its value to more than 0.

    ==> HKLM\Software\Microsoft\Fusion\LogResourceBinds

    Xsd.exe (.Net Framework Tools Series)

    Today we will discuss Xsd.exe tool.
     
    All of us know about xml serialization and deserialization. When we say xml serialization we mean to say that we convert an objects public properties into xml attributes and/or xml elements. You should use Binary Serialization techniques to archive private data of an object.
     
    There is a tool in the .net framework which can help us creating xml serialization classes,datasets,xml schemas from various xml
    formats and even compiled assemblies.
     
    1) Let us get started by creating an sample xml file containing employee information.
     
        <employeeInfo>
         <employee>
          <empid>1</empid>
          <firstname>Namratha</firstname>
          <lastname>Shah</lastname>
          <sex>F</sex>
          <address>
           <street>1</street>
           <city>mumbai</city>
           <state>maharashtra</state>
           <pin>400056</pin>
           <country>India</country>
          </address> 
         </employee>
        </employeeInfo>
     

    2) Name the file as employeeInfo.xml.
     
    3) This tool can be primarily used to generate xml schema file (.xsd) from an xml data file (.xml). The following command generates
        employeeinfo.xsd from employeeinfo.xml :

         xsd.exe employeeinfo.xml

    You should get a message 

         Writing file 'C:\xsd\employeeinfo.xsd'.
     
    4) To explore all the options of xsd.exe type xsd /?
     
    5) This tool can also be used to generate xml serialization classes and datasets. Now we will generate employeeinfo class and
       dataset.
     
    6) To generate a class from schema give /c option and to generate dataset use /d option

             xsd.exe employeeinfo.xsd /c  // to generate xml serilization class
             xsd.exe employeeinfo.xsd /d  // to generate dataset

        You should get a message 

             Writing file 'C:\xsd\employeeinfo.cs'.
     
    7) Xsd.exe is also used to generate schema of types present in comlied assemblies.
     
    8) Let us generate our employeeinfo class with the /c option as shown below and then add this class to a class library and   regenerate schema of the class from its dll
     
    9) Generate the class with the following command xsd.exe employeeinfo.xsd /c . If you are a VB.Net person than you can use the
       /l:VB option with it to generate the class in VB.
     
    10) Open a new class library project (C# or VB). Add this class to the project, compile the project and create the dll.
     
    11) Now to generate schema of a type from a compiled assembly :

             xsd <Your Dll Name>.dll  e.g. xsd EmployeeInfoLib.dll

         This will generate the schema of the various types present in the dll since we have only one class you should get a message

             Writing file 'C:\xsd\schema0.xsd'.
     
    12) To generate schema of any type from a complied assembly the class should be marked with xmlrootattribute. If you look at the
    employeeinfo class that we added to the assembly you will notice xmlroot attribute right at the top of the class declaration.
     
         /// <remarks/>
         [System.Xml.Serialization.XmlRootAttribute("employeeInfo", Namespace="", IsNullable=false)]
          public class employeeInfo {

    Only classes marked with xmlroot attribute will be recognized by xsd.exe.
     
    13) If you want to generate schema for any particular type in the assembly you can use the /type option. We can generate schema of employee address as follows:

         xsd <Your Dll Name>.dll /type:rootEmployeeAddress  /// check the name in the class.
     
    I hope these articles that I am posting help all of us. If you have any doubts/sugegstions/improvements/queries etc. please post them I may not be in a position to reply them immediately as I am working .... but you will definitely get an answer sooner or later.
     

    What is Isolated Storage ? ( Part- 2 .Net FrameWork Tools Series )

    To continue with our exploration on Isolated Storage Let us go ahead and create a sample application.

    1) Open a new Win App Place one listbox, one textbox and one button on the form.

    2) Our gaol is to serialize the contents of the listbox when the application shut downs and when the application runs it should load the serialized data back. IsolatedStorage works in a similar way as the file system . You can say it is a special type of file system which is specific to your application.Only your application knows where the files are stored.

    3) Getting started we will create a .txt file for our application in IsolationStorage which will hold all the serilized data. We first need to get the reference of the IsolatedStorage Store for out application. We do that by calling a static function of IsolatedStorageFile object called GetStore.

    4) Add code in the click event of the button to add the text entered in the textbox as an item in the listbox

    listBox2.Items.Add(textBox1.Text);
    textBox1.Text = "";

    5) Since we have got reference to the store we can go ahead and create our textfile to store our data.We need to serialize all the items in the listbox. We will handle this in the Form Closing event.

    6) Get the reference to the Application Store by calling GetStore method on IsolatedStorageFile class

    IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User,null,null);

    If you check out all the other static methods of this object you will see that there are specific methonds to get Isolated Stores for User and Application Domain called as GetUserStoreFor Assembly and GetUserStoreForDomain. While calling this function remember to put a combination of two or more options for IsolatedStorageScope. This does not take a single value. Here we have given the scope as Assembly and User.

    7) Our second step will be to create a text file to hold our data. So we create a file named "IsolatedStoreProj.txt" using the IsolatedStorageFileStream object.

    IsolatedStorageFileStream isfs = new

    IsolatedStorageFileStream("IsolatedStoreProj.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO.

    FileShare.ReadWrite,isf);

    8) Now just loop through the items in the listbox and serialize all the data in the text file. After wrting the data in the file stream close the file stream.You complete code should look something like this :-

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User,null,null);
    IsolatedStorageFileStream isfs = new IsolatedStorageFileStream ("IsolatedStoreProj.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO. FileShare.ReadWrite,isf);
    string [] sItems = new string[10];
    listBox1.Items.CopyTo(sItems,0);
    string oneString = null;
    for(int i=0;i<sItems.GetLength(0);i++)
    {
    if(sItems[i] != null)
    oneString += sItems[i].ToString() + ",";

    else

    break;
    }
    oneString = oneString.Substring(0,oneString.Length - 1);
    System.Text.ASCIIEncoding asc = new System.Text.ASCIIEncoding();
    byte [] byteArray = asc.GetBytes(oneString);
    isfs.Write(byteArray,0,byteArray.GetLength(0));
    isfs.Close();
    isf.Close();
    }

    9) Compile and run this code. On exiting the application a text named IsolatedStoreProj.txt should be created. This file will be created in at the follwoing location

    <drive>:\Documents and Settings\<user>\Local Settings\Application Data\IsolatedStorage\<some folder>\<some folder>\AssemFiles\IsolatedStoreProj.txt

    10) Open the file and you will be able to view the contents we had serialized.

    11) Now let us load this data when our application starts up. We will read this file in the form_load event and populate our listbox.

    private void Form1_Load(object sender, System.EventArgs e)
    {
    IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User,null,null);
    IsolatedStorageFileStream isfs = new IsolatedStorageFileStream ("IsolatedStoreProj.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Read,System.IO.FileShare.Read,isf);
    byte[] byteArray = new byte[10000];
    isfs.Read(byteArray,0,(int)isfs.Length);
    System.Text.ASCIIEncoding asc = new System.Text.ASCIIEncoding();
    string twoString = asc.GetString(byteArray);
    string[] oneArray = twoString.Split(new char[]{','},10);
    for(int i=0;i<oneArray.GetLength(0);i++)
    listBox2.Items.Add(oneArray[i]);
    isfs.Close();
    isf.Close();
    }

    12) In this way we can store our user setting , application related data in the Isolated store.

    13) This store that we have created in our sample application is a non-roaming store. To create a roaming store give the scope as IsolatedStorageScope.Roaming along with assembly and user as specified above.

    14) WinNT and Operationg systems after it have a feature called as roaming user profiles which allows the user to carry his perferences and presonal settings across machines on the network.On the same lines .Net provides us with roaming assembly stores so if the user has a roaming Windows profile his roaming assembly store will also roam.

    15) The assembly store is roaming only if it is mentioned explictly by mentioning the IsolatedStorageScope if it is not then the scope is non-roaming by default. Even if the user profile is roaming the isolated store can be non-roaming.

    16) You can create and list stores through code as well as use storeadm.exe for the same ( as per Part -1).

     

    What is Isolated Storage Part - 1 (.Net FrameWork Tools Series)

    After a long week end I am back again. Its nice and refreshing after a short vacation so lets get started with .NET once again.

    Today we will discuss about Isolated Storage. This is one of the topics which I find interesting as I feel that it has a lot of practical usage or applicability.

    We all know that all applications need some storage space to archive certain application information like users preferences, appliction info, or certain data which can be cached on the user's local machine etc. Initially all this information was stored in .ini files which were simple to use and manage. Being a flat file their access was easy and Microsoft also provided us with API's to access these files. But the only problem with .ini files was where do u put these ini files and if the files were lost it would result in an application nightmare.

    To solve this problem microsoft came up with an another idea for storing application related information i.e. The Windows Registry. Although registry was good for storing application related information it was very slow coz of its hierarcial nature. Loading information of all the applications in the machine's registry made the search slow. Secondly application downloaded from the web can not be granted access to the local machines registry. Hence it could not be used for web apps.

    To solve all the above problems Micorsoft with .NET has now come up with the idea of Isolated Storage.

    Isolated storage enables paritally trusted applications to store data as per computer's security policy esp. the web app's and other downloaded components. Code running on the local computer ,local network or the Internet is granted the right to use this isolated storage.

    Isolated storage isolates data by user or by assembly. Credentials such as the origin, strong name of the assembly or application domain can be used to isolate data.

    But what is isolated storage ?

    Well Isolated storage is a special folder on your harddisk which allows your application to store its application specific data. Isolated stores are put up at Microsoft\IsolatedStorage directory.Change folder settings to show hidden files and folders in order to see isolated storage.

    On Windows 2000 you will be able to view "IsolatedStorage" folder at :-

    Roaming-enabled stores = <drive>\Documents and Settings\<user>\Application Data

    Non-roaming stores = <drive>\Documents and Settings\<user>\Local Settings\Application Data

    All applications have a special allocated place to store their data which is a data folder containing one or more isolated storage files, called stores in this folder. These stores contain the actual directory locations where data is stored. The data saved in the store can be any kind of data from user's preference information to application state.

    To access isolated storage the code must be have appropriate IsolatedStorageFilePermissions and all necessary native platform

    operating system rights.

    e.g. On an OS like Win 2000 the access control lists (ACLs) controls which users have the rights to use the file system. Hence web applications dont have access to the local hard disk. But these applications have access to the Isolated storage folder on the client machine to store any application data. Thus inspite of not having access to the local harddisk web app can store data related to their application in the IsolatedStorage folder.

    Microsoft .NET Framework applications already have operating system rights to access isolated storage unless they perform

    impersonation.

    Let us use the storeadm.exe tool to list ,add and delete isolated stores.

    1) You can go to the VS.NET command prompt and type storeadm.exe /? to view all the options.

    Usage : StoreAdm [options]

    options : [/LIST] [/REMOVE] [/ROAMING] [/QUIET]

    /LIST : Displays the existing isolated storage for the current user.

    /REMOVE : Removes all existing isolated storage for the current user.

    /ROAMING : Select the roaming store.

    /QUIET : Only error messages will be output.

    2) Use the storeadm /LIST option to list all the stores on your machine. This will list all the stores in your local machine.

    You can use isolated storage just like any other file system folder. There are special IsolatedStorageFileStreams to create files and directories. Tomorrow we will see how we can create these isolated stores.

    December 11

    Webservice Tools (Disco and wsdl -- .Net FrameWork Tools Series)

    All of us have worked with web services but very of us have worked with the command line tools provided by .Net framwork. Today we will discuss .Net Webservice Tools disco.exe and wsdl.exe.

    Disco.exe :-

    Discovey is the most important step when it comes to webservices. This tool discovers the URL's of XML webservices on a given web server. Discovery of webservices is important for its consumers as from the discovery document they can know about the various services they can consume.

    This tool locates the webservice. If it finds the webservice it creates .wsdl, .xsd, .disco, and .discomap files and if it does not then the error message displayed to the user.

    Let us use this tool to discover our webservice and create the above files:

    1) Go to the VS.NET command prompt

    2) Run disco.exe /? for checking out all the options

    3) This is a list of some important options :

    /nosave - Do not save the discovered documents or results to disk (for example wsdl, xsd and disco files). The default is to save the documents.

    /out:<directoryName> The output directory to save the discovered documents in. The default is the current directory. Short form is '/o:'.

    /username:<username>

    /password:<password>

    /domain:<domain> The credentials to use when the connecting to a server that requires authentication. Short forms are '/u:', '/p:' and '/d:'.

    /proxy:<url>The url of the proxy server to use for http requests.The default is to use the system proxy setting.

    4) To discover the disco files of the webservice give the URL of the web service as

    disco.exe http://localhost/MyWebservice/service1.asmx /nosave .

    If the URL is found the following message will be displayed to you :

    Microsoft (R) Web Services Discovery Utility

    [Microsoft (R) .NET Framework, Version 1.0.3705.0]

    Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.

    Disco found documents at the following URLs:

    http://localhost/MyWebservice/service1.asmx?disco

    http://localhost/MyWebservice/service1.asmx?wsdl

    5) We will now perform the same command without /nosave option to save the document in MyWebSerDocs folder. Please see to it

    that the directory exists as this tool does not create the directory

    disco.exe http://localhost/MyWebservice/service1.asmx /out:MyWebSerDocs

    6)You should see a similar output

    Microsoft (R) Web Services Discovery Utility

    [Microsoft (R) .NET Framework, Version 1.0.3705.0]

    Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.

    Disco found documents at the following URLs:

    http://localhost/MyWebservice/service1.asmx?disco

    http://localhost/MyWebservice/service1.asmx?wsdl

    The following files hold the content found at the corresponding URLs:

    MyWebSerDocs\service1.disco <- http://localhost/MyWebservice/service1.asmx?disco

    MyWebSerDocs\service1.wsdl <- http://localhost/MyWebservice/service1.asmx?wsdl

    The file MyWebSerDocs\results.discomap holds links to each of these files.

    7) Check out the directory it should have all the above 3 files i.e. Service1.disco, Service1.wsdl and results.discomap

    8) Similarly you can discover any web service with this tool and create the .disco, .wsdl and discomap files.

    9) These files that we have generated with disco.exe can be used as an input to wsdl.exe to create our webservice proxy class.

    WSDL.exe :-

    This tool is used to generate webservice proxy class. This file contains all the details for its clients to use when they are interacting

    with the webservice.

    Let us create the webservice proxy class:

    1) Go to VS.Net command prompt

    2) Type wsdl.exe /? to view all the options

    3) I have listed a few important options below :

    <url or path> - A url or path to a WSDL contract, an XSD schema or .discomap document.

    /language:<language> - The language to use for the generated proxy class. Choose from 'CS','VB', 'JS' or provide a fully-qualified name for a class implementing

    System.CodeDom.Compiler.CodeDomProvider. The default is 'CS' (CSharp).

    /server Generate an abstract class for an xml web service implementation using ASP.NET based on the contracts. The default is to generate client proxy classes.

    /out:<fileName>

    The filename for the generated proxy code. The default name is derived from

    the service name. Short form is '/o:'.

    /protocol:<protocol> Override the default protocol to implement. Choose from 'SOAP', 'HttpGet','HttpPost', or custom protocol as specifiied in the configuration file.

    4) To generate the proxy class you can either use .wsdl or .discomap file that we have generated using the disco.exe or you can give the webservice url as input.

    5) We will create our proxy class using the .wsdl and .discomap files that we had generated.

    6) Type the following command :

    wsdl.exe Service1.wsdl

    or

    wsdl.exe results.discomap

    .

    Service1.cs class will be generated.

    7) You can use this proxy class with any of the client application to interact with the webservice.

    8) Create a client application say a Windows application and add the proxy class to it by choosing Add Existing Item and selecting out proxy class Service1.cs. Create the webservice object and call any method on it.

    Service1 myWebSer = new Service1();

    MessageBox.Show(myWebSer.HelloWorld());

     

    Ngen.exe -- A discussion -- Some Queries (.NET Framework Tools Series)

    Today we will discuss Ngen.exe and then there are some questions regarding Ngen which ahve always bothered me. I have managed to get answers to them .... please read thru and let me know your answers to them ... coz I am sure these questions must have bothered u also.

    Lets start with the discussion ....

    This tool is used to create a native Image from an .NET assembly and installs it into the native image cache on that computer. Since assembly image is present on the local machine cache loading of the assembly becomes faster because .NET reads data from the native image than generating them dynamically (JIT).

    This tool is available at :

    <drive>:\WINNT\Microsoft.NET\Framework\<version>\ngen.exe

     

    Lets us check out all the options of Native Image Gernerator.

    1) Go to the Visual Studio command prompt and type

    Ngen.exe /help // this will show us all options

    2) You will see the below details

     

    Administrative options:

    /show Show existing native images (show all if no args)

    /delete Delete existing native images (delete all if no args)

    Developer options:

    /debug Generate image which can be used under a debugger

    /debugopt Generate image which can be used under a debugger

    in optimized debugging mode

    /prof Generate image which can be used under a profiler

    Miscellaneous options:

    /? or /help Show this message

    /nologo Prevents displaying of logo

    /silent Prevents displaying of success messages

    Usage : ngen [options] <assembly path or display name>

    The native Image contains compiled processor-specific machine code.If you create an native image of an assembly then .NET

    Runtime tries to look out for that assembly. If it is unable to find the assembly than it reverts back to JIT.

    Incase the application is running in a debug mode than .NET runtime looks for a native image created with /debug or /debugopt option.

    Note: The assembly image created by Ngen depends on the options that we specify and below computer settings like:

    <DIR>

    The CPU type.

    The version of the operating system.

    The exact identity of the assembly (recompilation changes identity).

    The exact identity of all assemblies that the assembly references.

    Security factors.

    </DIR>

    To view all the native Images installed on the a machine go to:

    <drive>\<windows folder> say Winnt\assembly

    In the assembly folder (GAC) sort on type and you will find all the native Images installed on that machine.

    There are few questions that I have always had in my mind regarding Ngen and the assembly images:

    1) How long are these native assembly images valid ?

    Since the native assembly image is machine specific its validity depends on all the above factors. Well the are number of scenarios when the native image can become invalid :

    <DIR>

    .NET Framework updation causes all native images to become invalid.

    Computer CPU updation

    Any Changes made to the OS.

    Recompilation of an assembly to IL causes existing native images of

    that assembly to become invalid.

    Recompliation of a referenced assembly causes the native image to the

    refrencing assembly to become invalid.

    Change in machine security policy.

    </DIR>

    Hence if there is any change in the computer setting or environment then there are chances of the Native Image becoming invalid.

    Note : Its just that the assembly native image has become invalid not the assembly. hence next time the assembly will be loaded with (JIT) its native image will not be loaded.

    2) Can you create a native Image of ASP.NET assembly ... does this work ... is it possible ????

    Native Image generator creates a local image of an .NET Assembly and installs that image in the native cache on the local machine. But when you create a Native Image of an ASP.NET assembly the .NET Runtime ignores that assembly and reverts back to JIT. This is because CLR cannot load native images in a shared application domain and all ASP.NET applications run in a shared application domain. Hence although the native image of the assembly will be created it will not be installed in the image cache.

    3) How do I run Ngen as a part of Installation or deloyment of the application ?

    To run Ngen as a part of your application deployment or setup create a custom action during installation which will run the ngen and create images for all your application assemblies. Similarly also create a custom action in you deployment project during uninstallation to remove them from the native cache.

     

    These were questions that I had in my mind ... if u have any other let griup know .... if u have more thought opinions about these questions pls post them.

     

    Going ahead lets just explore a few options of Ngen.exe

    To create a native assembly

    ngen <Assembly name with its full path>

    You can also create a native images of one or more assemblies at the same time

    ngen <assembly1> <assembly3> <assembly2> <assembly4>

    To view all the assemblies in the native cache use the/show option

    ngen /show

    To delete an assembly from the cache

    ngen /delete <assembly name>

     

    Code Access Security Part - 2 (.Net FrameWork Tools Series)

    Before we start with our sample app we need to view the security configuration files on the machine. You will find them under

    <drive>\WInNT\Microsoft.NET\FrameWork\<version>\Config

    Enterprise Level Security configuration file is :- enterprise.config

    Machine Level Security configuration file is :- security.config

     

    You will find the user security configuration file in

    <drive>:\Documents and Settings\<userprofile>\Application

    Data\Microsoft\CLR Security Config\v1.1.4322\security.config

    Let us now create our sample app.In this we will create .Windows Forms application which will try and read and write to the local disk.

    1) Go to VS.NET create a new Win App.

    2) On the Form Place one text box And one button Make the multiline property of the text box true.

    3) In the click event of the button write the followinf piece of code which writes to a file wat ever is written in the text box.

    StreamWriter sWriter = new StreamWriter("C://MyTextFile.txt");

    sWriter.Write(textBox1.Text);

    sWriter.Flush();

    sWriter.Close();

    4) If you run this from your machine you will be able to create the file and write the textbox contents in it.

    Well Currently this code is executing on the local machine cause in the local mahinc policy MyComputer Zone has Full trust permission set.

    Check it out by typing caspol -m -lg

    Suppose if we were to run this same app from a local network share then the Intranet code access group does not have the permission to write to the local hard disk.

    5) Place the exe on a network share and execut it. It should give you a Security Permission Exception.

    6) Modify your code to catch the exception and give a user friendly message. Run the file again from the network share.

    Suppose that we wanted this application to run from the network share. For that we will need to change the Intranet Permission set.

    caspol.exe -chggroup 1.2 FulTrust. // This command tells to fully trust all the intranet applications

    Note : Please be extremely careful to chagne the permission sets as this can coz a lot viruses and other spy wares to come in. Change the permission sets only if you have not made any custom changes to your PC. After changing the permission set use

    caspol.exe -reset command this resets the .NET default permission sets for all code groups

    Thus in this way we can prevent malicious code to access our resources.

    Lets now explore the other options of caspol.exe

    Turning the Security On/Off

    It is possible to turn the .Net Security Off if so for any reason. By

    default it is On.

    caspol.exe -security off // to turn of the .Net security

    To reset the security to .Net default security use

    caspol.exe -reset

    To create a new code group

    caspol.exe -addgroup 1.3 -site www. <name of the site>

    /// this will add full trust for any content from this site.

    To create a code group under intranet with fulltrust to a particular share on the network

    caspol.exe -addgroup 1.2 -url file:///\\<machinename>/<foldername>/* FullTrust

    To remove a code group give the codegroup number (as shown in the list groups) with -remgroup option

    caspol.exe -remgroup 1.3.2

    To change the code group's permission( we just sw above when we changed the permission for our intranet code group)

    caspol.exe -chggroup 1.2 FullTrust

    You can add code group for a particular strong name E.g. If you have an application MyApp.exe and you want any version of this application have FullTrust you can achieve that by using the a similar command

    caspol.exe -addgroup l -strong -file \bin\debug\MyApp.exe - noname -noversion FullTrust

    This command will a new strong Name code group. You can view it by giving

    caspol -lg command.

    You will see that are already 2 strong name code groups installed by default. They belong to Microsoft and ECMA.

    Code Access Security Part - 1 (.Net FrameWork Tools Series)

    Today we are going to look at Code Access Security.

    Code access security is a feature of .NET that manages code depending

    on its trust level. If the CLS trusts the code enough to allow it ro

    run then it will execute, the code execution depends on the permission

    provided to the assembly. If the code is not trusted wnough to run or

    it attempts to perform an action which doe not have the required

    permissions then its execution is stop and the application exits.

    Code access security is primarily about protecting resources like

    your local disk,netwoek, user interface from malicious code and not a

    tool for protecting software from users which is a general misbelief.

    Code access security is based upon Code Groups and Permissions.

    Code Groups

    :- In windows we have user groups and every user belongs

    to a group. We do not give permissions to users on indiviual basis

    but rather it is more convient to create a group and give permissions

    to this group. In the same way we have code groups bring code that has

    similar characteristics and execution permissions togather.

    E.g. One of the predefined code groups is Internet. If we say that

    this code belongs to Internet code group this code has only those

    permissions which are defined by this group. Like the Internet code

    group does not have access to your local access hence all the

    applications executing under this code group will not have permissions

    to access the local hard disk.

     

    Permissions :- They are actions that each code group is allowed to

    perform e.g. Permissions to access the user interface. This permission

    management can be done at 3 levels Enterprise,Machine and User level.

    "All Code" code group is the root group. All the code groups is under

    this code group. If an assembly does not match a code group in the

    hierarchy code groups below it are not searched.

    For an assembly to be a member of any code group it need to fulfill

    its membership condition.Each code group has one and only one

    membership condition. This is the list of membership conditions in

    which "All code" membership condition is at the root.

    Let us view all the available code group membership conditions :

    1) Go to Visual Studio Command promt and type caspol /help

    2) Scroll at the bottom and you will see the following membership or "mship" options

    where "<mship>" can be:

    -allcode All code

    -appdir Application directory

    -custom <xml_file> Custom membership condition

    -hash <hashAlg> {-hex <hashValue>|-file <assembly_name>} Assembly hash

    -pub {-cert <cert_file_name> | -file <signed_file_name> | -hex <hex_string>} Software publisher

    -site <website> Site

    -strong -file <assemblyfile_name> {<name> | -noname}{<version> |-noversion} Strong name

    -url <url> URL

    -zone <zone_name> Zone, where zone can be: (MyComputer,Intranet,Trusted,Internet,Untrusted)

    Zone is the most commonly used membersip condition.These zones are

    managed from IE using the security options

    3) Go to IE. ... Tools ... Options ... Security Tab ... And you will see all these options.

    Note :- These options are set from IE they apply to the whole machine.

    4) Type caspol.exe - lg. This command will list all the code groups without the descriptions. If you want to see the descriptions

    Type caspol.exe -ld.

    5) To view the code groups of an assembly e.g. Type caspol -resolvegroups <DLLName>.dll. It will show a similar output

    Level = Enterprise

    Code Groups:

    1. All code: FullTrust

    Level = Machine

    Code Groups:

    1. All code: Nothing

    1.1. Zone - MyComputer: FullTrust

    Level = User

    Code Groups:

    1. All code: FullTrust

    Success

    6) In order to understand code access security completely we need to

    understand Permission sets very well.

    Type caspol -lp | more.

    You will see an entire list of permissions in the form of xml tags.

    We will look a few most frequently used permission sets :

    SQLCLientPermission :-- Permission to access SQL Database.

    UIPermission :- Permission to access user interface.

    FileIOPermission : - Permission to read,writing or append to file as

    well as creating folders.

    Printing Permission :- Permission to print

    WebPermission :- Prmission to make or accept connetions to/from the web.

    .Net has provided us with predefined permission sets a.k.a. named

    permssion sets. They are :-

    FullTrust

    Execution

    Nothing

    LocalIntranet

    Internet

    Everything

    Note : Only the last 3 can be modified the first three cannot altered.

    You can also view assembly premissions with caspol :-

    caspol.exe -rp <Your Assembly>.dll

    Note :- In one of my previous articles we had seen hoow to view

    assembly permissions with permview.exe.

    Now lets view the current permission sets for each code groups at

    various policy levels.

    CAS policy levels exists either at enterprise, user or machine level.

    By deffault when you listgroups using caspol machine level policy

    details are displayed to you. If you want to see user and enterprise

    policy details type -u or -en as follows :-

    caspol -u -lg // for user

    caspol -en -lg // for enterprise

    By Default .Net gives FullTrust permissions to "ALL Code " Code group

    at enterprise and user level.

    The question now is ow we determine which policy level will be used.

    Well CAS takes an intersection of all the 3 policy levels i.e. user

    enterprise and machine. Hence if you have made any changes on your

    machine's policy you administrator can easily override it by changing

    the user or enterprise policy.

    Today we have seen the code access groups, permission sets and the

    different policy levels. In my tommorrow's article we will create a

    sample app and see how we can manage security policy.

    Tlbexp .exe and Regasm.exe (.Net FrameWork Tools Series)

    TlbExp.exe and Regasm.exe tools aid us in exporting assembly information  to a type library so that non .Net Applications or unmanaged code use this type library information to call .Net assembly.
     
    Just like tlbimp which works on the entire COM Component (check out yesterdays article) tlbexp also works on the entire assembly.
     
    The entire assembly is converted at the same time. You cannot use it to generate type information for a subset of the types.
     
    Tbexp only generates the type library information for an assembly but it does not register the type libraries unlike regasm.exe

    Let us now create an assembly for which we will create a type library and use it through Visual Basic.
     
    1) Open a new dotnet project (Class Library).
    2) Add a class to the project called MyClass as below.
     
     public class MyClass
     {
      public MyClass()
      {
      }
      public int Add (int i , int j)
      {
       return i +j;
      }
      public int Mul (int i , int j)
      {
       return i *j;
      }
     }
     
    3) Strong name your assembly, Compile the project and create the assembly.
    4) Go to the visual studio command prompt and type tlbexp /? to explore all the options. I have enlisted them here
     

        /out:FileName        File name of type library to be produced
        /nologo                  Prevents TlbExp from displaying logo
        /silent                    Prevents TlbExp from displaying success message
        /verbose                 Displays extra information
        /names:FileName   A file in which each line specifies the captialization of a name in the type library.
        /? or /help              Display this usage message
     
    5) To create a typelibrary from it type the following command  tlbexp <application name>.dll e.g. tlbexp tlbexp.dll
    6) If it the export was successful a success message diplaying you the entire path and the name of the .tlb will be shown to you.
     
             Assembly exported to F:\Net\tlbexp\bin\Debug\tlbexp.tlb
     
    7) You can also use the /verbose option to check out the details of the classes that were exported.
    8) Although our typelibrary is created our assembly is not yet registered. You can register the assembly using regasm tool.
    9) Go to visual studio command prompt and type regasm /? to explore all the options. I have enlisted them here
     
        /unregister             Unregister types
        /tlb[:FileName]       Export the assembly to the specified type library and register it
        /regfile[:FileName]  Generate a reg file with the specified name instead of registering the types. This option cannot be used with                                 the  /u or /tlb options
        /codebase             Set the code base in the registry
        /registered             Only refer to already registered type libraries
        /nologo                  Prevents RegAsm from displaying logo
        /silent                    Silent mode. Prevents displaying of success messages
        /verbose                 Displays extra information
        /? or /help              Display this usage message
     
    10) To only register the assembly use the following command
              regasm <application name>.dll    e.g. regasm TlbExp.dll
    11) You can also create a ,reg file containing all the registry entries
             regasm TlbExp.dll  /regfile:myTlbExp.dll .reg
    12) You also create typelibrary from assembly using regasm tool by using /tlb option.
     
    13) To use this component from VB 6.0 put the assembly in GAC. You can do this by either using gacutil or just drag and         drop the assembly in <drive>/winnt/assembly folder.
     
    14) You can now use this assembly from VB 6.0 .
    15) Open a VB std project. Go to references . Select the .tlb file that we generated from the list.
    16) Yes you can now use your .Net assembly from VB 6.0 :).
     
    Sample code of using your .NET assembly from VB
     
        Dim tlbExp As tlbExp.MyClass
        Set tlbExp = New tlbExp.MyClass
        Label1.Caption = tlbExp.Add(1, 2)
     
    Note : You cannot use tlbexp on an assembly produced by tlbimp coz in that case u can directly use type library which was used to  produce the assembly.
     

    TlbImp (21 steps to ans your Interview Q's -.NET FrameWork Tools Series)

    /keycontainer:FileName Key container holding strong name key pair

    /delaysign Force strong name delay signing

    /nologo Prevents TlbImp from displaying logo

    /primary Produce a primary interop assembly

    /asmversion:Version Version number of the assembly to be produced :- The assembly version must be specified as:Major.Minor.Build.Revision.

    /reference:FileName

    File name of assembly to use to resolve references :- Multiple reference assemblies can be specified by using the /reference option multiple times.

    Lets now import a COM type library and check out some of these features.

    3) Create a new Windows Application.

    4) To view the list of COM components on your machine right click on the project and select add reference. In the Add refernce dialog select the COM tab.This tab will display all the COM components on your machine.

    5) I have selected to import the microsoft rich text control i.e. RICHTX32.ocx.This control will be placed in C:/winnt/system32.

    6) Copy the control to your project folder and excute the below command to generate the assembly.

    tlbimp richtx32.ocx

    7) You should get a message saying : "Type library imported to RichTextLib.dll".

    This dll that we have created can be strong named by using /keyfile: or /keycontainer or /public key option.

    8) Generate a strong name key to strong name the assembly with

    sn -k MyKey.snk.

    9) Regenerate your assembly with a strong name as follows :

    tlbimp richtx32.ocx /keyfile:MyKey.snk

    10) To change the name of the assembly produced by the tlbimp use the /out: option

    tlbimp richtx32.ocx /out:Namratha.dll

    11)Let us now copt another file called "MSACC9.OLB". You find this file on any machine with MSOffice in the "<drive>:\Program Files\Microsoft Office\Office" folder.

    12) Now crearte an interop assembly for this Component with the below command

    tlbimp msacc9.olb

    13) You will notice that it creates the following 5 assemblies

    ADODB.dll

    DAO.dll

    Office.dll

    VBIDE.dll

    Along with the main one "Access.dll"

    13) Here this assembly is internally referencing the first four assemblies and hence it has created assemblies for the same also.

    14) Microsoft does provide us with the primary interop for ADODB.dll ... hence if you want refer to the primary interop assembly and avoid generation of a new interop assembly use the /reference option.

    15) You will find all the primary interop assemblies in "<drive>:\Program Files\Microsoft.NET\Primary Interop Assemblies" folder where drive is where .NET is installed. You will see a primary interop for ADODB also.

    16) You can use the following command to refer to the existing Primary Interop Assembly (PIA .... is not Pakistan International Airlines ..just kidding ) adodb.dll.

    tlbimp msacc9.olb /reference:"C:\Program Files\Microsoft.NET\PrimaryInterop Assemblies\adodb.dll" /verbose

    17) The /verbose option will show you all the details while creating the interop assembly.

    18) If want your assembly to only refer a set of assemblies that is you have all its referneced assemblies you can give multiple references while creating the Interop Assembly and for tlbimp to use only those assemblies you can specify the /strictref option. By doing this tldimp will only and only refer to those assembly files which you have metioned with /reference option.

    19) Well If you want to create a PIA for your own COM component then use the /primary option while creating the assembly.

    20) Use the /asmversion option to maintain version of your PIA's.

    21) Now we are ready to use these assemblies in our project and inanswering our interview questions :) .

    Assembly Linker (Al.exe .Net FrameWork Tools Series)

    Assembly linker is a tool which is used to create an assembly by combining one or more modules and resource files.
     
    I had covered in one of previous articles as to wat are .netmodules. If have not read it here is the link to the same :
     
    In simple words an .netmodule is an IL file that does not have  manifest in it .... you can say its an assembly without the manifest ... and hence a non -assembly file containing IL code.

    In the yesterday's example we saw how we can create the .resources file which by itself is a binary file containing your resource data. Today we will see how we can embed or link this .resource file with other .netmodules and create an assembly
     
    1) Create 2 .netmodules say Module1.netmodule and Module2.netmodule
    2) Create a .resources file say MyResources.resources (as we created in yesterdays article ... please to the same for more details)
    3) Now type the follwoing command to combine these modules and binary resource file into a single assembly.
     
    // to create a dll.
    al Module1.netmodule Module2.netmodule /embed:MyResources.resources /out:MyExecutable.dll 
     
     // to create an exe.
    al Module1.netmodule  Module2.netmodule /embed:MyResources.resources /out:MyExecutable.exe /target:exe /Main:Class1.Main
     
     
    If you dont want to embed the resource file then use the /link option instead of /embed option with al.exe.
     
    Well if you have an want to embed or link a resource then you can compile the resource file when you are compliing the assembly with csc.exe or vbc.exe  just use /resource to embed the resource or /linkresource with the assembly.
     
    You can also achieve this from VS.Net studio by including the resource file in the project and setting the Build Action of the resource type to Embedded Resource.
     
    Al is mainly used by a lot of developers to create resource satellite assemblies esp for creating multilingual applications by creating resource assemblies for various cultures.
     
    If only resource files are passed to Al.exe, the output file is a satellite resource assembly.
     
    E.g. To create an satellite assembly for french culture
     
    1) Create a file named MyResource.fr-FR.txt
    2) Type your name=value resource data in it to generate the resource file
    3) generate the resource file with the name of MyResource.fr-FR.resources.
    4) And finally create the satellite assembly as shown below for your application
     
    al /out:MyGlobApp.resources.dll /v:1.0.0.0/c:fr-FR /embed:MyResource.fr-FR.resources, Private
     
    Note : Check out the Private keyword in the above command. You can use the "private" option if you want dont want other assemblies to use the embedded resource files by default it is "public".
     
    5) In this command we have specified the output file name , the version of this DLL , the culture "fr-FR" which denotes french and finally we are embedding the fr-FR.resources file in MyGlobApp.resources.dll
     
    6) Place this file in bin\fr-FR folder of your application and read it from the application using the ResourceManger Class.
     
    There are a lot of other options that are available with AL you can view these options by typing al /? or al /help. I am enlisting a few important or frequently used ones here :
     
     
      •   /copy[right]:<text>      Copyright message
      •   /c[ulture]:<text>         Supported culture
      •   /delay[sign][+|-]          Delay sign this assembly
      •   /out:<filename>          Output file name for the assembly manifest
      •   /t[arget]:lib[rary]          Create a library
      •   /t[arget]:exe               Create a console executable
      •   /t[arget]:win[exe]        Create a Windows executable
      •   /trade[mark]:<text>     Trademark message
      •   /v[ersion]:<version>     Version (use * to auto-generate remaining numbers)
      •   /win32icon:<filename> Use this icon for the output
      •   /win32res:<filename>   Specifies the Win32 resource file
     
    If you checkout the help at the end you will see this lines which show you how to go about using this tool.
     
    Sources: (at least one source input is required) <filename>[,<targetfile>]
             add file to assembly
     
    /embed[resource]:<filename>[,<name>[,Private]]
              embed the file as a resource in the assembly
     
    /link[resource]:<filename>[,<name>[,<targetfile>[,Private]]]
               link the file as a resource to the assembly
     

    Resource File Generator (Resgen.exe .Net FrameWork Tools Series)

    This is a resource file generation tool which converts an xml based resource formats to .net resource file i.e. (.resources) and vice-versa.

    Today we will see how we will generate

    • .txt files from .resources or .resx files.
    • .resources files from text or .resx files.
    • .resx files from text or .resources files.

    Let us start with converting a .txt file to resources or resx file

    In order to convert from one type to another we must ensure that the data written in them is in the correct format.

    Text files can only contain string resources as name=value pairs. Name here is a string that describes the resource it needs to be

    unique and the value is the resource string. All these name value pairs should start from a new line.

    Lets create a text file containing 10 name=value pairs;

    1) Create a text file name MyText.txt.


    2) Type the below name=value pairs

    name1=value
    name2=value
    name3=value
    name4=value
    name5=value
    name6=value
    name7=value
    name8=value
    name9=value
    name10=value

    3) Type the following command to generate MyResources.resx from MyText.txt.

    4) If you duplicated any of the entires you will get the below error message.

    error: Duplicate resource key!


    Else your resources will be complied successfully with the following message.


    Read in 10 resources from 'MyText.txt'
    Writing resource file... Done.

    5) To generate .resources file from .txt file use the following command resgen MyText.txt MyResources.resources

    6) To genereate .txt from .resources file or .resx file use the following commands

    resgen MyResources.resx MyTextFromRes.txt
    resgen MyResources.resources MyTextFromResources.txt

     

    7) To generate .txt file from resx file or .resource file use the following commands:

    resgen MyResources.resx MyTextFromRes.txt
    resgen MyResources.resources MyTextFromResources.txt

    There are a certain advantages or disadvantages of these format over one another :

    1) Text file format name=value pair is very convient ,easy to use and create but can contain only text strings and hence you cannot embed any objects in these files.


    2) Resx file format has the data in the xml format and hence you can embed objects. You will also be able to view the binary information about these objects e.g. embedding images in the resource files.

    Thus

    .Resources file is a binary file which is used by the assemblies
    .Resx has the data in an xml format
    .txt has the data in name=value format .... gr8 so many ways to represent and use your data.

    To use these resource files in your assembly( as a part of your assembly) you will need to embed or link it with main assembly using assembly linker or create satellite assembly.(We will look into detail about this in tommorrow's article).