Feeds:
Posts
Comments

Archive for August, 2007

Read-Write a Cookie
==================

Write Cookie
—————-

HttpCookie myCookie = new HttpCookie(“UserSettings”);
myCookie[“Font”] = “Arial”;
myCookie[“Color”] = “Blue”;
myCookie.Expires = DateTime.Now.AddDays(1); // Set the Cookie Expiration Time
Response.Cookies.Add(myCookie);


Read Cookie

—————
if (Request.Cookies[“UserSettings”] != null)
{
string userSettings;
if (Request.Cookies[“UserSettings”][“Font”] != null)
{
userSettings = Request.Cookies[“UserSettings”][“Font”];
}
}

Read Full Post »

FOR XML EXPLICIT

In Sql FOR XML command can be used in different way..

The most flexible is FOR XML EXPLICIT.

This command option used to generate XML from table

Cosider one table named tblProductMaster , the structure of table is

tblProductMaster (ID , ProductName)

Now write the following command

SELECT 1 AS TAG,
NULL AS PARENT,
ID AS [Product!1!ID!ELEMENT],
ProductName AS [Product!1!ProductName!ELEMENT]
FROM tblProductMaster FOR XML EXPLICIT

It will return following XML

 <Product><ID>1</ID><ProductName>Jeans</ProductName></Product>
<Product><ID>2</ID><ProductName>TShirt</ProductName></Product>
<Product><ID>3</ID><ProductName>Trouser</ProductName></Product>
<Product><ID>4</ID><ProductName>Jeans</ProductName></Product>

I hope u will like it…

Benazir

Read Full Post »

Dynamically change web.config file
============================== 

Description

// Suppose you want to remove a handler from ‘httpHandlers’
// and you want to remove modules from your ‘httpModules’
// section of you web.config file..

// Below, this is suppose your web.confile file’s sections

<httpHandlers>
<add verb=”GET” type=”DJ.Blog.FileUpload.UploadProgressHandler, FileUploadLibrary” path=”DJUploadProgress.ashx” />
</httpHandlers>
<httpModules>
<add name=”DJUpload” type=”DJ.Blog.FileUpload.UploadModule, FileUploadLibrary”/>
</httpModules>

Code 

// Now, you want to remove both section from you web.config file.

// Using these Namespaces

using System.Configuration;
using System.Web.Configuration;

// Write this code to your page_load() event

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
HttpHandlersSection sec = (HttpHandlersSection) objConfig.GetSection(“system.web/httpHandlers”);
sec.Handlers.Remove(“GET”, “DJUploadProgress.ashx”);

HttpModulesSection sec2 = (HttpModulesSection)objConfig.GetSection(“system.web/httpModules”);

sec2.Modules.Remove(“DJUpload”);

objConfig.Save();

// Your web.cofig is now changed dynamically.

