How to pass the Odesk ASP.Net 3.5 using C# Test 2012

Posted by imomins on September 8, 2012 at 6:30 AM Comments comments (1)

How to pass the Odesk ASP.Net 3.5 using C# Test 2012


Hello to every one. in this tutorial i will show you how to pass the odesk ASP.Net 3.5 using C# Test 2012.
 Question1:
The earliest event in which all viewstate information has been restored is:


    a.    Init
    b.    PreLoad
    c.    Load
    d.    Render

 the answer is:
    b.    PreLoad       

 Question2:
Which of the following differentiates a UserControl from a Custom Server control?


    a.    UserControl can directly express rendering information via markup; a Custom Server control can not.
    b.    UserControl does not require the use of the @Register directive; a Custom Server control does require it.
    c.    UserControl can make use of script based validation;  a Custom Server control can not.
    d.    UserControl can represent complete compositate hierarchy; a Custom Server control can not.

 the answer is:
    b.    UserControl does not require the use of the @Register directive; a Custom Server control does require it.       

 Question3:
What is the proper declaration of a method which will handle the following event?

Class MyClass
{
      public event EventHandler MyEvent;
}


    a.    public void A_MyEvent(object sender, MyArgs e)
{
}
    b.    public void A_MyEvent(object sender, EventArgs e)
{
}
    c.    public void A_MyEvent(MyArgs e)
{
}

 the answer is:
c.    public void A_MyEvent(MyArgs e)
{
}
       

 Question4:
Given the code below, which items will cause a compilation error?

static void F1(params int [] y)
{
}

static void Sample()
{
   int [] j = new Int32[3];
List k = new List();
// ANSWER GOES HERE
}


    a.    F1(j);
    b.    F1(k);
    c.    F1(1, 2, 3);
    d.    F1(new [] {1,2,3})
    e.    None of the above

 the answer is:
    e.    None of the above       

 Question5:
By which of the following can the .NET class methods be included in .aspx files?


    a.    Including .Net code within the script element with the runat attribute set to server
    b.    Including .Net code within the code element
    c.    Including .Net code using the @code directive on the page
    d.    Including .Net code within the execute attribute of the individual control

 the answer is:
    c.    Including .Net code using the @code directive on the page
       
 Question6:
Which of the following are true about System.Security.Cryptography under version 3.5 of the framework?


    a.    Support is provided for the "Suite B" set of cryptographic algorithms as specified by the National Security Agency (NSA).
    b.    Cryptography Next Generation (CNG) classes are supported on XP and Vista systems.
    c.    The System.Security.Cryptography.AesManaged class allows custom block size, iteration counts and feedback modes to support any Rijndael based encryption.

 the answer is:
    b.    Cryptography Next Generation (CNG) classes are supported on XP and Vista systems.       

 Question7:
Where should an instance of an object which provides services to all users be stored?


    a.    ApplicationState
    b.    SessionState
    c.    ViewState
    d.    None of the above

 the answer is:
    d.    None of the above       

 Question8:
Which of the following are the goals of the Windows Communciation Foundation?


    a.    Bringing various existing communication technologies into a unified environment.
    b.    Cross vendor/platform communication.
    c.    Support for asynchronous communications.
    d.    Support for distributed applications based on technologies such as MSMQ and/or COM+
    e.    All of the above

 the answer is:
    e.    All of the above       

 Question9:
When using a DataReader to access the results of a Database operation, which of the following is true?


    a.    The DataReader provides a cursor that can be used to move forward and backwards through the result.
    b.    The DataReader provides random access capabilities on the result.
    c.    The DataReader can provide the Schema information of the result to the application code.

 the answer is:
    b.    The DataReader provides random access capabilities on the result.       

 Question10:
Which of the following types guarantee atomic reads and writes?


    a.    int
    b.    double
    c.    long
    d.    float

 the answer is:
    d.    float       

 Question11:
Which of the following does Event Bubbling allow composite controls to perform?


    a.    Propagate container related events to the child controls.
    b.    Propagate child events up to control hierarchy
    c.    Distribute events between peer child controls.
    d.    Translate control unhandled control events into exceptions.

 the answer is:
    b.    Propagate child events up to control hierarchy       

 Question12:
Which of the following is/are true regarding the use of Authentication to control access to the HTML file (.htm or .html)?


    a.    ASP.NET authentication handles these by default in a manner equivalent to .aspx pages
    b.    ASP.NET authentication can be associated with these extensions using aspnet_isapi.dll in IIS 6.0, for the appropriate directory
    c.    ASP.NET authentication cannot be used for this purpose

 the answer is:
    c.    ASP.NET authentication cannot be used for this purpose       

 Question13:
Which of the following is false about declarative attributes?


    a.    They must be inherited from the System.Attribute.
    b.    Attribute classes may be restricted to be applied only to application element types.
    c.    By default, a given attribute may be applied multiple times to the same application element.

 the answer is:
    c.    By default, a given attribute may be applied multiple times to the same application element.       

 Question14:
Which of the following is false about System.GC under version 3.5 of the .NET Framework?


    a.    You can request that the garbage collector processes a generation if it determines that it is appropriate at specific points in your code
    b.    You can control the intrusiveness of the garbage collector (how often it performs collections) while your program is running
    c.    You can control the intrusiveness of the garbage collector (how often it performs collections) only during application initialization

 the answer is:
    b.    You can control the intrusiveness of the garbage collector (how often it performs collections) while your program is running       

 Question15:
With which of the following are Declarative Databinding expressions delimited?


    a.    <%#    %>
    b.    <%--   --%>
    c.  
    d.    <#  >

 the answer is:
<%--   --%>       

 Question16:
Which of the following statements are applicable in LINQ to SQL?


    a.    It is pure Object Relational (O/R) model.
    b.    It is a set of enhancements to the DataSet and DataTable classes.
    c.    It requires the use of SQLServer as the database.
    d.    Because LINQ is based on Queries, it can not be used to modify the data in the database.

 the answer is:
    b.    It is a set of enhancements to the DataSet and DataTable classes.       

 Question17:
Which of the following is used to remove a cookie from a client machine?


    a.    Remove the cookie from the System.Web.UI.Page.Request.Cookies collection.
    b.    Remove the cookie from the System.Web.UI.Page.Request.Browser.Cookies collection.
    c.    Set the Expires property to DataTime.Now for a cookie in the Web.UI.Page.Response.Cookies
    d.    Remove the cookie from the System.Web.UI.Page.Response.Cookies collection.

 the answer is:
    d.    Remove the cookie from the System.Web.UI.Page.Response.Cookies collection.       

 Question18:
Which of the following are true of using ADO.NET DataSets and DataTables?


    a.    The DataSets and DataTables objects requires continuous connection to the database
    b.    All tables in a dataset must come from the same database
    c.    A given instance of a DataTable can be in only one DataSet
    d.    Content from multiple DataSets can easily be combined into a single DataSet that contains the net result of all changes

 the answer is:
    b.    All tables in a dataset must come from the same database       

 Question19:
