Showing posts with label Asp.Net Interview Questions. Show all posts
Showing posts with label Asp.Net Interview Questions. Show all posts

Friday, March 11, 2016

Learn ASP.NET MVC step by step: - Part 2

Contents

Learn ASP.NET MVC step by step: - Part 2

Introduction

Step 11: Understanding Model binder

Step 12: Create model Binder Class.

Step 13: Attach the binder with the object and execute

Step 14: Implementing validation

Step 15: Check If the validations are proper

Step 16: Displaying error message

Step 17: Client side validation with Jquery

Introduction

This complete article is a guest post written by Mr. Prathamesh mestry https://www.facebook.com/prathamesh.mestry?pnref=story . If you think he is doing a good job send him a silent thanks to his FB.

In part 1 we saw http://www.codeproject.com/Articles/1081437/Learn-ASP-NET-MVC-Step-by-Step-Part basics of how to start MVC. In this session we will see model binder and validations. In validation we will do server side validations using data annotations and client side using Jquery.

In case you are completely new to MVC we would suggest you to watch this video series Learn MVC in 16 hours given in the below youtube video.

Step 11: Understanding Model binder

Model binder helps to connect the UI controls to the model objects of MVC. In the previous article our UI text box names where same as customer class names so we did not have issues. But what if you text box names are different from class names.

For example below is a customer UI which has text box names start with “txt” and class property names are without word “txt”.

You can see the below class is not in synch with UI text box names.

publicclassStudent
{
publicstringStudentRollNo{ get; set; } //Student Roll No.
publicstringStudentName{ get; set; } //Student Name.
publicstringStudentStd{ get; set; } //Student Standard.
publicstringStudentDIV { get; set; }//Student Division.
}

This is where model binder class comes to picture. Model binder class binds the UI textboxes with model.

Step 12: Create model Binder Class.

To create a model binder class the first thing we need to do is implement interface “IModelBinder”.

Right Click on ModelBinder Class  Implement Interface  Implement Interface.

In the class we need to put the binding code in “BindModel” method as shown below.

public class StudentBinder : IModelBinder
    {

public object BindModel(ControllerContextcontrollerContext, 
ModelBindingContextbindingContext)
        {
HttpContextBaseobjContext = controllerContext.HttpContext;
stringstuRoll = objContext.Request.Form["txtStudentRollno"];
stringstuName = objContext.Request.Form["txtStudentName"];
stringstuStd = objContext.Request.Form["txtStudentStd"];
stringstuDiv = objContext.Request.Form["txtStudentDiv"];
            Student obj = new Student()
            {
StudentRollNo = stuRoll,
StudentName = stuName,
StudentStd = stuDiv,
StudentDIV = stuDiv,

            };
returnobj;
        }
    }

Step 13: Attach the binder with the object and execute

Once the binding code is completed attach the binder with the object and execute to see the results.

public ActionResult Submit([ModelBinder(typeof(StudentBinder))] Student obj)
{

return View("Student",obj);

}

Step 14: Implementing validation

Now that we have the student screen and the output is displayed it’s time to put validations. So we will be applying the following validation for our student class:-

  • Student name and roll number is required.
  • Student Rollno should be alphanumeric with 7 characters with first three letter characters and last four letter numeric for example :-ABC1234, XYZ5678.

In order to implement validations we need to import “data annotation” namespace and decorate the attributes on the student properties.

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel.DataAnnotations;
usingSystem.Linq;
usingSystem.Web;

