1. --"TOOL_TYP_CODE" = COLUMN NAME
    --"DMS_DCT_TOOL_TYPE" = TABLE
    --"WBD0" = CODE LAST
    SELECT
    MAX(CONVERT(INTEGER,SUBSTRING(TOOL_TYP_CODE,5,4)))
    FROM DMS_DCT_TOOL_TYPE
    WHERE TOOL_TYP_CODE LIKE 'WBD0%'
    0

    Add a comment

  2. To disable autorecovery in .net :

    Go to Registry and change to 0 (zero) value of the following key:

    HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\90\Tools\Shell\General\AutoRecover\AutoRecover Enabled
    0

    Add a comment

  3. Row_Number() over (Order by Emp_ID) as Serial
    0

    Add a comment

  4. Que:- What’s the implicit name of the parameter that gets passed into the class’ set method?
    Ans:- Value, and its datatype depends on whatever variable we’re changing.

    Que:- How do you inherit from a class in C#?
    Ans:- Place a colon and then the name of the base class. Notice that it’s double
    colon in C++.

    Que:- Does C# support multiple inheritance?
    Ans:- No, use interfaces instead.

    Que:- When you inherit a protected class-level variable, who is it available to?
    Ans:- Classes in the same namespace.

    Que:- Are private class-level variables inherited?
    Ans:- Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

    Que:- Describe the accessibility modifier protected internal.
    Ans:- It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

    Que:- C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
    Ans:- Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

    Que:- What’s the top .NET class that everything is derived from?
    Ans:- System.Object.

    Que:- How’s method overriding different from overloading?
    Ans:- When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

    Que:- What does the keyword virtual mean in the method definition?
    Ans:- The method can be over-ridden.

    Que:- Can you declare the override method static while the original method is non-static?
    Ans:- No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

    Que:- Can you override private virtual methods?
    Ans:- No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

    Que:- Can you prevent your class from being inherited and becoming a base class for some other classes?
    Ans:- Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

    Que:- Can you allow class to be inherited, but prevent the method from being over-ridden?
    Ans:- Yes, just leave the class public and make the method sealed.

    Que:- What’s an abstract class?
    Ans:- A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

    Que:- When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
    Ans:- When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

    Que:- What’s an interface class?
    Ans:- It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

    Que:- Why can’t you specify the accessibility modifier for methods inside the interface?
    Ans:- They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

    Que:- Can you inherit multiple interfaces?
    Ans:- Yes, why not.

    Que:- And if they have conflicting method names?
    Ans:- 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.

    Que:- What’s the difference between an interface and abstract class?
    Ans:- In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

    Que:- How can you overload a method?
    Ans:- Different parameter data types, different number of parameters, different order of parameters.

    Que:- If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
    Ans:- 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.

    Que:- What’s the difference between System.String and System.StringBuilder classes?
    Ans:- System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

    Que:- What’s the advantage of using System.Text.StringBuilder over System.String?
    Ans:- StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

    Que:- Can you store multiple data types in System.Array?
    Ans:- No.

    Que:- What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    Ans:- The first one performs a deep copy of the array, the second one is shallow.

    Que:- How can you sort the elements of the array in descending order?
    Ans:- By calling Sort() and then Reverse() methods.

    Que:- What’s the .NET datatype that allows the retrieval of data by a unique key?
    Ans:- HashTable.

    Que:- What’s class SortedList underneath?
    Ans:- A sorted HashTable.

    Que:- Will finally block get executed if the exception had not occurred?
    Ans:- Yes.

    Que:- What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
    Ans:- 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 {}.

    Que:- Can multiple catch blocks be executed?
    Ans:- No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

    Que:- Why is it a bad idea to throw your own exceptions?
    Ans:- Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

    Que:- What’s a delegate?
    Ans:- A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

    Que:- What’s a multicast delegate?
    Ans:- It’s a delegate that points to and eventually fires off several methods.

    Que:- How’s the DLL Hell problem solved in .NET?
    Ans:- 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.

    Que:- What are the ways to deploy an assembly?
    Ans:- An MSI installer, a CAB archive, and XCOPY command.

    Que:- What’s a satellite assembly?
    Ans:- 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.

    Que:- What namespaces are necessary to create a localized application?
    Ans:- System.Globalization, System.Resources.

    Que:- What’s the difference between // comments, /* */ comments and /// comments?
    Ans:- Single-line, multi-line and XML documentation comments.

    Que:- How do you generate documentation from the C# file commented properly with a command-line compiler?
    Ans:- Compile it with a /doc switch.

    Que:- What’s the difference between and XML documentation tag?
    Ans:- Single line code example and multiple-line code example.

    Que:- Is XML case-sensitive?
    Ans:- Yes, so and are different elements.

    Que:- What debugging tools come with the .NET SDK?
    Ans:- CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

    Que:- What does the This window show in the debugger?
    Ans:- It points to the object that’s pointed to by this reference. Object’s instance data is shown.

    Que:- What does assert() do?
    Ans:- 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.

    Que:- What’s the difference between the Debug class and Trace class?
    Ans:- Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

    Que:- Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    Ans:- The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

    Que:- Where is the output of TextWriterTraceListener redirected?
    Ans:- To the Console or a text file depending on the parameter passed to the constructor.

    Que:- How do you debug an ASP.NET Web application?
    Ans:- Attach the aspnet_wp.exe process to the DbgClr debugger.

    Que:- What are three test cases you should go through in unit testing?
    Ans:- Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

    Que:- Can you change the value of a variable while debugging a C# application?
    Ans:- Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

    Que:- Explain the three services model (three-tier application).
    Ans:- Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

    Que:- What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    Ans:- 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, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

    Que:-. What’s the role of the DataReader class in ADO.NET connections?
    Ans:- It returns a read-only dataset from the data source when the command is executed.

    Que:- 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.
    Ans:- The wildcard character is %, the proper query with LIKE would involve ‘La%’.

    Que:- Explain ACID rule of thumb for transactions.
    Ans:- Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

    Que:- What connections does Microsoft SQL Server support?
    Ans:- Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

    Que:- Which one is trusted and which one is untrusted?
    Ans:- 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.

    Que:- Why would you use untrusted verificaion?
    Ans:- Web Services might use it, as well as non-Windows applications.

    Que:- What does the parameter Initial Catalog define inside Connection String?
    Ans:- The database name to connect to.

    Que:- What’s the data provider name to connect to Access database?
    Ans:- Microsoft.Access.

    Que:- What does Dispose method do with the connection object?
    Ans:- Deletes it from the memory.

    Que:- What is a pre-requisite for connection pooling?
    Ans:- Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
    0

    Add a comment

  5. Que:- What is the sequence in which ASP.NET events are processed ?
    Ans:- Following is the sequence in which the events occur :-
    * Page_Init.
    * Page_Load.
    * Control events.
    * Page_Unload event.
    Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.

    Que:- In which event are the controls fully loaded ?
    Ans:- Page_load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event.

    Que:- How can we identify that the Page is PostBack ?
    Ans:- Page object has a “IsPostBack” property which can be checked to know that is the page posted back.

    Que:-What is event bubbling ?
    Ans:- Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event. As the child control send there events to parent this is termed as event bubbling.

    Que:- If we want to make sure that no one has tampered with ViewState, how do we ensure it?
    Ans:- Using the @Page directive EnableViewStateMac to True.

    Que:- What is AppSetting Section in “Web.Config” file?
    Ans:- Web.config file defines configuration for a webproject. Using “AppSetting” section we can define user defined values. Example below defined is ConnectionString” section which will be used through out the project for database connection.

    Que:- Where is ViewState information stored ?
    Ans:- In HTML Hidden Fields.

    Que:- How can we create custom controls in ASP.NET ?
    Ans:- User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:

    * Register the ASCX control in page using the
    * Now to use the above accounting footer in page you can use the below directive.

    Que:- How many types of validation controls are provided by ASP.NET ?
    Ans:- There are six main types of validation controls :-
    1). RequiredFieldValidator :-

    It checks whether the control have any value. It's used when you want the control should not be empty.

    2). RangeValidator :-

    It checks if the value in validated control is in that specific range. Example
    TxtCustomerCode should not be more than eight length.

    3). CompareValidator:-

    It checks that the value in controls should match the value in other control. Example
    Textbox TxtPie should be equal to 3.14.

    4). RegularExpressionValidator:-

    When we want the control value should match with a specific regular expression.

    5). CustomValidator:-

    It is used to define UserDefined validation.

    6). ValidationSummary:-

    It displays summary of all current validation errors.

    Que:- Can you explain what is “AutoPostBack” feature in ASP.NET ?
    Ans:- If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.

    Que:- How can you enable automatic paging in DataGrid ?
    Ans:- Following are the points to be done in order to enable paging in Datagrid :-
    * Set the “AllowPaging” to true.
    * In PageIndexChanged event set the current pageindex clicked.

    Que:-What is the difference between “Web.config” and “Machine.Config” ?
    Ans:- “Web.config” files apply settings to each web application, while Machine.config” file apply settings to all ASP.NET applications.

    Que:- What is the difference between Server.Transfer and response.Redirect ?
    Ans:- Following are the major differences between them:-
    * Response.Redirect sends message to the browser saying it to move to some
    different page, while server.transfer does not send any message to the browser
    but rather redirects the user directly from the server itself. So in server.transfer
    there is no round trip while response.redirect has a round trip and hence puts
    a load on server.

    * Using Server.Transfer you can not redirect to a different from the server itself.
    Example if your server is www.yahoo.com you can use server.transfer to move
    to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e.
    within websites. This cross server redirect is possible only using
    Response.redirect.

    * With server.transfer you can preserve your information. It has a parameter
    called as “preserveForm”. So the existing query string etc. will be able in the
    calling page. In response.redirect you can maintain the state, but has
    lot of drawbacks.

    Que:- What is the difference between Authentication and authorization?
    Ans:- This can be a tricky question. These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceed to Authorization; even if your application lets anonymous users connect and use
    the application, it still authenticates them as being anonymous.

    Que:- What are the various ways of authentication techniques in ASP.NET?
    Ans:- Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:

    * authentication mode=”windows”
    * authentication mode=”passport”
    * authentication mode=”forms”
    * Custom authentication where you might install an ISAPI filter in IIS that
    compares incoming requests to list of source IP addresses, and considers
    requests to be authenticated if they come from an acceptable address. In that
    case, you would set the authentication mode to none to prevent any of the
    .net authentication providers from being triggered.

    Que:- How does authorization work in ASP.NET?
    Ans:- ASP.NET impersonation is controlled by entries in the applications web.config file. The default setting is “no impersonation”. You can explicitly specify that ASP.NET shouldn’t use impersonation by including the following code in the file

    It means that ASP.NET will not perform any authentication and runs with its own
    privileges. By default ASP.NET runs as an unprivileged account named ASPNET. You
    can change this by making a setting in the processModel section of the machine.config
    file. When you make this setting, it automatically applies to every site on the server. To user a high-privileged system account instead of a low-privileged set the userNameattribute of the processModel element to SYSTEM. Using this setting is a definite security risk, as it elevates the privileges of the ASP.NET process to a point where it can do bad things to the operating system.

    Que:- What’s difference between Datagrid, Datalist and repeater ?
    Ans:- A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.
    They have many things in common like DataSource Property, DataBind Method
    ItemDataBound and ItemCreated.
    When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow
    present in the DataRow Collection of DataTable is assigned to a corresponding
    DataGridItem and this is same for the rest of the two controls also. But The HTML code generated for a Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows.
    For a Datalist its an Array of Rows and based on the Template Selected and the
    RepeatColumn Property value We can specify how many DataSource records should
    appear per HTML table row. In short in datagrid we have one record per row, but in
    datalist we can have five or six rows per row.
    For a Repeater Control, the Datarecords to be displayed depends upon the Templates
    specified and the only HTML generated is the due to the Templates.
    In addition to these, Datagrid has a in-built support for Sort, Filter and paging the Data,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.

    Que:- From performance point of view how do they rate ?
    Ans:- Repeater is fastest followed by Datalist and finally datagrid.

    Que:- What is the method to customize columns in DataGrid?
    Ans:- Use the template column.

    Que:- How can we format data inside DataGrid?
    Ans:- Use the DataFormatString property.

    Que:- How to decide on the design consideration to take a Datagrid, datalist or repeater ?
    Ans:- Many make a blind choice of choosing datagrid directly, but that's not the right way.
    Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed. Second the display format is simple that is in row and columns.
    Real life scenarios can be more demanding that With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. It offers better performance than datagrid Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. But repeater does not provide editing features like datagrid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls.
    Repeater is fastest followed by Datalist and finally datagrid.

    Que:- Difference between ASP and ASP.NET?
    Ans:- ASP.NET new feature supports are as follows :-

    Better Language Support

    * New ADO.NET Concepts have been implemented.
    ASP.NET supports full language (C#, VB.NET, C++) and not simple scripting
    like VBSCRIPT..

    Better controls than ASP

    * ASP.NET covers large set’s of HTML controls..
    * Better Display grid like Datagrid, Repeater and datalist.Many of the display
    grids have paging support.

    Controls have events support

    * All ASP.NET controls support events.
    * Load, Click and Change events handled by code makes coding much simpler and much better organized.

    Compiled Code

    The first request for an ASP.NET page on the server will compile the ASP.NET code and
    keep a cached copy in memory. The result of this is greatly increased performance.
    Better Authentication Support
    ASP.NET supports forms-based user authentication, including cookie management and
    automatic redirecting of unauthorized logins. (You can still do your custom login page and custom user checking).

    User Accounts and Roles

    ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

    High Scalability

    * Much has been done with ASP.NET to provide greater scalability.
    * Server to server communication has been greatly enhanced, making it possible
    to scale an application over several servers. One example of this is the ability
    to run XML parsers, XSL transformations and even resource hungry session objects on other servers.

    Easy Configuration

    Configuration of ASP.NET is done with plain text files.
    * Configuration files can be uploaded or changed while the application is running.
    No need to restart the server. No more metabase or registry puzzle.

    Easy Deployment

    No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.


    Que:- What are major events in GLOBAL.ASAX file ?
    Ans:- The Global.asax file, which is derived from the HttpApplication class, maintains a pool
    of HttpApplication objects, and assigns them to applications as needed. The Global.asax
    file contains the following events:

    Application_Init: Fired when an application initializes or is first called. It is invoked for
    all HttpApplication object instances.

    Application_Disposed: Fired just before an application is destroyed. This is the ideal
    location for cleaning up previously used resources.

    Application_Error: Fired when an unhandled exception is encountered within the
    application.

    Application_Start: Fired when the first instance of the HttpApplication class is created.
    It allows you to create objects that are accessible by all HttpApplication instances.
    Application_End: Fired when the last instance of an HttpApplication class is destroyed.
    It is fired only once during an application's lifetime.

    Application_BeginRequest: Fired when an application request is received. It is the first
    event fired for a request, which is often a page request (URL) that a user enters.

    Application_EndRequest: The last event fired for an application request.

    Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework
    begins executing an event handler like a page or Web service.

    Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has finished executing an event handler

    Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends
    HTTP headers to a requesting client (browser).

    Application_UpdateRequestCache: Fired when the ASP.NET page framework completes
    handler execution to allow caching modules to store responses to be used to handle
    subsequent requests.

    Application_AuthenticateRequest: Fired when the security module has established the
    current user's identity as valid. At this point, the user's credentials have been validated.
    Application_AuthorizeRequest: Fired when the security module has verified that a user
    can access resources.

    Session_Start: Fired when a new user visits the application Web site.

    Session_End: Fired when a user's session times out, ends, or they leave the application
    Web site.

    Que:- What order they are triggered ?
    Ans:- They're triggered in the following order:

    * Application_BeginRequest
    * Application_AuthenticateRequest
    * Application_AuthorizeRequest
    * Application_ResolveRequestCache
    * Application_AcquireRequestState
    * Application_PreRequestHandlerExecute
    * Application_PreSendRequestHeaders
    * Application_PreSendRequestContent
    <>
    * Application_PostRequestHandlerExecute
    * Application_ReleaseRequestState
    * Application_UpdateRequestCache
    * Application_EndRequest.

    Que:- How can we force all the validation control to run ?
    Ans:- Page.Validate

    Que:- How can we check if all the validation control are valid and proper ?
    Ans:- Using the Page.IsValid() property you can check whether all the validation are done.

    Que:- Which JavaScript file is referenced for validating the validators at the client side ?
    Ans:- WebUIValidation.js javascript file installed at “aspnet_client” root IIS directory is used
    to validate the validation controls at the client side

    Que:- What is Tracing in ASP.NET ?
    Ans:- Tracing allows us to view how the code was executed in detail.

    Que:- How do we enable tracing ?
    Ans:-

    Que:- How can we kill a user session ?
    Ans:- Session.abandon

    Que:- How do I send email message from ASP.NET ?
    ANs:- ASP.NET provides two namespaces System.WEB.mailmessage classand
    System.Web.Mail.Smtpmail class. Just a small homework create a Asp.NET project and
    send a email at "Email Adress". Do not Spam.

    Que:- Explain the differences between Server-side and Client-side code?
    Ans:- Server side code is executed at the server side on IIS in ASP.NET framework, while
    client side code is executed on the browser.
    0

    Add a comment

  6. In Windows applications written before the advent of .NET, developers used various methods for providing configuration information to applications, such as .INI files, System Registry, etc. All .NET applications are designed to read configuration from either the app.config (Winform or console apps) or web.config (web apps) file. This normally means the developer adds configuration data to the appSettings section of the app.config file, as shown below.

    appSettings
    add key="myKey" value="myValue"
    appsettings


    The developer can access this information in the application by the use of the following code:

    Dim value As String = ConfigurationSettings.AppSettings("myKey")

    This works fine for most applications, but as application complexity increases, a need arises to have duplicate keys in the appSettings section. There is a problem in the implementation of AppSettings Method. When the application loads, the app.config file is read by the application (behind the scenes) and the values from the App.Config file are placed in a NamedValueCollection. The problem is that if you have multiple duplicate keys in a section, only the last value in the section will be placed into the NamedValueCollection. The reason for this is that the collection works like a VB Collection, where you cannont have duplicate keys. If you examine the code through Reflector, you will see that the code is implemented in the following way:

    collection(i).value = key ' if the value already exists

    instead of

    collection(i).Add(key)

    In order to get around this shortcoming, you can implement a sosphicated solution by using IConfigurationSectionHandler. However, any chance I have to keep something simple, I always do it. That's a rule of life with me as a programmer. To me, there is enough complication in programming Windows and Web applications, that cannot be escaped, to unnecessarily complicate something, just to use something that I have never used in the .NET Framework. Some will not agree, but as you know, if you have read many of my articles, the KISS (keep it simple stupid) principle is always in my mind.

    My simple solution allows multiple "logical" duplicate keys without actually having real duplicates in the appSettings section.
    After all, the whole purpose is to get the data to the application without having to recompile the application every time you want to add the ability to handle new customers, etc., in the application. In this example, I have the requirement to be able to add a new customer name along with a userid and password to the app.config file. The application will use the customer names in a combo box, from which the user will select the desired customer. The application will then pick up the userid and password associated with the customer and use it to call a Web Service.

    The code shown below, in the FillCustomerCollection method, will be called by the Form_Load event. This method will build a collection of CustAcctPW objects. On return from this method, a method to load the combo box will be called. Finally, when the user selects a user from the combo box, the application will go through the collection to find the selected customer, and then retrieve the associated userid and password. I will not show all of that ancillary code, but I will quickly explain the logic behind this simple method.

    Instead of having multiple, duplicate keys in appSettings, which will not work, I will place a "NumberCustomers" key and value in the appSettings section of the app.config file. Next, I will add two "Customer" keys and associated values. Instead of duplicating the key, I simply give them keys of "Customer001", "Customer002", etc. The appSetting section that contains my customers is shown below.

    <configuration>
    <appSettings>

    -- Add Customer keys with Name|Account|PW -->
    <add key = "NUMBERCUSTOMERS" value = "2" />
    <add key = "CUSTOMER001" value="Jones Co|JONESUser|!23*(Abc1" />
    <add key = "CUSTOMER002" value= "NYTA|NYTAUserid|y*hg01K" />
    appSettings>
    configuration>

    The NumberCustomers value will determine the number of times to loop to retrieve the customers and associated data values. Obviously, you want to make sure that the value of NumberCustomers changes if you add or remove a customer, but then any other invalid value in your app.config file will probably cause something ugly in your application. I use the NumberCustomers as an index which will be converted to string and appended to "Customer" to access the appSetting. I concatenate multiple values of Customer, Userid (Account), and Password in the value field delimited by "|". The FillCustomerCollection method is shown below, along with the CustAcctPW class and collection.

    '''
    ''' The App Config file will have multiple CUSTNBRnnn keys in appsettings.
    ''' It will also have a NumberCustomers key with value = nbr of CustNbr occurrences.
    ''' Retrieve the number and use it to compute the value of each CustNbrnnn key value.
    ''' This must be done because the ConfigurationSettings.AppSettings method only picks up
    ''' the last value of a duplicate key name (bummer). This is because the code that builds
    ''' the NamedValueCollection stores into the collection, if a value exists, instead of
    ''' adding to the collection. It's built like an old VB Collection. I.,e., you can't have
    ''' but one occurrence of the same key name. But we wlll not be daunted...
    '''

    '''
    Private Sub FillCustomerCollection()
    Dim nbrCusts As Integer = _
    CType(ConfigurationSettings.AppSettings("NUMBERCUSTOMERS"), Integer)
    colCustomers =
    New Collection

    For i As Integer = 1 To nbrCusts
    Dim custKey As String = "CUSTOMER" & Format(i, "000")
    Dim custValue As String = ConfigurationSettings.AppSettings(custKey)
    Dim cust As New CustAcctPW
    Dim m As Match = Regex.Match(custValue, _
    "(?\w+)\|(?\w+)\|(?\w+)")
    If m.Success Then
    cust.Customer = m.Groups("cust").Value
    cust.Account = m.Groups(
    "acct").Value
    cust.PW = m.Groups(
    "pw").Value
    colCustomers.Add(cust)
    End If
    Next
    End Sub

    Private colCustomers As Collection
    Public Class CustAcctPW
    Public Customer As String
    Public Account As String
    Public PW As String
    End
    Class

    The following method fills the combo box from the collection of customer data created by the FillCustomerCollection method shown above.

    ' Fill the customer combo box with customer numbers from the
    ' colCustomers collection.
    Private Sub FillCustomerCombo(ByVal colCustomers As Collection)
    Me.cboSelectCustomer.Items.Clear()
    For i As Integer = 1 To colCustomers.Count
    Dim cust As CustAcctPW = CType(colCustomers(i), CustAcctPW)
    Me.cboSelectCustomer.Items.Add(cust.Customer)
    Next
    End Sub

    Finally, the following combo box event handler fills the userid and password text boxes when the user selects a customer in the combo box.

    Private Sub cboSelectCustomer_SelectedIndexChanged(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles cboSelectCustomer.SelectedIndexChanged
    If formLoading Then Exit Sub
    For i As Integer = 1 To colCustomers.Count
    Dim cust As CustAcctPW = CType(colCustomers(i), CustAcctPW)
    If cust.Customer = cboSelectCustomer.Text Then
    Me.txtAccount.Text = cust.Account
    Me.txtPassword.Text = cust.PW
    End If
    Next
    End Sub
    0

    Add a comment

Subscribe
Subscribe
Favorite Links
Blog Archive
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.