The following are two statements related to System.DateTimeOffset namespace.

Statement X: DateTimeOffset values can be converted to DateTime values and vice versa.
Statement Y: DateTimeOffset does not supports arithmetical operations


    a.    Statement X is incorrect and Statement Y is correct
    b.    Statement X is correct and Statement Y is incorrect
    c.    Both Statements X, Y are correct
    d.    Both Statements X, Y are incorrect

 the answer is:
    d.    Both Statements X, Y are incorrect       

 Question20:
Which of the following are true regarding System.Web.Mail and System.Net.Mail namespaces?


    a.    System.Web.Mail is not supported under version 3.5 of the Framework
    b.    System.Web.Mail is deprecated under version 3.5 of the Framework, and it is officially recommended that System.Net.Mail be used.
    c.    System.Web.Mail is the preferred solution when using IIS hosted applications
    d.    There are no functional differences; the items were moved to a new namespace to better reflect their applicability

 the answer is:
    b.    System.Web.Mail is deprecated under version 3.5 of the Framework, and it is officially recommended that System.Net.Mail be used.       

 Question21:
In which file are Predefined Client Side Validation Scripts defined?


    a.    WebUIValidation.js
    b.    ClientValidation.js
    c.    AspNetValidation.js
    d.    USerValidation.js

 the answer is:
    d.    USerValidation.js       

 Question22:
Which of the following are common methods of supplying "Help" information to an ASP.NET application?


    a.    Setting the ToolTip property of a control to a string containing the information.
    b.    using the open method of the browser window object to open a new browser window and display a help related ASP.NET page
    c.    Using the showHelp method of the browser window object to display a topic from a compiled help file (.chm).
    d.    All of the above

 the answer is:
    c.    Using the showHelp method of the browser window object to display a topic from a compiled help file (.chm).       

 Question23:
When using Cascading Style Sheets (CSS) to format output, which of the following is/are true?


    a.    Styles can be applied to all elements having the same CSS Class attribute
    b.    Styles can be applied to specific elements based on their ID attribute
    c.    Styles can be applied to elements based on their position in a hierarchy
    d.    Styles can be used to invoke script based code
    e.    All of the above

 the answer is:
    e.    All of the above       

 Question24:
Which of the following is false regarding System.Threading.ReaderWriterLockSlim?


    a.    It is optimized for single processor/core operations
    b.    A thread which has a read lock on a resource may not acquire a write lock on the same resource
    c.    By default, a thread which has a read lock on a resource and attempts to get another read lock on the same resource will throw an exception

 the answer is:
    b.    A thread which has a read lock on a resource may not acquire a write lock on the same resource       

 Question25:
Which of the following conditions can trigger the automatic recycling of an ASP.NET application hosted in IIS?


    a.    A specific number of requests to the application process.
    b.    A percentage of physical memory utilized by the process.
    c.    A specific time interval
    d.    All of the above

 the answer is:
    d.    All of the above       

 Question26:
Which of the following is not a characteristic, that a Query expression should have?


    a.    It must contain a from clause
    b.    It must begin with a select clause
    c.    It can end with a group clause

 the answer is:
    b.    It must begin with a select clause       

 Question27:
When using asynchronous partial updates with an UpdatePanel, which of the following are true?


    a.    Only the UpdatePanel and any child controls go through the server lifecycle.
    b.    The entire page always goes through the entire lifecycle.
    c.    Only the UpdatePanel which initiated the Postback and its child controls can provide updated information.
    d.    UpdatePanels can not be used with Master Pages.

 the answer is:
    d.    UpdatePanels can not be used with Master Pages.       

 Question28:
Which of the following statements is false about Passport Authentication?


    a.    The Passport SDK must be installed.
    b.    Passport authentication requires a network path between the Client and the Microsoft Passport Server
    c.    Passport Authentication provides persistent authentication across sessions

 the answer is:
    b.    Passport authentication requires a network path between the Client and the Microsoft Passport Server       

 Question29:
The default number of threads per processor in the System.Threading.ThreadPool class under version 3.5 of the Framwork is:


    a.    1
    b.    25
    c.    250
    d.    100
    e.    500

 the answer is:
    d.    100       

 Question30:
Which of the following statements do Expression Trees fit best?


    a.    Expression trees are a data structure which can be initially composed using language syntax.
    b.    Expression trees are a dynamically generated code which is executed to perform the desired function.
    c.    Expression trees can be modified once they are created

 the answer is:
    c.    Expression trees can be modified once they are created       

 Question31:
Which of the following are performed to fully debug an ASP.NET Application running on the same machine as the debugger?


    a.    Enabling debug information in the .NET Assembly
    b.    Setting the debug attribute of the compilation element to true in the web.config file.
    c.    Enabling ASP.NET debugging in the IIS metabase.

 the answer is:
    c.    Enabling ASP.NET debugging in the IIS metabase.       

 Question32:
Which of the following are included in the advantages of Lambda Expressions over Anonymous methods?


    a.    More concise syntax
    b.    The types for a Lambda Expression may be omitted
    c.    The body of an Anonymous method can not be an expression
    d.    Lambda Expressions permit deferred type inference, that anonymous methods do not
    e.    All of the above

 the answer is:
    b.    The types for a Lambda Expression may be omitted       

 Question33:
Which of the following controls allows the use of XSL to transform XML content into formatted content?


    a.    System.Web.UI.WebControls.Xml
    b.    System.Web.UI.WebControls.Xslt
    c.    System.Web.UI.WebControls.Substitution
    d.    System.Web.UI.WebControls.Transform

 the answer is:
    d.    System.Web.UI.WebControls.Transform       

 Question34:
Which of the following is not an unboxing conversion?


    a.    void Sample1(object o)
{
   int i = (int)o;
}
    b.    void Sample1(ValueType vt)
{
   int i = (int)vt;
}
    c.    enum E { Hello, World}

void Sample1(System.Enum et)
{
   E e = (E) et;
}
    d.    class C { public int Value { get; set; } }

void Sample1(C vt)
{
   int i = vt.Value;
}

 the answer is:
    d.    class C { public int Value { get; set; } }