namespaceHelloWorld.Models
{
public class Student
    {

        [Required]
        [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string StudentRollNo{ get; set; } //Student Roll No.

        [Required]
        [StringLength(10)]
public string StudentName{ get; set; } //Student Name.
public string StudentStd{ get; set; } //Student Standard.
public string StudentDIV { get; set; }//Student Divsion.
    }
}

Step 15: Check If the validations are proper

When the object is filled the final output whether the validation is passed or failed is updated to the “ModelState” object. You can see in the below code we are checking if the “ModelState” object is valid by using the “IsValid” property.

Depending on the property value its redirecting to the views.

public ActionResult Submit(Student obj)
        {
if (ModelState.IsValid)
            {
return View("Student", obj);
            }
else
            {
return View("EnterStudent");
            }
        }

Step 16: Displaying error message

To display error message we need to use Helper class as shown in the below code.

Step 17: Client side validation with Jquery

Install Jqurey validation from Nuget.

33.1 In Solution Explorer Right Click on MyApplication (HelloWorld).  Click on Manage NuGet Packages

Search jQuery Validation.  Select Microsoft jQuery Unobtrusive Validation  install

Using Helper class Create UI elements like Textboxes.

Output Screen of EnterStudent View using Html helper Class...

Validation Output 2(incorrect RollNo)

Monday, May 19, 2014

Server.Transfer” VS “Response.Redirect” – Simplified

Introduction

“Server.Transfer”vs “response.Redirect”

So when to use “Server.Transfer” and when to use “Response.Redirect” ?

What is importance of “preserveForm” flag in “Server.Transfer”?

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?

Introduction


In ASP.NET some of the concepts do the same task but are meant to be used in different scenarios. One such concept which is confusing and most discussed among developers is the difference between “Server.Transfer” and “Response.Redirect”.



“response.redirect” and “server.transfer” helps to transfer user from one page to other page while the page is executing. But the way they do this transfer / redirect is very different.

In this short blog we will discuss about how they differ and in which scenarios we should use them.

In case you are visual guy and would like see demonstration rather than theory I would suggest to see the below facebook video which explains the difference in a more demonstrative way.



“Server.Transfer”vs “response.Redirect”


The main difference between them is who does the transfer. In “response.redirect” the transfer is done by the browser while in “server.transfer” it’s done by the server. Let us try to understand this statement in a more detail manner.

In “Server.Transfer” following is the sequence of how transfer happens:-
  1. User sends a request to an ASP.NET page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Server starts executing “Webform1” and the life cycle of the page starts. But before the complete life cycle of the page is completed “Server.transfer” happens to “WebForm2”.
  3. “Webform2” page object is created, full page life cycle is executed and output HTML response is then sent to the browser.



One important point to note here is the URL is not changed to the target page. If you have sent request from “Webform1.aspx” to redirect to “WebForm2.aspx” on the browser URL you will still see “WebForm1.aspx”.

While in “Response.Redirect” following is the sequence of events for navigation:-
  1. Client (browser) sends a request to a page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Life cycle of “Webform1” starts executing. But in between of the life cycle “Response.Redirect” happens.
  3. Now rather than server doing a redirect , he sends a HTTP 302 command to the browser. This command tells the browser that he has to initiate a GET request to “Webform2.aspx” page.
  4. Browser interprets the 302 command and sends a GET request for “Webform2.aspx”.

In this case you will the URL’s are changed as per redirection. So if you have redirected to “Webform2.aspx” then on the browser URL you should see “WebForm2.aspx”.

In other words “Server.Transfer” is executed by the server while “Response.Redirect” is executed by thr browser. “Response.Redirect” needs to two requests to do a redirect of the page.

So when to use “Server.Transfer” and when to use “Response.Redirect” ?


Use “Server.Transfer” when you want to navigate pages which reside on the same server, use “Response.Redirect” when you want to navigate between pages which resides on different server and domain.



Below goes the consolidated table with all the differences as discussed at the top.

Server.TransferResponse.Redirect
RedirectionRedirection is done by the server.Redirection is done by the browser client.
Browser URLDoes not change.Changes to the redirected target page.
When to useRedirect between pages of the same server.Redirect between pages on different server and domain.


What is importance of “preserveForm” flag in “Server.Transfer”?


“Server.Transfer” helps to redirect from one page to other page. If you wish to pass query string and form data of the first page to the target page during this redirection you need to set “preserveForm” to “true” as shown in the below code.

Server.Transfer("Webform2.aspx",true);

By default the value of “preserveForm” is “true”.

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?


Response.Redirect(URL,false) :- Client is redirected to a new page and the current page on the server will keep processing ahead.

Response.Redirect(URL,true) :- Client is redirected to a new page but the processing of the current page is aborted.


Below is a facebook video whichdemonstrates practically the difference between server.transfervsresponse.redirect .A big thanks to www.questpond.com to allow me to publish this videos for free on facebook.



Monday, April 29, 2013

34 important ASP.NET Interview questions



34 important ASP.NET Interview questions


Below are 34 important ASP.NET interview questions which repeat again and
again in .NET Interviews .


  1. What is an application object?
  2. what is the difference between Cache object and application object?
  3. How can get access to cache object?
  4. What are dependencies in cache and types of dependencies?
  5. Can you show a simple code showing file dependency in cache?
  6. What is Cache Callback in Cache?
  7. What is scavenging?
  8. What are different types of caching using cache object of ASP.NET?
  9. How can you cache different version of same page using ASP.NET cache object?



  10. How will implement Page Fragment Caching?


  11. Can you compare ASP.NET sessions with classic ASP?


  12. Which are the various modes of storing ASP.NET session?


  13. Is Session_End event supported in all session modes? 106


  14. What are the steps to configure StateServer Mode?


  15. What are the steps to configure SQLServer mode?


  16. Where do you specify session state mode in ASP.NET?


  17. What are the other ways you can maintain state?


  18. What are benefits and Limitation of using Hidden fields?


  19. What is ViewState?


  20. Does the performance for viewstate vary according to User controls?


  21. What are benefits and Limitation of using Viewstate for state management?



  22. How can you use Hidden frames to cache client data ?


  23. What are benefits and limitations of using Hidden frames?


  24. What are benefits and limitations of using Cookies? 109


  25. What is Query String and What are benefits and limitations of using Query
    Strings?


  26. What is Absolute and Sliding expiration?


  27. What is cross page posting?


  28. How do we access viewstate value of this page in the next page ?


  29. Can we post and access view state in another application?


  30. What is SQL Cache Dependency in ASP.NET 2.0?


  31. How do we enable SQL Cache Dependency in ASP.NET 2.0?


  32. What is Post Cache substitution?


  33. Why do we need methods to be static for Post Cache substitution?


  34. Can you explain page life cycle ?





Saturday, April 27, 2013

ASP.NET Interview Questions: - Show Post Cache substitution?


This is one of the asked ASP.Net Interview Questions during the Interview by the Interviewer.

Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.

Post-cache substitution can be achieved by two means:


  • Call the new Response.WriteSubstitution method, passing it a reference to the desired substitution method callback.

  • Add a <> control to the page at the desired location, and set its methodName attribute to the name of the callback method.



Learn more on ASP.NET interview questions

Regards,

From more on author’s blog related to ASP.NET interview questions click and visit.

ASP.NET Interview Questions: - Show Post Cache substitution?

This is one of the asked ASP.Net Interview Questions during the Interview by the Interviewer.
Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.
Post-cache substitution can be achieved by two means:

Figure: - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response substitution callback to the “WriteSubstitution” method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it’s content is never cached.
Ok the above example was by using “WriteSubstitution” now lets try to see how we can do by using “<>” control. You can get the “<>” control from the editor toolbox.
Figure: - Substitution Control
Figure: - Substitution in Action
Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the “methodname” attribute of the substitution control.
View following video on Web.config transformation in ASP .Net: -

Learn more on ASP.NET interview questions
Regards,
From more on author’s blog related to ASP.NET interview questions click and visit.

Thursday, November 22, 2012

C# and ASP.NET MVC (Model view controller) interview questions and answers:- What are MVC partial views and how can we call the same in MVC pages?

ASP.NET MVC (Model view controller) partial view is a reusable view (like a user control)which can be embedded inside other view. For example let's say all your pages of your site have a standard structure with left menu,header and footer as shown in the image below.



For every page you would like to reuse the left menu, header and footer controls.So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

When you add a view to your project you need to check the “Create partial view” check box.



Once the partial view is created you can then call the partial view in the main view using "Html.RenderPartial" method as shown in the below code snippet'










Below is an important SQL server interview question and answers video:-




Do visit us for c#  and ASP.NET MVC interview question and answers

See more stuffs on C#/ASP.NET interview questions 

Regards,

Click here to see more C# and ASP.NET interview questions and answers

Friday, June 8, 2012

Site is under maintenance, please visit later: - ASP.NET trick

24 x 7 uptime guaranteed



As a web site owner we all boast about 24 x 7 uptime. But somewhere down below in our hearts we know it’s difficult. We need to bring down the website for maintenance, fixingdefects, upgrading etc.

Easy way…

As an innocent c# ASP.NET developer you would think how about just stopping IIS web server, do your activity(maintenance, fixing defect etc.) and then start the IIS again.



While this looks to be a but obvious way of solving the problem but it’s not the best way if we consider the end user perspective. The end user would see an ugly screen as shown below leading to more confusion.



Rather than end user seeing that kind of absurd screen how about showing something more better and informative like: - “Site is under maintenance and will be live till 3:00 AM”.

Going offline graciously:-App_Offline.htm

Also I would like to highlight here it’s not about showing the error message but technically we would like to ensure that the following things happen in IIS:-
  • Application domain under which the website is running is brought down.
  • All incoming request coming to the ASP.NET site needs to stopped.
  • All request to be routed to the temporary page which is created.
  • After maintenance the application domain should be loaded and the incoming request should be processed in a normal manner.
Thanks to Microsoft they always understand our needs. The proper way of approaching this problem is to create a simple “App_offline.htm” file in your application root directory. In this “App_offline.htm” you can put your user friendly message which the end users can see when the site is under maintenance.
Once done you can delete the file and your web site app domain is loaded and the normal life continues.






You can visit my site for
C# and .NET interview questions and in case you are a fresher you can attend FREE C# training by clicking on C# training videos.

Take a quick look as revision for practical video on "Site is under maintenance"

Thursday, May 3, 2012

ASP.Net Interview questions: - Mention differences between ‘Server.Transfer’ and ‘response.Redirect’?

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 cannot redirect to a different from the server itself. Example if your server is www.yahoo.com you cannot use server. Transfer to move to www.microsoft.com but yes, you can move to www.yahoo.com/travels, i.e. with in websites. Cross server redirect is possible only by using Response. Redirect.

With ‘server. Transfer’ you can preserve your information. It has a parameter called as “preserveForm”.Therefore, the existing query string etc. will be able in the calling page.

If you are navigating within the same website use “Server. Transfer” or else go for “response.Redirect ()”

See the following video on ASP.NET4.0: -



Click for more ASP.NET interview questions

Regards,

Visit for more Authors’ blog on ASP.NET interview questions

Saturday, April 21, 2012

ASP.NET interview questions: - How will you explain differences between ASP and ASP.NET?

This is the most practical oriented ASP.NET Interview Questions which may be asked during the Interview by the Interviewer.

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 Data grid, Repeater and datalist.Many of the display grid havpaging 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
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).

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.

