Thursday, 27 October 2011

c-sharp dot net code for tricky game using some mouse events


Introduction:

This is tricky game using some mouse events.

Step 1:

Add a form in application and make it borderStyle property none.

Step 2:

Add a picturebox and two buttons in the form.




Step 3:

int x, y;
bool quit = false;
bool win =false;

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    if (quit == false && win == false)
    {
        /*
        When you take mouse over the picturebox randmoly two value generated
        And it is different every time..and that two value assign to x and y which is  
        use to set picture at different location whenever you take mouse over the picture.
        */
        x = Convert.ToInt32(Microsoft.VisualBasic.VBMath.Rnd() * ((this.ClientSize.Width) - 50));
        y = Convert.ToInt32(Microsoft.VisualBasic.VBMath.Rnd() * ((this.ClientSize.Height) - 60));
        pictureBox1.Location = new System.Drawing.Point(x, y);
    }
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
    win = true;
    pictureBox1.Image = global::fungame_clickMe.Properties.Resources.winner;
    pictureBox1.Location = new System.Drawing.Point(200, 180);
    pictureBox1.Size = new System.Drawing.Size(200, 200);
}
private void button1_Click(object sender, EventArgs e)
{
    this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
    quit = true;
    pictureBox1.Image = global::fungame_clickMe.Properties.Resources.loser;
    pictureBox1.Location = new System.Drawing.Point(200, 180);
    pictureBox1.Size = new System.Drawing.Size(200,200);
}

Saturday, 22 October 2011

c# ASP.NET Interview Questions And Answers Part-2


What is ADO .NET and what is difference between ADO and ADO.NET? 
ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.
Explain the differences between Server-side and Client-side code?
Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn’t have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.
What type of code (server or client) is found in a Code-Behind class? 
C# 
Should validation (did the user enter a real date) occur server-side or client-side? Why? 
Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.
What does the "EnableViewState" property do? Why would I want it on or off? 
Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.
What is the difference between Server.Transfer and Response.Redirect? 
Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist across the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical location (page name and query string as well). Context.Items loses the persistence when navigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.
Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component? 
When to Use Web Services:
* Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.

* Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.

* Business-to-Business Integration This is an enabler for B2B integration which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.

* Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary component-based reuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of several other Applications. Each of these functions could be performed by individual apps, but there is value in perhaps combining the multiple apps to present a unified view in a Portal or Intranet.

* When not to use Web Services: Single machine Applications When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Components as there is very little overhead.

* Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
In ADO, the in-memory representation of data is the RecordSet. In ADO.NET, it is the dataset. There are important differences between them.

* A RecordSet looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.

* In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies.

* Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.

* Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.

* Richer data types.COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.

* Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.

* Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.
Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.

If I’m developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users? 
What are ASP.NET Web Forms? How is this technology different than what is available though ASP?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application. 
How does VB.NET/C# achieve polymorphism? 
By using Abstract classes/functions.

Monday, 10 October 2011

ASP.NET interview questions and answers


1. Explain how a web application works.
A web application resides in the server and serves the client’s requests over internet. The client
access the web page using browser from his machine. When a client makes a request, it receives
the result in the form of HTML which are interpreted and displayed by the browser.
A web application on the server side runs under the management of Microsoft Internet
Information Services (IIS). IIS passes the request received from client to the application. The
application returns the requested result in the form of HTML to IIS, which in turn, sends the result
to the client.

2. Explain the advantages of ASP.NET.
Following are the advantages of ASP.NET.
Web application exists in compiled form on the server so the execution speed is faster as
compared to the interpreted scripts.
ASP.NET makes development simpler and easier to maintain with an event-driven, server-side
programming model.
Being part of .Framework, it has access to all the features of .Net Framework.
Content and program logic are separated which reduces the inconveniences of program
maintenance.
ASP.NET makes for easy deployment. There is no need to register components because the
configuration information is built-in.
To develop program logic, a developer can choose to write their code in more than 25 .Net
languages including VB.Net, C#, JScript.Net etc.
Introduction of view state helps in maintaining state of the controls automatically between the
postbacks events.
ASP.NET offers built-in security features through windows authentication or other authentication
methods.
Integrated with ADO.NET.
Built-in caching features.

3. Explain the different parts that constitute ASP.NET application.
Content, program logic and configuration file constitute an ASP.NET application.
Content files
Content files include static text, images and can include elements from database.
Program logic
Program logic files exist as DLL file on the server that responds to the user actions.
Configuration file
Configuration file offers various settings that determine how the application runs on the server.

4. Describe the sequence of action takes place on the server when ASP.NET application
starts first time?

Following are the sequences:
IIS starts ASP.NET worker process>> worker process loads assembly in the memory>>IIS sends
the request to the assembly>>the assembly composes a response using program logic>> IIS
returns the response to the user in the form of HTML.

5. Explain the components of web form in ASP.NET
Server controls.
The server controls are Hypertext Markup Language (HTML) elements that include a
runat=server attribute. They provide automatic state management and server-side events and
respond to the user events by executing event handler on the server.
HTML controls.
These controls also respond to the user events but the events processing happen on the client
machine.
Data controls
Data controls allow to connect to the database, execute command and retrieve data from
database.
System components
System components provide access to system-level events that occur on the server.