void Sample1(C vt)
{
       

 Question35:
Which of the following are true about Nullable types?


    a.    A Nullable type is a reference type.
    b.    An implicit conversion exists from any non-nullable value type to a nullable form of that type.
    c.    A predefined conversion from the nullable type S? to the nullable type T? exists if there is a predefined conversion from the non-nullable type S to the non-nullable type T

 the answer is:
    c.    A predefined conversion from the nullable type S? to the nullable type T? exists if there is a predefined conversion from the non-nullable type S to the non-nullable type T       

 Question36:
Which of the following are required to be true by objects which are going to be used as keys in a System.Collections.HashTable?


    a.    They must handle case-sensitivity identically in both the GetHashCode() and Equals() methods.
    b.    Key objects must be immutable for the duration they are used within a HashTable.
    c.    Get HashCode() must be overridden to provide the same result, given the same parameters, regardless of reference equality unless the HashTable constructor is provided with an IEqualityComparer parameter.
    d.    Each Element in a HashTable is stored as a Key/Value pair of the type System.Collections.DictionaryElement
    e.    All of the above

 the answer is:
    d.    Each Element in a HashTable is stored as a Key/Value pair of the type System.Collections.DictionaryElement       

 Question37:
Where should information about a control created at design time be stored?


    a.    ApplicationState
    b.    SessionState
    c.    ViewState
    d.    None of the above

 the answer is:
    d.    None of the above       

 Question38:
Which directive allows the utilization of  a custom web control in an ASP.NET page?


    a.    @Register
    b.    @Include
    c.    @Control
    d.    @Import

 the answer is:
    d.    @Import       

 Question39:
The output generated by the following code will be:

string t = @"This\Is\a\Test";
Response.Write(t);


    a.    ThisIsaTest
    b.    This\Is\a\Test
    c.    It will give a compilation error: Unrecognized escape sequence

 the answer is:
    c.    It will give a compilation error: Unrecognized escape sequence       

 Question40:
Which of the following events should be used for assigning a Theme dynamically to a page?


    a.    PreInit
    b.    Init
    c.    PreLoad
    d.    PreRender
    e.    Render

 the answer is:
    c.    PreLoad

Source

Web.config File - ASP.NET

Posted by imomins on August 23, 2012 at 5:45 AM Comments comments (0)

Web.config files are stored in XML format which makes us easier to work with.

  • You can have any number of Web.config files for an application. Each Web.config applies settings to its own directory and all the child directories below it.
  • All the Web.config files inherit the root Web.config file available at the following location systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config location
  • IIS is configured in such a way that it prevents the Web.config file access from the browser.
  • The changes in Web.config don’t require the reboot of the web server.
  • Web.config Settings

    Before we start working with configuration settings of ASP.NET, we see the hierarchy of the Web.config file.

    <configuration>
    
            <configSections>
                <sectionGroup>
                </sectionGroup>
            </configSections>
    
            <system.web>
            </system.web>
    
            <connectionStrings>
            </connectionStrings>
    
            <appSettings>
            </appSettings>
            …………………………………………………………………………………………………………
            …………………………………………………………………………………………………………
            …………………………………………………………………………………………………………
            …………………………………………………………………………………………………………
            …………………………………………………………………………………………………………
    
    </configuration>

    So from the above tree structure, we can understand that the configuration tag is the root element of the Web.config file under which it has all the remaining sub elements. Each element can have any number of attributes and child elements which specify the values or settings for the given particular section. To start with, we’ll see the working of some of the most general configuration settings in the Web.config file.

    system.web

    In the configuration hierarchy, the most common thing we will work with is the system.web section. Now we look at some of the child sections of the system.web section of Web.config file.

    Compilation Settings

    If you are using Visual Studio 2010, probably the only available section of Web.config file by default is Compilation section. If you want to specify the target framework or if you need to add an assembly from the Global Assembly Cache (GAC) or if you want to enable the debugging mode of the application, you can take Compilation settings as granted for these tasks. The following code is used to achieve the discussed settings:

    <system.web
    	<compilation
                     debug="true" strict="true" explicit="true" batch="true"
                     optimizeCompilations="true" batchTimeout="900"
                     maxBatchSize="1000" maxBatchGeneratedFileSize="1000"
                     numRecompilesBeforeAppRestart="15" defaultLanguage="c#"
                     targetFramework="4.0" assemblyPostProcessorType="">
    	<assemblies>
    		<add assembly="System, Version=1.0.5000.0, Culture=neutral,
                      PublicKeyToken=b77a5c561934e089"/>
    	</assemblies>
    
    </compilation>
    </system.web>

    Under the assemblies element, you are supposed to mention the type, version, culture and public key token of the assembly. In order to get the public key token of an assembly, you need to follow the below mentioned steps:

    1. Go to Visual Studio tools in the start menu and open the Visual Studio command prompt.
    2. In the Visual Studio command prompt, change the directory to the location where the assembly or .dll file exists.
    3. Use the following command, sn –T itextsharp.dll.
    4. It generates the public key token of the assembly. You should keep one thing in mind that only public key token is generated only for the assemblies which are strongly signed.

    Example

    C:\WINNT\Microsoft.NET\Framework\v3.5> sn -T itextsharp.dll
    Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
    Copyright (c) Microsoft Corporation.  All rights reserved.
    
    Public key token is badfaf3274934e0

    Explicit and sample attributes are applicable only to VB.NET and C# compiler however ignores these settings.

    Page Settings

    Ok, by this time, we have got familiar with the Web.config file and we have seen the settings of Compilation Sections, now we will see the settings of a page. As an ASP.NET application consists of several number of pages, we can set the general settings of a page like sessionstate, viewstate, buffer, etc., as shown below:

    <pages buffer ="true" styleSheetTheme="" theme ="Acqua"
                  masterPageFile ="MasterPage.master"
                  enableEventValidation="true"> 

    By using the MasterPageFile and theme attributes, we can specify the master page and theme for the pages in web application.

    Custom Error Settings

    The next section of Web.config file, we are going to look around is Custom Error settings, by the name itself it is clear that we can configure the settings for the application level errors in these section. Now we will see the description of the customErrors section of the Web.config from the below mentioned code snippet.

    <customErrors defaultRedirect ="Error.aspx" mode ="Off">
       <error statusCode ="401" redirect ="Unauthorized.aspx"/>
    </customErrors>    

    The customErrors section consists of defaultRedirect and mode attributes which specify the default redirect page and the on/off mode respectively.
    The subsection of customErrors section allows redirecting to specified page depending on the error status code.

    • 400 Bad Request
    • 401 Unauthorized
    • 404 Not Found
    • 408 Request Timeout

    For a more detailed report of status code list, you can refer to this URL:

    Location Settings

    If you are working with a major project, probably you might have numerous numbers of folders and sub-folders, at this kind of particular situation, you can have two options to work with. First thing is to have a Web.config file for each and every folder(s) and Sub-folder(s) and the second one is to have a single Web.config for your entire application. If you use the first approach, then you might be in a smoother way, but what if you have a single Web.config and you need to configure the sub-folder or other folder of your application, the right solution is to use the "Location" tag of "system.web" section of Web.config file. However you can use this tag in either of the discussed methods.

    The following code shows you to work with Location settings:

    <location path="Login.aspx">
    	<system.web>
    		<authorization>
    	         <allow users="*"/>
    		</authorization>
    	</system.web>
    </location>
    <location path ="Uploads">
        <system.web>
    	<compilation debug = "false">
        </system.web>
    </location>

    In a similar way, you can configure any kind of available settings for any file/folder using the location tag.

    Session State and View State Settings

    As we all know, the ASP.NET is stateless and to maintain the state we need to use the available state management techniques of ASP.NET. View state and session state are among them. For complete information about view state and Session State and how to work with, there are some excellent articles in CodeProject, which you can refer here:

    Now we'll see the Web.config settings of View State and Session State:
    View State can be enabled or disabled by using the following page settings in the web.config file.

    <Pages EnableViewState="false" />

    Session state settings for different modes are as shown below:

    <sessionState mode="InProc" />
    <sessionState mode="StateServer"
    stateConnectionString= "tcpip=Yourservername:42424" />
    <sessionState mode="SQLServer" sqlConnectionString="cnn" />

    HttpHandler Settings

    HttpHandler is a code that executes when an http request for a specific resource is made to the server. For example, request an .aspx page the ASP.NET page handler is executed, similarly if an .asmx file is requested, the ASP.NET service handler is executed. An HTTP Handler is a component that handles the ASP.NET requests at a lower level than ASP.NET is capable of handling.

    You can create your own custom http handler, register it with IIS and receive notice whenever a request is made. For doing this, you just need to create a class which implements IHttpHanlder and then you need to add the following section of configuration settings in the web.config file. For this demonstration, I have created a sample imagehandler class which displays a JPG image to the browser.You can go through the imagehandler class code in the sample download code.

    <httpHandlers>
        <add verb="*" path="*.jpg" type="ImageHandler"/>
        <add verb="*" path="*.gif" type="ImageHandler"/>
    </httpHandlers/>

    HttpModule Settings

    HttpModule is a class or an assembly that implements the IHttpModule interface that handles the application events or user events. You can too create your own custom HttpModule by implementing the interface and configure it with ISS. The following settings show the HttpModules configuration in the web.config.

    <httpModules>
          <add type ="TwCustomHandler.ImageHandler"
               name ="TwCustomHandler"/>
          <remove name ="TwCustomHandler"/>
          <clear />
    </httpModules>

    Authentication, Authorization, Membership Provider, Role Provider and Profile Provider Settings

    These settings are directly available in the web.config file if you have created the ASP.NET application by using the Visual Studio 2010. I'm not going to elaborate them as there are lot of articles in CodeProject describing the functionality and use of these settings and for further information you can refer to them. Some of the links are here:

    Authentication Settings

    <authentication mode="Forms">
         <forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
                        loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
          </forms>
    </authentication>    

    Authorization Settings

    <authorization
            <allow roles ="Admin"/>
            <deny users ="*"/>
    </authorization>        

    Membership Provider Settings

    <membership defaultProvider="Demo_MemberShipProvider">
    	<providers>
    	   <add name="Demo_MemberShipProvider"
    	        type="System.Web.Security.SqlMembershipProvider"
    	        connectionStringName="cnn"
    	        enablePasswordRetrieval="false"
    	        enablePasswordReset="true"
    	        requiresQuestionAndAnswer="true"
    	        applicationName="/"
    	        requiresUniqueEmail="false"
    	        passwordFormat="Hashed"
    	        maxInvalidPasswordAttempts="5"
    	        minRequiredPasswordLength="5"
    	        minRequiredNonalphanumericCharacters="0"
    	       passwordAttemptWindow="10" passwordStrengthRegularExpression="">
    	</providers>
    </membership>

    Role Provider Settings

    <roleManager enabled="true" cacheRolesInCookie="true"
    cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">
                  <providers>
                      <add connectionStringName="dld_connectionstring"
                      applicationName="/" name="Demo_RoleProvider"
                      type="System.Web.Security.SqlRoleProvider, System.Web,
                      Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
                 </providers>
    </roleManager>

    Profile Provider Settings

    <profile defaultProvider="Demo_ProfileProvider">
        <providers>
    	<add name="Demo_ProfileProvider" connectionStringName="cnn"
    	applicationName="/" type="System.Web.Profile.SqlProfileProvider,
    	System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </providers>
        <properties>
    	<add name="Name" type="String"/>
    	<add name="DateofBirth" type="DateTime"/>
    	<add name="Place" type="string"/>
        </properties>
    </profile>

    AppSettings

    In the above section, we have seen the settings available in system.web tag, now we will see the available settings in appSettings section.
    appSettings element helps us to store the application settings information like connection strings, file paths, URLs, port numbers, custom key value pairs, etc.
    The following code snippet shows the example of appSettings Section:

    <appSettings>
    	<add key="AppKey" value="APLJI12345AFAFAF89999BDFG"/>
    </appSettings>

    connectionStrings

    The most common section of web.config file the connectionStrings sections allows you to store multiple connection strings that are used in the application. The connectionStrings tag consists of child element with attributes name and connectionstring which is used to identify the connectionstring and the other is used to connect to the database server respectively.

    The general connectionstring settings are shown below:

    <connectionStrings>
        <add name ="cnn" connectionString ="Initial Catalog = master; 
    		Data Source =localhost; Integrated Security = true"/>
    </connectionStrings>

    ConfigSections

    ConfigSections helps you to create your own custom configuration section that can be used with the web.config file. We look at this in the later section of the article, for the time being, we can have look at the configsection settings. ConfigSections should be declared just below the configuration (parent element) otherwise it is going through you an error.

    <configSections>
        <sectionGroup name="pageAppearanceGroup">
          <section
            name="pageAppearance"
            type="PageAppearanceSection"
            allowLocation="true"
            allowDefinition="Everywhere"
          />
     </sectionGroup>
     </configSections>

    Programmatically Accessing the Web.config File

    We can use the C# classes to read and write the values to the Web.config file.

    Reading appSettings values

    The following code is used to read the appSettings values from Web.config file. You can use either of the methods shown below:

    //Method 1:
            string key = ConfigurationManager.AppSettings["AppKey"];
            Response.Write(key);
    
    //Method 2:
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
            KeyValueConfigurationElement Appsetting = config.AppSettings.Settings["AppKey"];
            Response.Write(Appsetting.Key + " <br/>" + "Value:" + Appsetting.Value);

    Reading connectionstring values

    The following code is used to read the connectionstring values from Web.config file. You can use either of the methods shown below:

    //Method 1:
            string cnn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    
    //Methods 2:
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
            ConnectionStringSettings cnnstring;
    
            if (config.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                cnnstring = config.ConnectionStrings.ConnectionStrings["conn"];
                if (cnnstring != null)
                    Response.Write("ConnectionString:" + cnnstring.ConnectionString);
                else
                    Response.Write(" No connection string");
            }

    Reading configuration section values

    The following code is used to read the configuration section values from Web.config file. The comments in the code will help you to understand the code:

    // Intialize System.Configuration object.
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
    //Get the required section of the web.config file by using configuration object.
    CompilationSection compilation = 
    	(CompilationSection)config.GetSection("system.web/compilation");
    //Access the properties of the web.config
    Response.Write("Debug:"+compilation.Debug+"<br/>""+
    		"Language:"+compilation.DefaultLanguage);

    Update the configuration section values

    The following code is used to read the configuration section values from Web.config file:

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
    //Get the required section of the web.config file by using configuration object.
    CompilationSection compilation = 
    	(CompilationSection)config.GetSection("system.web/compilation");
    //Update the new values.
    compilation.Debug = true;
    //save the changes by using Save() method of configuration object.
    if (!compilation.SectionInformation.IsLocked)
    {
        config.Save();
        Response.Write("New Compilation Debug"+compilation.Debug);
    }
    else
    {
        Response.Write("Could not save configuration.");
    }

    Encrypt Configuration Sections of Web.config File

    As we have already discussed that IIS is configured in such a way that it does not serve the Web.Config to browser, but even in some such situation to provide more security, you can encrypt some of the sections of web.config file. The following code shows you the way to encrypt the sections of web.config file:

    Configuration config = WebConfigurationManager.OpenWebConfiguration
    			(Request.ApplicationPath);
    ConfigurationSection appSettings = config.GetSection("appSettings");
    if (appSettings.SectionInformation.IsProtected)
    {
        appSettings.SectionInformation.UnprotectSection();
    }
    else
    {
        appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
    }
    config.Save();    

    Custom Configuration Section in Web.config

    I have thought twice before I could put this section of content in this article, as there are a lot of wonderful articles explaining this topic, but just to make this article as complete, I have included this topic too.

    Create Custom Configuration Section

    The ConfigurationSection class helps us to extend the Web.config file in order to fulfill our requirements. In order to have a custom configuration section, we need to follow the below steps:

    Before we actually start working with it, we will have a look at the section settings. We need to have a ProductSection element with child elements girdSettings and color. For this purpose, we will create two classes with the child elements which inherits ConfigurationElement as shown below:

    public class GridElement : ConfigurationElement
    {
        [ConfigurationProperty("title", DefaultValue = "Arial", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~[email protected]#$%^&*()[]{}/;'\"|\\", 
    			MinLength = 1, MaxLength = 60)]
        public String Title
        {
            get
            {
                return (String)this["title"];
            }
            set
            {
                this["title"] = value;
            }
        }
    
        [ConfigurationProperty("count", DefaultValue = "10", IsRequired = false)]
        [IntegerValidator(ExcludeRange = false, MaxValue = 30, MinValue = 5)]
        public int Count
        {
            get
            { return (int)this["count"]; }
            set
            { this["size"] = value; }
        }
    }
    
    public class ColorElement : ConfigurationElement
    {
        [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~[email protected]#$%^&*()[]{}/;
    		'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]
        public String Background
        {
            get
            {
                return (String)this["background"];
            }
            set
            {
                this["background"] = value;
            }
        }
    
        [ConfigurationProperty("foreground", DefaultValue = "000000", IsRequired = true)]
        [StringValidator(InvalidCharacters = "~[email protected]#$%^&*()[]{}/;
    		'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)]
        public String Foreground
        {
            get
            {
                return (String)this["foreground"];
            }
            set
            {
                this["foreground"] = value;
            }
        }
    
    } 

    ... and then we will create a class called ProductSection, for the root element which includes the above child elements.

    public class ProductSection : ConfigurationSection
    {
        [ConfigurationProperty("gridSettings")]
        public GridElement gridSettings
        {
            get
            {
                return (GridElement)this["gridSettings"];
            }
            set
            { this["gridSettings"] = value; }
        }
    
        // Create a "color element."
        [ConfigurationProperty("color")]
        public ColorElement Color
        {
            get
            {
                return (ColorElement)this["color"];
            }
            set
            { this["color"] = value; }
        }
    }

    Then finally, we will configure these elements in Web.config file as shown below:

     <configSections>
          <section name ="ProductSection" type ="<ProductSection"/>
      </configSections>
    
      <ProductSection>
        <gridSettings title ="Latest Products" count ="20"></gridSettings>
        <color background="FFFFCC" foreground="FFFFFF"></color>
      </ProductSection>

    Access Custom Configuration Section

    The following code is used to access the custom configuration section:

    ProductSection config = (ProductSection)ConfigurationManager.GetSection("ProductSection");
    string color =config.Color.Background;
    string title =config.gridSettings.Title;
    int count = config.gridSettings.Count;

    Conclusion

    Image preview before uploading using AsynFileUpload

    Posted by imomins on August 11, 2012 at 10:50 AM Comments comments (0)

    It is always nice to show the preview of the image which has to be uploaded by the user.

    After lot of searching I found that the HTML upload i.e input type="file"... is not useful as it does not expose enough server side events. For this scenario the better control is Ajax control ToolKit's AjaxFileUpload, which has enough server side events and client side events.

    After the file is uploaded instead of saving it in the location in the server instead HttpHandler can be used which can write the uploaded image directly into the response. so no storage and less headaches.

    What have been done.

    1) Use AjaxFileUpload to upload the file.
    2) Store the file in the session object.
    3) Use the session object in the Handler. Set the Image control source to the Handler.


    In .aspx.cs

    public static readonly string STORED_IMAGE = "SessionImage";

    protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)
    {
    if (asyncFileUpload.PostedFile != null)
    {
    HttpPostedFile file = asyncFileUpload.PostedFile;

    byte[] data = ReadFile(file);
    //Store the image in the session.
    Session[STORED_IMAGE] = data;
    }
    }


    private byte[] ReadFile(HttpPostedFile file)
    {
    byte[] data = new Byte[file.ContentLength];
    file.InputStream.Read(data, 0, file.ContentLength);
    return data;
    }



    In .aspx

    Note: Use the randomnumber in the querystring of the handler otherwise, browser caches the first image and returns the same image again and again.


    <script language="javascript" type="text/javascript">
    function getRandomNumber() {
    var randomnumber = Math.random(10000);
    return randomnumber;
    }

    function OnClientAsyncFileUploadComplete(sender, args)
    {
    var handlerPage = '<%= Page.ResolveClientUrl("~/ImageHandler.ashx")%>';
    var queryString = '?randomno=' + getRandomNumber();
    var src = handlerPage + queryString;
    var clientId = '<%=previewImage.ClientID %>';
    document.getElementById(clientId).setAttribute("src", src);
    }
    </script>



    The Handler

    Note use the IRequiresSessionState to access the session variables in the Handler.



    public class ImageRequestHandler: IHttpHandler, IRequiresSessionState
    {
    public void ProcessRequest(HttpContext context)
    {
    context.Response.Clear();

    if(context.Request.QueryString.Count != 0)
    {
    //Get the stored image and write in the response.
    var storedImage = context.Session[_Default.STORED_IMAGE] as byte[];
    if (storedImage != null)
    {
    Image image = GetImage(storedImage);
    if (image != null)
    {
    context.Response.ContentType = "image/jpeg";
    image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
    }
    }
    }

    private Image GetImage(byte[] storedImage)
    {
    var stream = new MemoryStream(storedImage);
    return Image.FromStream(stream);
    }

    public bool IsReusable
    {
    get { return false; }
    }
    }



    In web.config


    <add validate="false" verb="*" path="ImageHandler.ashx"type="ImagePreviewDemo.ImageRequestHandler,ImagePreviewDemo"/>



    Please find the full source code attached.
    Attachments

  • ImagePreviewUploadDemo (40858-835-ImagePreviewDemo.rar)

    Did you like this resource? Share it with your friends and show your love!
    Share
  •  

    How to Integrate Asp.Net application in Facebook

    Posted by imomins on June 13, 2012 at 9:50 AM Comments comments (0)

    How to Integrate Asp.Net application in Facebook

    (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

     

    Hi,

    Someone asked me how to create facebook app day before yesterday and he wanted to integrate existing asp.net webpage in this facebook app. I was not much aware about facebook integration but got to know that facebook doesn’t have any api for asp.net to integrate webpage instead they have for php and python. So I googled and then find very good dotnet toolkit for facebook app which is from Microsoft (Facebook Developer Kit). We can integrate desktop or web app using this toolkit. So I thought I should make a sample app and share on this platform.

    Below are some steps":

    Before creating facebook app you need to have facebook account.

    Setting up Facebook App
    • To create facebook app click on Developer section 
    • Click on Set up New App button.
    • Agree Facebook terms and click on Create App

    Fb_CreateApp_thumb1

    • Put Security Check keywords.
    • Click on Submit.
    • Fill basic information about app.

    fb_BasicInfo_thumb1

    • Click on Facebook Integration tab.
    • Put Name of Canvas page.
    • Before putting URL of webpage of your website, I want to show how your page can get callback from facebook app. So first we create webpage in our website:
    • Create asp.net website in Visual studio.
    • Add reference of Facebook.dll from “C:\Program Files\Coding4Fun\Facebook\Binaries”. This dll will be placed after installing Facebook Developer kit on your machine.
    • Create instance of FacebookService object. you can copy facebook app api key and secret key from application page on facebook in source code.

     

    fb_appkey_thumb1

    put above values in FACEBOOK_API_KEY and FACEBOOK_SECRET constants respectively.

    you can get user_id of facebook who requested this application by calling

    1.string userId = Session["Facebook_userId"] as String;

    you can also get many information about user like name, sex, location,friends etc.

    1.User usr=_fbService.GetUserInfo();

    fb_userInfo_code_thumb2

    Source Code

    01.using System;
    02.using Facebook;
    03.public partial class Facebook_ConnectFacebook : System.Web.UI.Page
    04.{
    05.    Facebook.Components.FacebookService _fbService = new Facebook.Components.FacebookService();
    06.    private const string FACEBOOK_API_KEY = "191856207506775";
    07.    private const string FACEBOOK_SECRET = "820c0b05b14a09365e072c8d37a8c49f";
    08. 
    09.    protected void Page_Load(object sender, EventArgs e)
    10.    {
    11.        _fbService.ApplicationKey = FACEBOOK_API_KEY; _fbService.Secret = FACEBOOK_SECRET;
    12.        _fbService.IsDesktopApplication = false;
    13.        string sessionKey = Session["Facebook_session_key"] as String;
    14.        string userId = Session["Facebook_userId"] as String;
    15.         
    16.    // When the user uses the Facebook login page, the redirect back here
    17.    // will will have the auth_token in the query params
    18.         
    19.    string authToken = Request.QueryString["auth_token"];
    20.         
    21.    // We have already established a session on behalf of this user
    22.        if (!String.IsNullOrEmpty(sessionKey))
    23.        {
    24.            _fbService.SessionKey = sessionKey; _fbService.UserId = userId;
    25.        }
    26.        // This will be executed when Facebook login redirects to our page        
    27.        else if (!String.IsNullOrEmpty(authToken))
    28.        {
    29.            _fbService.CreateSession(authToken);
    30.            Session["Facebook_session_key"] = _fbService.SessionKey;
    31.            Session["Facebook_userId"] = _fbService.UserId;
    32.            Session["Facebook_session_expires"] = _fbService.SessionExpires;
    33.        }
    34.        // Need to login        
    35.        else
    36.        {
    37.            Response.Redirect(@"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0\");
    38.        }
    39. 
    40.        User usr = _fbService.GetUserInfo();
    41.        string t = string.Format("User Name:{0}, Sex:{1}, Location: {2}", usr.Name, usr.Sex, usr.CurrentLocation.City);
    42.        Response.Write(t);
    43.    }
    44.}
    Testing
    
        

    Now we are done with coding. Its time for testing.

    • Run your website.
    • Put webaddress of your webpage in facebook developer section as canvas URL.
    • Canvas type should be IFrame.

    fb_canvasUrl_thumb1

    • Click on Save changes.
    • now Facebook app has created.

    image_thumb2

    • Now open app url like http://apps.facebook.com/testneeraj/ on browser .
    • First time authToken will not authorize from facebook because you need to agree on “Allow Access” information.
    image_thumb4
    • Click on facebook banner.
    • It will ask Request for Permission. Click Allow.

    image_thumb10

    • It will show all basic information of user on webpage.

    image_thumb15

    • After that you can publish your app but having restriction from facebook that your application should 10 active member per month.

     

    I hope this article will give good knowledge about integration with facebook app. Please share your comments and feedback with me.

    How can a formcollection be enumerated in ASP.NET MVC?

    Posted by imomins on June 4, 2012 at 6:25 AM Comments comments (1)

     

    Here are 3 ways to do it specifically with a FormCollection object.

    public ActionResult SomeActionMethod(FormCollection formCollection)

    {

      foreach (var key in formCollection.AllKeys)

      {

        var value = formCollection[key];

      }

      foreach (var key in formCollection.Keys)

      {

        var value = formCollection[key.ToString()];

      }

      // Using the ValueProvider

      var valueProvider = formCollection.ToValueProvider();

      foreach (var key in valueProvider.Keys)

      {

        var value = valueProvider[key];

      }

    }


    ASP.Net Chart Control On Shared Hosting Environment

    Posted by imomins on May 22, 2012 at 5:45 AM Comments comments (0)

    Chart Control of ASP.Net 3.5 is very handy way to get statictical data as charts. There are variety of ways to display data with Chart Control. Also it is extramely simple to adapt it to your project. But as I hear from so many ASP.Net user nowadays, there might be some problems when it comes to publish it on your web server, especially on shared hosting servers !

    After you install the Chart Control, in order to run ASP.Net chart control on your project, you need to configure your web.config file on your root directory which you have already done (I guess !). If you do that properly, you are able to run it on your local server perfectly. But it is not enough for you to be good to go on your web server.

    You need to have Chart Control installed on your web server in order to run it on web !

    It is easy to do that if you have your own server but for those who have their website files on a shared hosting service, it is a bit hard. But you do not need to beg your hosting provider to make it be installed on server. Only you need to do is to make proper changes on your web.config file and believe me those changes are much more simple than you think ! Of Course, some references is needed to be added to the Bin Folder on your root directory !

    Solution :

    Follow this directory on windows explorer:

    C:\Program Files\Microsoft Chart Controls\Assemblies

    You will see 4 DLL files inside the folder. Two of those files are for Windows Applications and two of them for Web Applications. We need web application dll files so copy the dll files which are named 'System.Web.DataVisualization.Design' and 'System.Web.DataVisualization'

    Paste those dll files into the Bin folder on the root directory of your Web Application.

    Secondly, open the Web.Config file on the root directory of your web application.Find the <appSettings> node. You have a key add inside this just like below;

    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />

    Replace this tag with the new one as below;

    <add key="ChartImageHandler" value="storage=file;timeout=20;"/>

    Save the changes on your Web.Config file and close it. Now copy the two dll inside the bin folder and replace the Web.Config file on your server with your new Web.Config file.

    That's it !

    Now you should be able to run the Chart Control on your Web Server without begging your hosting provider :) If you have any problem with this, I recommend you to check the following codes if they exist on your Web.Config file or not;




     

     

    how to create and consume webservice using asp.net

    Posted by imomins on January 26, 2012 at 7:40 AM Comments comments (0)

    What is Web Service?

    Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as

    HTTP

    XML

    SOAP

    Advantages of Web Service

    Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.


    Examples for Web Service

    Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.

    Stock Quote: You can display latest update of Share market with Stock Quote on your web site.

    News Headline: You can display latest news update by using News Headline Web Service in your website.

    In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.


    Frequently used word with web services

    What is SOAP?

    SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

    What is WSDL? 

    WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

    What is UDDI?

    UDDI allows you to find web services by connecting to a directory.

    What is Discovery or .Disco Files?

    Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

    Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose

     

     

    Now we will see how to create new web service application in asp.net

    Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service



    Now our new web service ready our webservice website like this

    Now open your Service.cs file in web service website to write the code to get the user details from database

    Before writing the WebMethod in Service.cs first add following namespaces

     

    using System.Xml;

    using System.Configuration;

    using System.Data;

    using System.Data.SqlClient;

    After adding namespaces write the following method GetUserDetails in Service.cs page

     





    ASP.NEt Interview Question

    Posted by imomins on October 11, 2011 at 7:30 AM Comments comments (1)

    1. Explain the life cycle of an ASP .NET page.?

    Following are the events occur during ASP.NET Page Life Cycle:

     

    1)Page_PreInit

    2)Page_Init

    3)Page_InitComplete

    4)Page_PreLoad

    5)Page_Load

    6)Control Events

    7)Page_LoadComplete

    8)Page_PreRender

    9)SaveViewState

    10)Page_Render

    11)Page_Unload

     

    Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.

    2. how does the cookies work in asp.net?

    we know Http is an state-less protocol which is required for interaction between clinet and server .

     

    so there is an need to remeber state of request raised by an web browser so that 

    web server can recognize you have already previously visited or not.

     

    There are two types of state management techniques:

    a) Client side state management

    b) Server - side statemanagement

     

    Using cookies comes under clinet side statemanagement .In HttpResponse we write 

    Cookie containing sessionId and other information within it.

     

    when a browser made a request to the web server the same cookie is sent to the server where server recognize the session id and get other information stored to it previously.

    3. What is Ispostback method in ASP.Net? Why do we use that??

    Basically Post back is an action performed by a interactive Webpage. When it goes to the server side for a non-client Operation Server again posts it back to the client and hence the name.

    Ex:

     

    if(!IsPostBack)

     

    will not allow the page to post back again n again bcoz it reduces the performance.

    5. what is the difference between application state and caching?

    Application Object and Cached Object both falls under Server side State Management.

     

    Application object resides in InProc i.e. on the same server where we hosted our application.

    Cache Object resides on server side/ DownStream/Client Side.

     

    Application Object will be disposed once application will stop.

    Cache Object can be disposed using Time based cache dependency.

     

    Only one user can access Application Object at a time hence we have to lock it every time we modify it.

    6. what is boxing and unboxing?

    Boxing is what happens when a value-type object is assigned to a reference-type variable.

    Unboxing is what happens when a reference-type variable is assigned to a value-type variable.

    7. What are the uses of Reflection??

    Reflection is a concept using which we can 

    1) Load assemblies dynamically

    2) Invoke methods at runtime

    3) Retriving type information at runtime.

    8. What is the use of AutoWireup in asp.net?

    AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.

    In the case where AutoEventWireup attribute is set to false (by default) event handlers are automatically required for Page_Load or Page_Init. However when we set the value of the AutoEventWireup attribute to true the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.


    9. what events will occur when a page is loaded?

    Below are the events occures during page load.

     

    1) Page_PreInit

    2) Page_Init

    3) Page_InitComplete

    4) Page_PreLoad

    10. Where is the View state Data stored?

    ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed.

    12. Where do the Cookie State and Session State information be stored?

    Cookie Information will be stored in a txt file on client system under a 

    folder named Cookies. Search for it in your system you will find it. Coming to Session State

    As we know for every process some default space will be allocated by OS.

    In case of InProc Session Info will be stored inside the process where our 

    application is running.

    In case of StateServer Session Info will be stored using ASP.NET State Service.

    In case of SQLServer Session info will be stored inside Database. Default DB 

    which will be created after running InstallSQLState Script is ASPState.

    14. What are the different types of sessions in ASP.Net? Name them.?

    Session Management can be achieved in two ways

     

    1)InProc

    2)OutProc

     

    OutProc is again two types

    1)State Server

    2)SQL Server

     

    InProc

    Adv.:

    1) Faster as session resides in the same process as the application

    2) No need to serialize the data DisAdv.:

    1) Will degrade the performance of the application if large chunk of data is stored

    2) On restart of IIS all the Session info will be lost

    State Server

    Adv.:

    1) Faster then SQL Server session management 

    2) Safer then InProc. As IIS restart 

    won't effect the session data

    DisAdv.:

    1) Data need to be serialized

    2) On restart of ASP.NET State Service session info will be lost

    3)Slower as compared to InProc

    SQL Server

    Adv.:

    1) Reliable and Durable

    2) IIS and ASP.NET State Service 

    restart won't effect the session data

    3) Good place for storing large chunk of data

    DisAdv.:

    1) Data need to be serialized

    2) Slower as compare to InProc and State Server

    3)Need to purchase Licensed 

    version of SQL Serve

    16. What is caching? What are different ways of caching in ASP.NET?

    Caching is a technique of persisting the data in memory for immediate access to requesting program calls. This is considered as the best way to enhance the performance of the application.

     

    Caching is of 3 types:

    Output Caching - Caches the whole page.

    Fragment Caching - Caches a part of the page

    Data Caching - Caches the data

    17. What is meant by 3-tier architecture.

    We generally split our application into 3-Layers

    1)Presentation Layer ( Where we keep all web forms Master Pages and User Controls).

    2)Business Layer (Where we keep business logic). e.g Code related to manipulating data Custom Exception classes Custom Control classes Login related code if any etc. etc.

    3)Data Access Layer (Where we keep code used to interact with DB). e.g. We can have the methods which are using SQL Helper (Application Block).


    19. What is the difference between mechine.config and web.config?

    machine.config is a system level configuration i.e it is applied on all application in o/s that the configuration is set where as in web.config it is applicable to only one application i.e each asp.net webapplication will contain atleast on web.config file.


    21. What is the difference between Response.Redirect and Server.Transfer.

    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 toredirect the user's browser to another page or site. This performs 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.

    25. What is the exact purpose of http handlers?

    ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as ISAPI extensions with a much simpler programming model

    Ex

    1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)

    2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)

    An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a process that can be lengthy and returns before that process finishes

    After writing and compiling the code to implement an HttpHandler you must register the handler using your application's Web.config file.

     


     

     




    Interview Question of .NET

    Posted by imomins on October 11, 2011 at 7:20 AM Comments comments (0)

    Cookies

    Definition: – A cookie is information that a Website puts on your hard disk so that it can remember something about you at a later time. (More technically, it is information for future use that is stored by the server on the client side of a client/server communication.)

    In short, Cookie is client’s information for particular site stored on client’s PC.

    Typically, a cookie records your preferences when using a particular site. Using the Web’s Hypertext Transfer Protocol (HTTP), each request for a Web page is independent of all other requests. For this reason, the Web page server has no memory of what pages it has sent to a user previously or anything about your previous visits. A cookie is a mechanism that allows the server to store its own information about a user on the user’s own computer.

     


    Procedure:-  following are steps show how cookies works

    When you visit some site, server for that site stores information (user name or simply physical address of user’s pc) in 1 text file. For that, that site may ask you to fill details about yourself  or  it can simple fetch physical address of your computer.Server sends this file to client with web page and that file is saved in client’s pc.Now when user visits that website again, that cookie file is also sent to server with the web page request. From that file, website’s sever can identify that particular user and do further procedures (Ex.  Prepare customized webpage for that user) using that information.


    Session

    Definition: – A session is information of user that a Website puts on its temporary memory so that it can remember something about you when you are visiting that site. (More technically, it is information for future use that is stored by the server on the server side of a client/server communication.)

     In short, Session is client’s information for particular site stored on Server’s temporary memory. The period of time a user interfaces with an application. The user session begins when the user accesses the application and ends when the user quits the application The number of user sessions on a site is used in measuring the amount of traffic a website gets. The site administrator determines what the time frame of a user session will be (e.g., 30 minutes). If the visitor comes back to the site within that time period, it is still considered one user session because any number of visits within those 30 minutes will only count as one session. If the visitor returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is counted as a separate user session. Contrast with unique visitor, hit, click-through and page view, which are all other ways that site administrators measure the amount of traffic a Web site gets. Example:- When you visit www.gmail.com , you have to enter your account ID and password first. That information is verified on server and stored on server in session until that user is logged on.


    What is the difference between session and cookie?


    If you set the variable to “cookies”, then your users will not have to log in each time they enter your community. The cookie will stay in place within the user’s browser until the user deletes it.

    But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.

    If you set the variable to “sessions”, then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. Additionally, if you are using the “sessions” variable, you need to secure the “sessions” directory, either by placing it above the web root or by requesting that your web host make it a non-browsable directory.

    The Key difference would be cookies are stored in your hard disk whereas a session aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.

      1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.

    2) session and cookies differ in type and amount of information they are capable of storing.

    Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects

    Explain the access specifiers Public, Private, Protected, Friend, Internal, Default?


    The main purpose of using access specifiers is to provide security to the applications. The availability (scope)of the member objects of a class may be controlled using access specifiers.

     

    1. PUBLIC

    As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.

     

    2. PRIVATE

    As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.

     

    3. FRIEND/INTERNAL

    Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#.Friends can be accessed by all classes within an assembly but not from outside the assembly.

     

    4. PROTECTED

    Protected variables can be used within the class as well as the classes that inherites this class.

     

    5. PROTECTED FRIEND/PROTECTED INTERNAL

    The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.

     

    6. DEFAULT

    A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

    Whats the difference between Classic ASP and ASP.NET?

    Major difference: Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles, otherwise does'nt.

    Other differences: ASP works with VB as the language. ASP.NET works with VB.NET & C# as the languages (Also supported by other languages that run on the .NET Framework).

    ASP.NET is the web technology that comes with the Microsoft .NET Framework. Themain process in ASP.NET is called aspnet_wp.exe that accesses system resources. ASP.NET was launchedin 2002 with version 1.0. Subsequent versions are 1.1 and version 2.0. ASP.NET is built upusing thousands of objects, ordered in the System namespace. When an ASP.NET class is compiled, itscalled an assembly.

    In Classic ASP, complex functionalities are achieved using COM components, that are nothingbut component objects created using VB 6, C++ etc, and are usually in a DLL format. Thesecomponents provide an exposed interface to methods in them, to the objects that reference thesecomponents. Last version of classic ASP is version 3.0. ASP has 7 main objects - Application, ASPError, ObjectContext, Request, Response, Server, Session.



     


     

     


     

     

    Introduction to JSON

    Posted by imomins on July 11, 2011 at 6:22 AM Comments comments (0)

    Introduction

    As we know Ajax is a web development technology that makes the server responses faster by enabling the client-side scripts to retrieve only the required data from the server without retrieving a complete web page on each request, which will minimize the data transferred from the server.

    These requests usually retrieve xml formatted response, the xml responses are then parsed in the JavaScript code to render the results. Which complicate the JavaScript code

    The idea of JSON (JavaScript Object Notation) is to make the response a specific data structure that can be easily parsed by the JavaScript code.

     

    Advantages

    1- lightweight data-interchange format

    2- Easy for humans to read and write

    3- Easy for machines to parse and generate

    4- JSON can be parsed trivially using the eval() procedure in JavaScript

    5- JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.

    .

    Syntax

    The JSON Syntax is the convention which you will use it to generate data, it’s near to the C family language, so it can be parsed easily in the C family languages.

    For objects start the object with “{“ and end it with “}”

    object

    {}

    { members }

    ·         For members (properties), use pairs of string : value and separate them by commas

    members

    string : value

    members , string : value

    ·         For arrays put the arrays between []

    array

    []

    [ elements ]

    ·         For elements put the values directly separated by commas

    elements

    value

    elements , value

    ·         Values can be  string, number, object, array, true, false, null

    EXAMPLESJSON 

    {"menu": {  

      "id": "file",

      "value": "File:",  

      "popup": {  

        "menuitem": [ 

          {"value": "New", "onclick": "CreateNewDoc()"},

          {"value": "Open", "onclick": "OpenDoc()"},  

          {"value": "Close", "onclick": "CloseDoc()"}  ]

      }

    }}

    XML<menu id="file" value="File" >  <popup>     <menuitem value="New" onclick="CreateNewDoc()" />     <menuitem value="Open" onclick="OpenDoc()" />     <menuitem value="Close" onclick="CloseDoc()" />  </popup></menu>

     

     

     

     

     

    Server side codeThe following code will be generated in the server side to retrieve the server time, and in one step in the client side it will be rendered to JavaScript

    Java <%@ page language="java" import="java.util.*" %>

    <%Date date = new Date(); %>alert("The server time is: <%Úte%>");

    <SPAN style="mso-tab-count: 1">          ASP.NET<%@ page language="C#" %>   alert("The server time is: <%=System.Date.Now.ToString()%>"); 

    PHPalert("The server time is: <?=time()?>"); 

    Client Side JavaScript//XMLHttpRequest completion function

    var myOnComplete = function(responseText, responseXML){eval(responseText);}

     

    http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=11