See the following video on ASP.NET for importance of session and view state: -



Click for more ASP.NET interview questions

Regards,

Visit for more Authors’ blog on ASP.NET interview questions

Wednesday, April 18, 2012

ASP.NET interview questions: - Show in brief how the ASP.NET authentication process works?

ASP.NET does not run by itself, it runs inside the process of IIS. Therefore, there are two authentication layers, which exist in ASP.NET system. First authentication happens at the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.

Below is how the whole process works:-
  • IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.
  • Next IIS performs its own user authentication if it is configured to do so. By default IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per – application basis with in IIS.
  • If the request is passed to ASP.NET with an authenticated user, ASP.net checks to see whether impersonation is enabled. If impersonation is enabled, ASP.net acts as though it were the authenticated user. If not ASP.net acts with its own configured account.
  • Finally, the identity from step 3 is used to request resources from the operating system. If ASP.net authentication can obtain all the necessary resources it grants the users request otherwise it is denied. Resources can include much more than just the ASP.net page itself you can also use .NET’s code access security features to extend this authorization step to disk files, Registry keys and other resources.

See the following video on ASP.NET Forms authentication by using session hijack: -



Click for more ASP.NET interview questions

Regards,

Visit for more Author's blog on ASP.NET interview questions

Saturday, April 14, 2012