6. Describe in brief .NET Framework and its components.
.NET Framework provides platform for developing windows and web software. ASP.NET is a part
of .Net framework and can access all features implemented within it that was formerly available
only through windows API. .NET Framework sits in between our application programs and
operating system.
The .Net Framework has two main components:
.Net Framework Class Library: It provides common types such as data types and object types
that can be shared by all .Net compliant language.
The Common language Runtime: It provides services like type safety, security, code execution,
thread management, interoperability services.

7. What is an Assembly? Explain its parts?
An assembly exists as a .DLL or .EXE that contains MSIL code that is executed by CLR.
An assembly contains interface and classes, it can also contain other resources like bitmaps, files
etc. It carries version details which are used by the CLR during execution. Two assemblies of the
same name but with different versions can run side-by-side enabling applications that depend on
a specific version to use assembly of that version. An assembly is the unit on which permissions
are granted. It can be private or global. A private assembly is used only by the application to
which it belongs, but the global assembly can be used by any application in the system.
The four parts of an assembly are:
Assembly Manifest - It contains name, version, culture, and information about referenced
assemblies.

Type metadata - It contains information about types defined in the assembly.
MSIL - MSIL code.
Resources - Files such as BMP or JPG file or any other files required by application.

8. Define Common Type System.
.Net allows developers to write program logic in at least 25 languages. The classes written in one
language can be used by other languages in .Net. This service of .Net is possible through CTS
which ensure the rules related to data types that all language must follow. It provides set of types
that are used by all .NET languages and ensures .NET language type compatibility.

9. Define Virtual folder.
It is the folder that contains web applications. The folder that has been published as virtual folder
by IIS can only contain web applications.

10. Describe the Events in the Life Cycle of a Web Application
A web application starts when a browser requests a page of the application first time. The request
is received by the IIS which then starts ASP.NET worker process (aspnet_wp.exe). The worker
process then allocates a process space to the assembly and loads it. An application_start event
occurs followed by Session_start. The request is then processed by the ASP.NET engine and
sends back response in the form of HTML. The user receives the response in the form of page.
The page can be submitted to the server for further processing. The page submitting triggers
postback event that causes the browser to send the page data, also called as view state to the
server. When server receives view state, it creates new instance of the web form. The data is
then restored from the view state to the control of the web form in Page_Init event.
The data in the control is then available in the Page_load event of the web form. The cached
event is then handled and finally the event that caused the postback is processed. The web form
is then destroyed. When the user stops using the application, Session_end event occurs and
session ends. The default session time is 20 minutes. The application ends when no user
accessing the application and this triggers Application_End event. Finally all the resources of the
application are reclaimed by the Garbage collector.


Saturday, 13 August 2011

C-Sharp Dot Net Code


using System;

namespace randomPassword
{
   
    class Program
    {
       
        static void Main(string[] args)
        {
            // Gets the length  of the password.
            int len;

            // Gets the type of the password
            int sel;

            // Gets a random value.
            int rand;

            // The string that contains the password.
            string pass = "";

            // Random number.
            Random num = new Random();

            // Get the password length (user input).
            Console.WriteLine("Password length:");
            len = Convert.ToInt32(Console.ReadLine());

            // Get the password type (user input).
            Console.WriteLine("Select password type:");
            Console.WriteLine("1 - Letters, Symbols, Numbers");
            Console.WriteLine("2 - Letters, Symbols");
            Console.WriteLine("3 - Letters, Numbers");
            Console.WriteLine("4 - Letters");
            Console.WriteLine("5 - Numbers");
            sel = Convert.ToInt32(Console.ReadLine());
           
            // Based on the password type, generate a password.
            switch (sel)
            {
                    // Complex password (letters, numbers, symbols).
                case 1:
                    for (int c1 = 0; c1 < len; c1++)
                        pass += char.ConvertFromUtf32(num.Next(33, 126));
                    break;

                    // Password composed of letters and symbols.
                case 2:
                    for (int c1 = 0; c1 < len; c1++)
                    {
                    genNew:rand = num.Next(33, 126);
                        if ((rand < 48) || (rand > 57))
                        {
                            pass += char.ConvertFromUtf32(rand);
                        }
                        else
                        {
                            goto genNew;
                        }
                    }
                    break;

                    // Password composed of letters and numbers.
                case 3:
                    for (int c1 = 0; c1 < len; c1++)
                    {
                    genNew2:
                        rand = num.Next(33, 126);
                        if (((rand > 47) && (rand < 58)) || ((rand < 122) && (rand > 96)) || ((rand < 89) && (rand > 64)))
                        {
                            pass += char.ConvertFromUtf32(rand);
                        }
                        else
                        {
                            goto genNew2;
                        }
                    }
                    break;

                    // Password composed of letters.
                case 4:
                    for (int c1 = 0; c1 < len; c1++)
                    {
                    genNew3:
                        rand = num.Next(33, 126);
                        if (((rand > 65) && (rand < 90)) || ((rand < 122) && (rand > 96)))
                        {
                            pass += char.ConvertFromUtf32(rand);
                        }
                        else
                        {
                            goto genNew3;
                        }
                    }
                    break;

                    // Password composed of numbers.
                case 5:
                    for (int c1 = 0; c1 < len; c1++)
                    {
                        pass += char.ConvertFromUtf32(num.Next(48, 57));
                    }
                    break;
            }

            // Show the generated password.
            Console.WriteLine("Your password is: {0}", pass);
            Console.ReadLine();

        }
    }
}