Read Full Post »

  1. What’s a Windows process?
    It’s an application that’s running and had been allocated memory.

 

  • What’s typical about a Windows process in regards to memory allocation?
    Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
  • Explain what relationship is between a Process, Application Domain, and Application?
    A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
  • What are possible implementations of distributed applications in .NET?
    .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
  • What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
    Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology. 
  • What’s a proxy of the server object in .NET Remoting?
    It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
  • What are remotable objects in .NET Remoting?
    Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
  • What are channels in .NET Remoting?
    Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
  • What security measures exist for .NET Remoting in System.Runtime.Remoting?
    None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
  • What is a formatter?
    A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end. 
  • Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
    Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
  • What’s SingleCall activation mode used for?
    If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
  • What’s Singleton activation mode?
    A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
  • How do you define the lease of the object?
    By implementing ILease interface when writing the class code.
  • Can you configure a .NET Remoting object via XML file?
    Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
  • How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
    Use the Soapsuds tool.
  • Read Full Post »

    ASP.NETInterview Questions
    =========================

    1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
      inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

     

  • What’s the difference between Response.Write() andResponse.Output.Write()?
    Response.Output.Write() allows you to write formatted output. 
  • What methods are fired during the page load?
    Init() – when the page is instantiated
    Load() – when the page is loaded into server memory
    PreRender() – the brief moment before the page is displayed to the user as HTML
    Unload() – when page finishes loading.
  • When during the page processing cycle is ViewState available?
    After the Init() and before the Page_Load(), or OnLoad() for a control.
  • What namespace does the Web page belong in the .NET Framework class hierarchy?
    System.Web.UI.Page
  • Where do you store the information about the user’s locale?
    System.Web.UI.Page.Culture
  • What’s the difference between Codebehind=”MyCode.aspx.cs” andSrc=”MyCode.aspx.cs”?
    CodeBehind is relevant to Visual Studio.NET only. 
  • What’s a bubbled event?
    When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
  • Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
    Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add(“onmouseover”,”someClientCodeHere();”);
  • What data types do the RangeValidator control support?
    Integer, String, and Date.
  • Explain the differences between Server-side and Client-side code?
    Server-side code executes on the server. Client-side code executes in the client’s browser. 
  • What type of code (server or client) is found in a Code-Behind class?
    The answer is server-side code since code-behind is executed on the server. However, during the code-behind’s execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.
  • Should user input data validation occur server-side or client-side? Why?
    All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user. 
  • What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
    Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user’s browser to another page or site. This performas a trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address. 
  • Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
    Valid answers are:
    ·
    A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
    · A DataSet is designed to work without any continuing connection to the original data source.
    · Data in a DataSet is bulk-loaded, rather than being loaded on demand.
    · There’s no concept of cursor types in a DataSet.
    · DataSets have no current record pointer You can use For Each loops to move through the data.
    · You can store many edits in a DataSet, and write them to the original data source in a single operation.
    · Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
  • What is the Global.asax used for?
    The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
  • What are the Application_Start and Session_Start subroutines used for?
    This is where you can set the specific variables for the Application and Session objects.
  • Can you explain what inheritance is and an example of when you might use it?
    When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.
  • Whats an assembly?
    Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN 
  • Describe the difference between inline and code behind.
    Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
  • Explain what a diffgram is, and a good use for one?
    The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.
  • Whats MSIL, and why should my developers need an appreciation of it if at all?
    MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.
  • Which method do you invoke on the DataAdapter control to load your generated dataset with data?
    The Fill() method. 
  • Can you edit data in the Repeater control?
    No, it just reads the information from its data source.
  • Which template must you provide, in order to display data in a Repeater control?
    ItemTemplate.
  • How can you provide an alternating color scheme in a Repeater control?
    Use the AlternatingItemTemplate.
  • What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
    You must set the DataSource property and call the DataBind method.
  • What base class do all Web Forms inherit from?
    The Page class. 
  • Name two properties common in every validation control?
    ControlToValidate property and Text property.
  • Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
    DataTextField property.
  • Which control would you use if you needed to make sure the values in two different controls matched?
    CompareValidator control.
  • How many classes can a single .NET DLL contain?
    It can contain many classes.
  • Web Service Questions

    1. What is the transport protocol you use to call a Web service?
      SOAP (Simple Object Access Protocol) is the preferred protocol.
  • True or False: A Web service can only be written in .NET?
    False
  • What does WSDL stand for?
    Web Services Description Language.
  • Where on the Internet would you look for Web services?
    http://www.uddi.org
  • True or False: To test a Web service you must create a Windows application or Web application to consume this service?
    False, the web service comes with a test page and it provides HTTP-GET method to test.
  • State Management Questions

    1. What is ViewState?
      ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.
  • What is the lifespan for items stored in ViewState?
    Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).
  • What does the “EnableViewState” property do? Why would I want it on or off?
    It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.
  • What are the different types of Session state management options available with ASP.NET?
    ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a “sticky-server” (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.
  • Read Full Post »

    C# Interview Questions

    C# Interview Questions
    ====================

    This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.

    There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.

    General Questions

    1. Does C# support multiple-inheritance?
      No.
  • Who is a protected class-level variable available to?
    It is available to any sub-class (a class inheriting this class).
  • Are private class-level variables inherited?
    Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited. 
  • Describe the accessibility modifier “protected internal”.
    It is available to classes that are within the same assembly and derived from the specified base class.
  • What’s the top .NET class that everything is derived from?
    System.Object.
  • What does the term immutable mean?
    The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

  • What’s the difference between System.String and System.Text.StringBuilder classes?
    System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  • What’s the advantage of using System.Text.StringBuilder over System.String?
    StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
  • Can you store multiple data types in System.Array?
    No.
  • What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identacle object. 
  • How can you sort the elements of the array in descending order?
    By calling Sort() and then Reverse() methods.
  • What’s the .NET collection class that allows an element to be accessed using a unique key?
    HashTable.
  • What class is underneath the SortedList class?
    A sorted HashTable.
  • Will the finally block get executed if an exception has not occurred?­
    Yes.
  • What’s the C# syntax to catch any possible exception?
    A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. 
  • Can multiple catch blocks be executed for a single try statement?
    No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
  • Explain the three services model commonly know as a three-tier application.
    Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
  • Class Questions

    1. What is the syntax to inherit from a class in C#?
      Place a colon and then the name of the base class.
      Example: class MyNewClass : MyBaseClass
  • Can you prevent your class from being inherited by another class?
    Yes. The keyword “sealed” will prevent the class from being inherited.
  • Can you allow a class to be inherited, but prevent the method from being over-ridden?
    Yes. Just leave the class public and make the method sealed.
  • What’s an abstract class?
    A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
  • When do you absolutely have to declare a class as abstract?
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2.
    When at least one of the methods in the class is abstract. 
  • What is an interface class?
    Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
  • Why can’t you specify the accessibility modifier for methods inside the interface?
    They all must be public, and are therefore public by default.
  • Can you inherit multiple interfaces?
    Yes. .NET does support multiple interfaces.
  • What happens if you inherit multiple interfaces and they have conflicting method names?
    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
    To Do: Investigate 
  • What’s the difference between an interface and abstract class?
    In an interface class, all methods are abstract – there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
  • What is the difference between a Struct and a Class?
    Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.
  • Method and Property Questions

    1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
      Value. The data type of the value parameter is defined by whatever data type the property is declared as.
    2. What does the keyword “virtual” declare for a method or property?
      The method or property can be overridden.
    3. How is method overriding different from method overloading?
      When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
    4. Can you declare an override method to be static if the original method is not static?
      No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
    5. What are the different ways a method can be overloaded?
      Different parameter data types, different number of parameters, different order of parameters.
    6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
      Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

    Events and Delegates

    1. What’s a delegate?
      A delegate object encapsulates a reference to a method.
  • What’s a multicast delegate?
    A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
  • XML Documentation Questions

    1. Is XML case-sensitive?
      Yes.
  • What’s the difference between // comments, /* */ comments and /// comments?
    Single-line comments, multi-line comments, and XML documentation comments.
  • How do you generate documentation from the C# file commented properly with a command-line compiler?
    Compile it with the /doc switch.
  • Debugging and Testing Questions

    1. What debugging tools come with the .NET SDK?
      1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
      2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.
  • What does assert() method do?
    In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  • What’s the difference between the Debug class and Trace class?
    Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  • Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
  • Where is the output of TextWriterTraceListener redirected?
    To the Console or a text file depending on the parameter passed to the constructor.
  • How do you debug an ASP.NET Web application?
    Attach the aspnet_wp.exe process to the DbgClr debugger.
  • What are three test cases you should go through in unit testing?
    1. Positive test cases (correct data, correct output).
    2. Negative test cases (broken or missing data, proper handling).
    3. Exception test cases (exceptions are thrown and caught properly).
  • Can you change the value of a variable while debugging a C# application?
    Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.
  • ADO.NET and Database Questions

    1. What is the role of the DataReader class in ADO.NET connections?
      It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
    2.  

    3. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
      SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
    4. What is the wildcard character in SQL?
      Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
    5. Explain ACID rule of thumb for transactions.
      A transaction must be:
      1. Atomic – it is one unit of work and does not dependent on previous and following transactions.
      2. Consistent – data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
      3. Isolated – no transaction sees the intermediate results of the current transaction).
      4. Durable – the values persist if the data had been committed even if the system crashes right after.
    6. What connections does Microsoft SQL Server support?
      Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
    7. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
      Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
    8. What does the Initial Catalog parameter define in the connection string?
      The database name to connect to.
    9. What does the Dispose method do with the connection object?
      Deletes it from the memory.
      To Do: answer better. The current answer is not entirely correct.
    10. What is a pre-requisite for connection pooling?
      Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

    Assembly Questions

    1. How is the DLL Hell problem solved in .NET?
      Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  • What are the ways to deploy an assembly?
    An MSI installer, a CAB archive, and XCOPY command. 
  • What is a satellite assembly?
    When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  • What namespaces are necessary to create a localized application?
    System.Globalization and System.Resources.
  • What is the smallest unit of execution in .NET?
    an Assembly.
  • When should you call the garbage collector in .NET?
    As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. 
  • How do you convert a value-type to a reference-type?
    Use Boxing.
  • What happens in memory when you Box and Unbox a value-type?
    Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
  • What is CAS ?
    CAS(Code Access Secutiry)
    CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk. How does CAS work? The CAS security policy revolves around two key concepts – code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the ‘Zone – Internet’ code group, which adheres to the permissions defined by the ‘Internet’ named permission set. (Naturally the ‘Internet’ named permission set represents a very restrictive range of permissions.)
  • What is Satellite Assemblies ?
    Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.
  • Automatic Memory Management ?
    Automatic Memory Management: From a programmer’s perspective, this is probably the single biggest benefit of the .NET Framework. No, I’m not kidding. Every project I’ve worked on in my long career of DOS and Windows development has suffered at some point from memory management issues. Proper memory management is hard. Even very good programmers have difficulty with it. It’s entirely too easy for a small mistake to cause a program to chew up memory and crash, sometimes bringing the operating system to a screeching halt in the process.Programmers understand that they’re responsible for releasing any memory that they allocate, but they’re not very good at actually doing it. In addition, functions that allocate memory as a side effect abound in the Windows API and in the C runtime library. It’s nearly impossible for a programmer to know all of the rules. Even when the programmer follows the rules, a small memory leak in a support library can cause big problems if called enough.

    The .NET Framework solves the memory management problems by implementing a garbage collector that can keep track of allocated memory references and release the memory when it is no longer referenced. A large part of what makes this possible is the blazing speed of today’s processors. When you’re running a 2 GHz machine, it’s easy to spare a few cycles for memory management. Not that the garbage collector takes a huge number of cycles–it’s incredibly efficient.
    The garbage collector isn’t perfect and it doesn’t solve the problem of mis-managing other scarce resources (file handles, for example), but it relieves programmers from having to worry about a huge source of bugs that trips almost everybody up in other programming environments.
    On balance, automatic memory management is a huge win in almost every situation.

  • What Language familar to CLR?
    Any language that can be compiled into Microsoft Intermediate Language (MSIL) is considered a .NET-compliant language. Following are a few of the popular .NET-compliant languages supported by CLR:
    APL,COBOL,Component Pascal,Eiffel,Fortran,Haskell,JScript,Mercury,Oberon,Pascal,Perl,Python,Smalltalk,Visual Basic,Visual C#,Visual C++
  • Read Full Post »

    Encrypt – Decrypt with DES Algorithm
    ================================

    // Use this Namespace
    using System.Security.Cryptography;
    // Encrypt Function
    public static string Encryption(string value)
    {
    if (value != “”)
    {
    DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateEncryptor(Key_64, Iv_64), CryptoStreamMode.Write);
    StreamWriter sw = new StreamWriter(cs);
    sw.Write(value);
    sw.Flush();
    cs.FlushFinalBlock();
    ms.Flush();
    return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
    }
    return string.Empty;
    } 

    // Decrypt Function 

    public static string Descryption(string value)
    {
    if (value != “”)
    {
    DESCryptoServiceProvider CryptoProvidor = new DESCryptoServiceProvider();
    Byte[] buf = Convert.FromBase64String(value);
    MemoryStream ms = new MemoryStream(buf);
    CryptoStream cs = new CryptoStream(ms, CryptoProvidor.CreateDecryptor(Key_64, Iv_64), CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cs);
    return sr.ReadToEnd();
    }
    return string.Empty;
    }Encrypt with MD5 Algorithm
    ========================

     

    // Encrypt Function 

    public static string EncryptWithMD5(string ClearString)
    {
    System.Text.UnicodeEncoding objUE = new System.Text.UnicodeEncoding();byte[] bytClearString = objUE.GetBytes(ClearString);

    MD5CryptoServiceProvider objProv = new MD5CryptoServiceProvider();

    byte[] hash = objProv.ComputeHash(bytClearString);
    return Convert.ToBase64String(hash);

    }

    Read Full Post »

    The following code example demonstrates the standard formatting specifiers for numbers, dates, and enumerations.

    C#==

    // This code example demonstrates the String.Format() method.// Formatting for this example uses the “en-US” culture. using System;class Sample{enum Color {Yellow = 1, Blue, Green};static DateTime thisDate = DateTime.Now; public static void Main(){// Store the output of the String.Format method in a string.string s = “”; Console.Clear(); // Format a negative integer or floating-point number in various ways.Console.WriteLine(“Standard Numeric Format Specifiers”);s = String.Format( “(C) Currency: . . . . . . . . {0:C}\n” + “(D) Decimal:. . . . . . . . . {0:D}\n” + “(E) Scientific: . . . . . . . {1:E}\n” + “(F) Fixed point:. . . . . . . {1:F}\n” + “(G) General:. . . . . . . . . {0:G}\n” + ” (default):. . . . . . . . {0} (default = ‘G’)\n” + “(N) Number: . . . . . . . . . {0:N}\n” + “(P) Percent:. . . . . . . . . {1:P}\n” + “(R) Round-trip: . . . . . . . {1:R}\n” + “(X) Hexadecimal:. . . . . . . {0:X}\n”, -123, -123.45f);Console.WriteLine(s); // Format the current date in various ways.Console.WriteLine(“Standard DateTime Format Specifiers”);s = String.Format( “(d) Short date: . . . . . . . {0:d}\n” + “(D) Long date:. . . . . . . . {0:D}\n” + “(t) Short time: . . . . . . . {0:t}\n” + “(T) Long time:. . . . . . . . {0:T}\n” + “(f) Full date/short time: . . {0:f}\n” + “(F) Full date/long time:. . . {0:F}\n” + “(g) General date/short time:. {0:g}\n” + “(G) General date/long time: . {0:G}\n” + ” (default):. . . . . . . . {0} (default = ‘G’)\n” + “(M) Month:. . . . . . . . . . {0:M}\n” + “(R) RFC1123:. . . . . . . . . {0:R}\n” + “(s) Sortable: . . . . . . . . {0:s}\n” + “(u) Universal sortable: . . . {0:u} (invariant)\n” + “(U) Universal sortable: . . . {0:U}\n” + “(Y) Year: . . . . . . . . . . {0:Y}\n”, thisDate);Console.WriteLine(s); // Format a Color enumeration value in various ways.Console.WriteLine(“Standard Enumeration Format Specifiers”);s = String.Format( “(G) General:. . . . . . . . . {0:G}\n” + ” (default):. . . . . . . . {0} (default = ‘G’)\n” + “(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n” + “(D) Decimal number: . . . . . {0:D}\n” + “(X) Hexadecimal:. . . . . . . {0:X}\n”, Color.Green); Console.WriteLine(s);}} This code example produces the following results:=================================================Standard Numeric Format Specifiers(C) Currency: . . . . . . . . ($123.00)(D) Decimal:. . . . . . . . . -123(E) Scientific: . . . . . . . -1.234500E+002(F) Fixed point:. . . . . . . -123.45(G) General:. . . . . . . . . -123(default):. . . . . . . . -123 (default = ‘G’)(N) Number: . . . . . . . . . -123.00(P) Percent:. . . . . . . . . -12,345.00 %(R) Round-trip: . . . . . . . -123.45(X) Hexadecimal:. . . . . . . FFFFFF85 Standard DateTime Format Specifiers(d) Short date: . . . . . . . 6/26/2004(D) Long date:. . . . . . . . Saturday, June 26, 2004(t) Short time: . . . . . . . 8:11 PM(T) Long time:. . . . . . . . 8:11:04 PM(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM(g) General date/short time:. 6/26/2004 8:11 PM(G) General date/long time: . 6/26/2004 8:11:04 PM(default):. . . . . . . . 6/26/2004 8:11:04 PM (default = ‘G’)(M) Month:. . . . . . . . . . June 26(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT(s) Sortable: . . . . . . . . 2004-06-26T20:11:04(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)(U) Universal sortable: . . . Sunday, June 27, 2004 3:11:04 AM(Y) Year: . . . . . . . . . . June, 2004 Standard Enumeration Format Specifiers(G) General:. . . . . . . . . Green(default):. . . . . . . . Green (default = ‘G’)(F) Flags:. . . . . . . . . . Green (flags or integer)(D) Decimal number: . . . . . 3(X) Hexadecimal:. . . . . . . 00000003

    Read Full Post »

    Sample Example of Custom Validator to check Length of Textbox
    =======================================================

    1. Create Javascript function

    function CheckLength(events, args)
    {
    var x = (document.getElementById(txtSKU).value);
    if(x != ”)
    {
    if(x.length < 5) { args.IsValid = false; } else { args.IsValid = true;}

    2. Use one Custom Validator

    EnableClientScript=”true” Display=”None” ClientValidationFunction=”CheckLength”

    3. Declare Variable in CS file

    Page.ClientScript.RegisterStartupScript(this.GetType(), “CustomValidationTestForSKU”, “var txtSKU='” + this.txtSKU.ClientID + “‘;”, true);

    Read Full Post »

    .NET Framework Conceptual Overview
    =============================

     

    The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives:

    • To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.
    • To provide a code-execution environment that minimizes software deployment and versioning conflicts.
    • To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party.
    • To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.
    • To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications.
    • To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

    The .NET Framework has two main components: the common language runtime and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness. In fact, the concept of code management is a fundamental principle of the runtime. Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. The class library, the other main component of the .NET Framework, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.

    The .NET Framework can be hosted by unmanaged components that load the common language runtime into their processes and initiate the execution of managed code, thereby creating a software environment that can exploit both managed and unmanaged features. The .NET Framework not only provides several runtime hosts, but also supports the development of third-party runtime hosts.

    For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services, both of which are discussed later in this topic.

    Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed managed components or Windows Forms controls in HTML documents. Hosting the runtime in this way makes managed mobile code (similar to Microsoft® ActiveX® controls) possible, but with significant improvements that only managed code can offer, such as semi-trusted execution and isolated file storage.

    The following illustration shows the relationship of the common language runtime and the class library to your applications and to the overall system. The illustration also shows how managed code operates within a larger architecture.

    .NET Framework in context

    Managed code within a larger architecture

    The following sections describe the main components and features of the .NET Framework in greater detail.

    Features of the Common Language Runtime
    ==================================

    The common language runtime manages memory, thread execution, code execution, code safety verification, compilation, and other system services. These features are intrinsic to the managed code that runs on the common language runtime.

    With regards to security, managed components are awarded varying degrees of trust, depending on a number of factors that include their origin (such as the Internet, enterprise network, or local computer). This means that a managed component might or might not be able to perform file-access operations, registry-access operations, or other sensitive functions, even if it is being used in the same active application.

    The runtime enforces code access security. For example, users can trust that an executable embedded in a Web page can play an animation on screen or sing a song, but cannot access their personal data, file system, or network. The security features of the runtime thus enable legitimate Internet-deployed software to be exceptionally feature rich.

    The runtime also enforces code robustness by implementing a strict type-and-code-verification infrastructure called the common type system (CTS). The CTS ensures that all managed code is self-describing. The various Microsoft and third-party language compilers generate managed code that conforms to the CTS. This means that managed code can consume other managed types and instances, while strictly enforcing type fidelity and type safety.

    In addition, the managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors, memory leaks and invalid memory references.

    The runtime also accelerates developer productivity. For example, programmers can write applications in their development language of choice, yet take full advantage of the runtime, the class library, and components written in other languages by other developers. Any compiler vendor who chooses to target the runtime can do so. Language compilers that target the .NET Framework make the features of the .NET Framework available to existing code written in that language, greatly easing the migration process for existing applications.

    While the runtime is designed for the software of the future, it also supports software of today and yesterday. Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs.

    The runtime is designed to enhance performance. Although the common language runtime provides many standard runtime services, managed code is never interpreted. A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. Meanwhile, the memory manager removes the possibilities of fragmented memory and increases memory locality-of-reference to further increase performance.

    Finally, the runtime can be hosted by high-performance, server-side applications, such as Microsoft® SQL Server™ and Internet Information Services (IIS). This infrastructure enables you to use managed code to write your business logic, while still enjoying the superior performance of the industry’s best enterprise servers that support runtime hosting.

    .NET Framework Class Library
    =======================

    The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.

    For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET Framework.

    As you would expect from an object-oriented class library, the .NET Framework types enable you to accomplish a range of common programming tasks, including tasks such as string management, data collection, database connectivity, and file access. In addition to these common tasks, the class library includes types that support a variety of specialized development scenarios. For example, you can use the .NET Framework to develop the following types of applications and services:

    • Console applications.
    • Windows GUI applications (Windows Forms).
    • ASP.NET applications.
    • XML Web services.
    • Windows services.

    For example, the Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI development. If you write an ASP.NET Web Form application, you can use the Web Forms classes.

    Client Application Development
    ========================

    Client applications are the closest to a traditional style of application in Windows-based programming. These are the types of applications that display windows or forms on the desktop, enabling a user to perform a task. Client applications include applications such as word processors and spreadsheets, as well as custom business applications such as data-entry tools, reporting tools, and so on. Client applications usually employ windows, menus, buttons, and other GUI elements, and they likely access local resources such as the file system and peripherals such as printers.

    Another kind of client application is the traditional ActiveX control (now replaced by the managed Windows Forms control) deployed over the Internet as a Web page. This application is much like other client applications: it is executed natively, has access to local resources, and includes graphical elements.

    In the past, developers created such applications using C/C++ in conjunction with the Microsoft Foundation Classes (MFC) or with a rapid application development (RAD) environment such as Microsoft® Visual Basic®. The .NET Framework incorporates aspects of these existing products into a single, consistent development environment that drastically simplifies the development of client applications.

    The Windows Forms classes contained in the .NET Framework are designed to be used for GUI development. You can easily create command windows, buttons, menus, toolbars, and other screen elements with the flexibility necessary to accommodate shifting business needs.

    For example, the .NET Framework provides simple properties to adjust visual attributes associated with forms. In some cases the underlying operating system does not support changing these attributes directly, and in these cases the .NET Framework automatically recreates the forms. This is one of many ways in which the .NET Framework integrates the developer interface, making coding simpler and more consistent.

    Unlike ActiveX controls, Windows Forms controls have semi-trusted access to a user’s computer. This means that binary or natively executing code can access some of the resources on the user’s system (such as GUI elements and limited file access) without being able to access or compromise other resources. Because of code access security, many applications that once needed to be installed on a user’s system can now be deployed through the Web. Your applications can implement the features of a local application while being deployed like a Web page.

    Server Application Development
    ========================

    Server-side applications in the managed world are implemented through runtime hosts. Unmanaged applications host the common language runtime, which allows your custom managed code to control the behavior of the server. This model provides you with all the features of the common language runtime and class library while gaining the performance and scalability of the host server.

    The following illustration shows a basic network schema with managed code running in different server environments. Servers such as IIS and SQL Server can perform standard operations while your application logic executes through the managed code.

    Server-side managed code

    Managed server codeASP.NET is the hosting environment that enables developers to use the .NET Framework to target Web-based applications. However, ASP.NET is more than just a runtime host; it is a complete architecture for developing Web sites and Internet-distributed objects using managed code. Both Web Forms and XML Web services use IIS and ASP.NET as the publishing mechanism for applications, and both have a collection of supporting classes in the .NET Framework.

    XML Web services, an important evolution in Web-based technology, are distributed, server-side application components similar to common Web sites. However, unlike Web-based applications, XML Web services components have no UI and are not targeted for browsers such as Internet Explorer and Netscape Navigator. Instead, XML Web services consist of reusable software components designed to be consumed by other applications, such as traditional client applications, Web-based applications, or even other XML Web services. As a result, XML Web services technology is rapidly moving application development and deployment into the highly distributed environment of the Internet.

    If you have used earlier versions of ASP technology, you will immediately notice the improvements that ASP.NET and Web Forms offer. For example, you can develop Web Forms pages in any language that supports the .NET Framework. In addition, your code no longer needs to share the same file with your HTTP text (although it can continue to do so if you prefer). Web Forms pages execute in native machine language because, like any other managed application, they take full advantage of the runtime. In contrast, unmanaged ASP pages are always scripted and interpreted. ASP.NET pages are faster, more functional, and easier to develop than unmanaged ASP pages because they interact with the runtime like any managed application.

    The .NET Framework also provides a collection of classes and tools to aid in development and consumption of XML Web services applications. XML Web services are built on standards such as SOAP (a remote procedure-call protocol), XML (an extensible data format), and WSDL ( the Web Services Description Language). The .NET Framework is built on these standards to promote interoperability with non-Microsoft solutions.

    For example, the Web Services Description Language tool included with the .NET Framework SDK can query an XML Web service published on the Web, parse its WSDL description, and produce C# or Visual Basic source code that your application can use to become a client of the XML Web service. The source code can create classes derived from classes in the class library that handle all the underlying communication using SOAP and XML parsing. Although you can use the class library to consume XML Web services directly, the Web Services Description Language tool and the other tools contained in the SDK facilitate your development efforts with the .NET Framework.

    If you develop and publish your own XML Web service, the .NET Framework provides a set of classes that conform to all the underlying communication standards, such as SOAP, WSDL, and XML. Using those classes enables you to focus on the logic of your service, without concerning yourself with the communications infrastructure required by distributed software development.

    Finally, like Web Forms pages in the managed environment, your XML Web service will run with the speed of native machine language using the scalable communication of IIS.

    Read Full Post »