ASP.NET interview questions: - Mention benefits and limitations of using Query Strings?

A simple but most frequently asked ASP.NET interview question.

A query string is information sent to the server appended to the end of a page URL.

Following are the benefits of using query string for state management:-
  • No server resources are required. The query string containing in the HTTP requests for a specific URL.
  • All browsers support query strings.
Following are limitations of query string:-
  • Query string data is directly visible to user thus leading to security problems.
  • Most browsers and client devices impose a 255-character limit on URL length.
See the following video on ASP.NET for importance of session and viewstate: -



Explore for more ASP.NET interview questions tutorials.

Regards,

From Author’s blog see other blog links ASP.NET interview questions

Tuesday, April 10, 2012

ASP.NET Interview questions: - Mention use of session and viewstate in ASP.NET?

HTTP is a stateless protocol , session and viewstate help you to maintain states between request and response.

For more information see the below video.



Click for more ASP.NET Interview questions

Regards,

Visit for more authors’ blog on ASP.NET Interview questions

Thursday, March 22, 2012

ASP.NET interview questions: - Can you differentiate between trace and debug in ASP.NET?

There is also a fundamental difference in thinking when we want to use trace and when want to debug. Tracing is a process about getting information regarding program's execution. On the other hand debugging is about finding errors in the code.

