namrata's profileNashaPhotosBlogListsMore ![]() | Help |
|
|
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.dll13) <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. What is Migpol ? (.Net FrameWork Tools Series)Today we will discuss migpol.exe. This tool is shipped with .NET Framework SDK. .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. Management Strongly Typed Class Generator (Mgmtclassgen.exe .Net Framework Tools SeriesToday 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. 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. 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. chktrust.exe MyExecutable.exe 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. 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\ForceLog8) 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\LogPath18) 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\LogResourceBindsXsd.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); 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) else break; 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) 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 options3) 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.wsdlor 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 options2) 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 -lgSuppose 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 applicationsNote : 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.2To 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 FullTrustYou 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 belongsto 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 outputLevel = 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 groupat 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.
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 :
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
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.
name1=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!
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
7) To generate .txt file from resx file or .resource file use the following commands: resgen MyResources.resx MyTextFromRes.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.
Thus .Resources file is a binary file which is used by the assemblies 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). |
|
|