Debug and trace enables you to monitor the application for errors and exception without VS. NET IDE.

In Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the part of the executable they run on the same thread where the code runs and they do not given you the exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will see a debug file also as shown in figure ‘Debug Mode’.

Figure: - Debug mode
Trace works in both debug as well as release mode. The main advantage of using trace over debug is to do performance analysis which cannot be done by debug. Trace runs on a different thread thus it does not impact the main code thread.

See the following video for how to Skip debugging in ASP. NET: -



Click for more ASP. NET Interview questions

Regards,

Visit for more authors’ blog on ASP. NET Interview questions

Thursday, March 1, 2012

ASP.NET Interview Questions: - Show Post Cache substitution?

This is one of the asked ASP.Net Interview Questions during the Interview by the Interviewer.
Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.

Post-cache substitution can be achieved by two means:







Figure: - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response substitution callback to the “WriteSubstitution” method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it’s content is never cached.



Figure: - Substitution Control
Figure: - Substitution in Action
Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the “methodname” attribute of the substitution control.

View following video on Web.config transformation in ASP.Net: -



Learn more on ASP.NET interview questions

Regards,

From more on author’s blog related to ASP.NET interview questions click and visit.

Saturday, December 10, 2011

.NET/ASP.NET interview questions: - While choosing design, when to consider Data grid, data list, or repeater?

This is one of quiet often asked .NET/ASP.NET interview questions so prepare accordingly to answer it to the interviewer.

Many of the developers make a blind choice of choosing data grid directly, but that is not the right way.

Data grid provides ability to allow the end-user to sort, page, and edit its data. However, 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 Data List provides more control over the look and feel of the displayed data than the Data Grid. It offers better performance than data grid

Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the data binding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the Data Grid and Data List. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. However, repeater does not provide editing features like data grid 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 data grid.

See video on ASP.NET 4.0 web.config transformation as follows: -



Get more fundamentals stuffs on .NET/ASP.NET interview questions

Regards,
More from author’s blogs on .NET/ASP.NET interview questions for interview references

Monday, December 5, 2011

ASP.NET interview questions: - Working of Forms authentication in ASP.NET

Start answering this ASP.NET interview questions as follows: -

In traditional ASP if you are told to create a login page and do authentication you have to do hell lot of custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see in detail what form authentication is.

Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then Forms authentication mechanism sends the user to the login page.

Following are the steps, which defines steps for Forms authentication:-
  • Configure Web.config file with forms authentication. As shown below in the config file you can see we have give the cookie name and loginurl page.
  • Remove anonymous access to the IIS web application, following are changes done to web.config file.
  • Create the login page, which will accept user information. You will have create your login page that is the Login.aspx, which will actually take the user data.
  • Finally a small coding in the login button.
Let us assume that the login page has two textboxes TX name and txtapssword.

Also, import System.Web.Security and put the following code in login button of the page.


See the following video on Single sign-on using forms authentication in ASP.NET as follows: -



Click and see more ASP.NET interview questions

Regards,

Also view author’s other blog on ASP.NET interview questions

Friday, October 28, 2011

ASP.NET interview questions: - Unique Code in ASP.NET.

This is one of the requirements that would come across you many a times while working on .NET projects. Some of the senior developers will find this question very easy but many of the developer friends find it difficult to answer the above question.

So we have tried to give an answer for this ASP. NET interview questions in the practical form as follows: -

So take a small example to see how exactly we can create a Unique Code like C001, C002……., C00n. 
In order to see it practically you just need to follow the following steps: -

Step1: - Create an ASP.NET Web Application for that just open Visual Studio >> go to >>File >> New >> Project >> Web>> Select ASP.NET Empty Web Application. 




Step2: - Now simply just add a Web Form in to your Web Application for that just go to Solution Explorer >> Right click on the Project name>> ADD >> New Item>> Select Web Form.
Step3: - Assume that we have the table of Customer like below diagram.


Step4: - Design your Web Form like below diagram.



Also add a GridView Control to your WebForm.aspx page.


Step5: - This is the most important step for creating Unique Customer code.
Add the below code snippet in to your WebForm.aspx.cs file.
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AutoGenerateCode();
            }
        }
        public void AutoGenerateCode()
        {
            string Unique Code = "";
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand();
            com.CommandText = "select CustCode from Customer where CustomerID in (select max(CustomerID) from Customer)";
            com.Connection = con;
            SqlDataReader objRead = com.ExecuteReader();
            if (objRead.Read())
            {
                UniqueCode = objRead[0].ToString();
                string sd = UniqueCode.Remove(0, 1);
                int sd1 = Int32.Parse(sd) + 1;
                UniqueCode = sd1.ToString();
                if (UniqueCode.Length == 3)
                {
                    UniqueCode = "C" + UniqueCode;
                }
                if (UniqueCode.Length == 2)
                { 
                    UniqueCode = "C" + "0" + UniqueCode; 
                }
                if (UniqueCode.Length == 1)
                {
                    UniqueCode = "C" + "0" + "0" + UniqueCode; 
                }
            }
            else 
            {
                UniqueCode = "C001"; 
            }
            objRead.Close();
            con.Close();
            TextBox3.Text = UniqueCode;
            //The below line will not allow 
            //the user to modify the Unique Code.
            TextBox3.ReadOnly = true;
        }
Once you have done with all the above steps simply run the application and will see the result like below diagram.

In the above code snippet you can clearly see that the Unique Customer Code is been generated.

See the following video on ASP.NET Authentication, Authorization, Principal and Identity objects as follows: -



Visit for more ASP.NET interview questions

Regards,

Get more from author’s blog for ASP.NET interview questions.

Saturday, October 22, 2011

ASP.NET interview questions: - How to make GridView Editable, Updateable and Deleteable in ASP.NET?


The process of making GridView Editable, Updateable and Deleteable is almost used in the entire ASP.NET project. So, making GridView Editable, Updateable and Deleteable is one of the most important aspects according to any ASP.NET project.

Let’s create a simple demonstration to understand the concept of making GridView Editable, Updateable and Deleteable in much better manner.

In order to see it practically you just need to follow the following steps.

Step1: - Create a simple ASP.NET Web Application for that just open Visual Studio >>go to >> File >> New >> Project >> Web >> Select ASP.NET Empty Web Application.



Step2: - Now, simply just add a Web Form to your ASP.NET
Empty Web Application for that just go to >> Solution Explorer >> Right Click on the project name >> Add >> New Item >> Select Web Form.


Now, simply just drag and drop GridView to your Web Form and allow the below
properties to true.

1. Allow AutoGenerateEditButton to True.

2. Allow AutoGenerateDeleteButton to True.


Now, as soon as you set the above two properties you will see the GridView like below diagram.


Step3: - Now, let bind the GridView with Data for that just add the below
code snippet in to your WebForm.aspx.cs file.

        //Below variable holds the Connection String.
string str = ConfigurationManager.AppSettings["Connect"];

protected void Page_Load(object sender, EventArgs e)
 {
  if (!IsPostBack)
  {
      GridViewData();
  }
}

//Created a GridViewData method to bind data to GridView
//from the SQL Server DataBase Table.
public void GridViewData()
{
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "select * from Book";
  com.Connection = con;
  com.ExecuteNonQuery();
  SqlDataAdapter adap = new SqlDataAdapter(com);
  DataSet ds = new DataSet();
  adap.Fill(ds);
  GridView1.DataSource = ds;
  GridView1.DataBind();
}

Step4: - This is the most important step while making GridView Editable, Updateable and Deleteable.

Now, simply just add the below Events of the GridView control in to your
Web Application.

1. OnRowEditing.

2. OnRowCancelingEdit.

3. OnRowUpdating.

4. OnRowDeleting.


Step5: - now, just add the below code snippet to make necessary changes on the respective events of the
GridView control.

1. OnRowEditing add the below code snippet.

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 {
  GridView1.EditIndex = e.NewEditIndex;
  GridViewData();
  }

2. OnRowCanelingEdit add the below code snippet.

 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
  GridView1.EditIndex = -1;
  GridViewData();
}

3. OnRowDeleting add the below code snippet.

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  //The below line of code will hold the Cells[1] data of th GridView Control.
  string id = GridView1.Rows[e.RowIndex].Cells[1].Text;
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "delete from Book where Book_Id = '"+id+"'";
  com.Connection = con;
  com.ExecuteNonQuery();
  GridViewData();
 }

4. OnRowUpdating add the below code snippet.

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  string id = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
  string bookname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;            string author = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
  string price = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
  string quantity = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "update Book set Book_Name='" + bookname + "',Book_Author='" + author + "',Book_Price='" + price + "',Book_Quantity='" + quantity + "' where Book_Id= '" + id + "'";
  com.Connection = con;
  com.ExecuteNonQuery();
  GridViewData();
}

Note: - You can modify your code according to your requirements.

Step6: - Now, let’s run your Web Application and see the respective results.

Let’s first see the result for deleting.


The above diagram is my output of the loaded GridView and note that I am going to delete the
circled row data from the GridView control.

Now, as soon as you click on the delete link will see the result like below diagram.




In the above result of diagram you can see that the data has been deleted.

Similarly, let’s see the result for updating the below circled row data in the
GridView control.


Now, as soon as you click on the edit link you will see something like below diagram.


Now, let’s modify the Book_Author Name as Kalim Shaikh and click on the Update link and see whether the data is updated or not.


In the above output diagram you can clearly see that now the Book_Author name is modified to
Kalim Shaikh.

See the following video on ASP.NET Tracing and instrumentation.



Visit for more ASP.NET interview questions.

Regards,

For more author's blog on ASP.NET interview questions