professional documents
home
Upload
docsters
Upload
Word Document

ASP.NET INTERVIEW QUESTIONS-ANSWERS center doc


ASP.NET What's the difference between a Placeholder and a Panel? Functionality-wise, both server controls are generally the same. They both act as containers, separating other server controls, etc., into logical sections. However, the Panel has a bit more overhead. A panel has most of the display/decoration/style capabilities of the other server controls (border style/width/color, BackColor, Font, CssClass, etc). The PlaceHolder control doesn't have most of those capabilities. It's major function is to act as a container for other tags/server controls. So, if you just want a container, without all the Display properties, use a PlaceHolder. If you want to use it to separate controls visually, then, the Panel is the control for you. What is the Difference between Server.Transfer and Response.Redirect ? Server.Transfer processes the page from one page directly to the next page without making a round-trip back to the client's browser. This way is faster, with a little less overhead on the server. However, it does NOT update the clients url history list or current url. Response.Redirect, as expected, is used to redirect the user's browser to another page or site. It DOES perform a trip back to the client where the client's browser is actually redirected to the new page. The browser history list IS updated to reflect the new address. How can I use the Session Object in my code behind (or Partial class)? In your ASPX pages, you can easily use the Session object, by just using: Session("Whatever")="Something" However to use it in your separated code pages (codebehind, partial class, function library, etc), it's necessary to use it this way: System.Web.HttpContext.Current.Session("Whatever")="Something" Why isn't my (ItemStyle/HeaderStyle) tag properties working correctly? Remember that a DataGrid generates an HTML Table, with TableRows and Cells. If you have ItemStyle/HeaderStyle/SelectedItem/FooterStyle tags with display properties (like forecolor/bold/font properties) and some of them are not displaying like you think they should, be sure to check your page for a StyleSheet. If you have a TD tag section in your page's stylesheet --whatever properties you set there will normally override whatever you add into your DataGrid's Item styles. How do I convert the text in a TextBox to Upper Case, as I type? In order to do this, as it's typed, you must add a Javascript attribute to the Textbox. In your Page_Load routine, assuming your text box's ID is 'TextBox1': TextBox1.attributes("onKeyUp")="this.value=this.value.toUpperCase();" Why isn't my ExecuteNonQuery updating my database? When editing/updating a database with OleDb -here are two things to make sure of: 1. Make sure the defining parameter (ie: Where uid=@uid) in the Where clause is actually getting populated 2. When using parameterized queries, OLEDB parameters are positional. Make sure the parameters are defined in the same order as they appear in the SQL update string. How can I set focus on an ASP.Net TextBox Control when the page loads? Two things: 1. Give your BODY Tag and ID and include 'Runat=Server' (like --) 2. In the Page_Load event: if not Page.IsPostBack then bdyMain.attributes("onload")="document.form1.TextBox1.focus();" end if How can I set focus on an ASP.Net TextBox Control when the page loads? Two things: 1. Give your BODY Tag and ID and include 'Runat=Server' (like --) 2. In the Page_Load event: if not Page.IsPostBack then bdyMain.attributes("onload")="document.form1.TextBox1.focus();" end if How can I loop through either all or certain types of controls on a page? You can loop through all or certain type of controls on ASP.NET Page using this code. Code will loop through also those controls that are contained in some other container that Form, Panel for example. Example of looping through all TextBoxes on Page. [C#] private void LoopTextBoxes (Control parent) { foreach (Control c in parent.Controls) { TextBox tb = c as TextBox; if (tb != null) //Do something with the TextBox if (c.HasControls()) LoopTextBoxes(c); } } And you can start the looping by calling: LoopTextBoxes(Page); How can I use Javascript to set focus in a particular ASP.Net text box? One of the 'gotchas' about inline coding is that, within a script tag, you can not have another script tag. On the surface that sounds reasonable. However, let's say, you have some conditional coding, in within that coding, you want to place focus in another textbox, using Javascript. Normally, you'd probably do something like this: response.write("") The problem occurs when ASP.Net reads that closing script tag. It reads it as the close of it's main Script tag. To get around this and not confuse ASP.Net, you can do it like this: response.Write("<" & "script>document.form1.txtLoanNum.focus();<" & "/script>") Why does text from a MultiLine TextBox display in only one line when I know there are Line feeds? When displaying the information contained in and/or saved in a database from a Multiline textbox, remember, it saves line feeds/carriage returns as just that -line feeds/carriage returns. A web browser does not recognize those characters --therefore, to display them as such, you must replace the characters with tags a web browser can understand, like
or

. In VB.Net, 'vbcrlf' is the equivalent of a LineFeed/CarriageReturn, so to display those correctly in a browser, before displaying them (lets call the string, 'sItem'), you need to do something like this: sItem=sItem.Replace(vbcrlf, "
") .Then, when sItem (a variable containing the saved data) is displayed, it will display correctly How can I disable a button to keep away multiple clicking? Here's the scenario -let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times. For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation -like this: Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True" That's all there is to it! Why am I getting an 'AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection' Error? If you are getting this error: 'AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection' Most likely, you are trying to implement paging in a DataGrid while binding the DataGrid with a DataReader. To fix this, instead of using a DataReader to bind data to the DataGrid, use a DataSet How do I select a specific item in a DropDownList? With a dropdown list -you can dynamically select items in the list with a sort of 'built-in' find routine. To select a certain item, based on the Value of the item in the list: DropDownList.SelectedIndex = DropDownList.Items.IndexOf(DropDownList.Items.FindByValue(YourValueHere)) To select a certain item, based on the Text of the item in the list: DropDownList.SelectedIndex = DropDownList.Items.IndexOf(DropDownList.Items.FindByText("YourTextHere")) OR -you can do it this way: DropDownList.Items.FindByText("TextYouAreLookingFor").Selected = true or, using the value of the item DropDownList.Items.FindByValue("ValueYouAreLookingFor").Selected = true How do I select a specific item in a ListBox? If you don't know the exact index number in the list of listbox items (listbox1.selectedindex=x), then you can find an item and select it by using the Value of the item: ListBox1.Items.FindByValue(MyValue).Selected = true If you don't know the Value of the item, but you know the text, you can find and select the item using the Text of the item: ListBox1.Items.FindByText("TextYouAreLookingFor").Selected = true Why won't my dropdownlist or listbox selected item remain set when the page posts back? When using DropdownLists and Listboxes, or any control which uses 'selecteditem.text' to get the selected item, the major reason for not getting the correct item is as follows. If you are binding the control at Page_load, you MUST surround the binding code with a page.ispostback/if/then statement. Something like this: if not Page.IsPostBack then 'do your databinding and/or list selection here end if Inside Page_load, you need to make sure that, when it posts back, the actual item selected is maintained.... The reasoning is as follows: If you have as specific item being selected during page_load -it will always be selected upon every subsequent page_load -the page_load sub is exactly that -it tells the page what to do when the page is loading. If you post back, based on a selection, you naturally, would not want this to happen -you only want it to happen the first time the page loads -not on a postback... SO --to get around this, you need to qualify whether or not the page is loading for the first time, or it's posting back. For further information, check out the tutorial on PostBack Where is the best place to store global Database connections? Let's say you have a database connection (or several) that you will be using over and over. Yes, you can manually copy/type it in on every ASP.Net page -BUT -an easier way is to store it in the Web.Config file (formerly config.web) and then refer to it in the code. In Web.Config, you would add a key to the AppSettings Section: for OleDb -use Absolute Path -Not Server.MapPath: Then, in your ASP.Net application -just refer to it like this: Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("MyDBConnection")) That's all there is to it! Sending Multiple Emails At Once (Mass Emailing -kind of) Just like setting up emailing from a form, in general, is not difficult, neither is sending emails to multiple people at the same time. First, we need to dimension a variable called 'MyVar': to hold all the email addresses in a string: Dim MyVar as String In inline coding, this would be placed inside the script tag, but outside any Sub or Function. Next we need to set up the BCC field, grabbing all the emails from a database field called (surprise!) 'email': Dim MySQL as string = "Select email from yourTableName" Dim MyConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("UrAppString")) Dim objDR as SQLDataReader Dim Cmd as New SQLCommand(MySQL, MyConn) MyConn.Open() objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection) MyVar="" While objDR.Read() MyVar+=objDR("email")& ";" End While MyVar=MyVar.substring(0,(MyVar.Length-1)) The last line merely removes the semi-colon from the end that will naturally be placed there due to the line inside the While section. You might want to check out another Tutorial here, called 'Emailing Form Results'. It goes over much of this next section also. Dim objEmail as New MailMessage objEmail.To="News@YourDomain.com" objEmail.FROM="You@YourDomain.com" objEmail.BCC=MyVar objEmail.SUBJECT="This is my Subject" objEmail.Body="Put text or a variable which represents the text -here" objEmail.BodyFormat = MailFormat.Text SmtpMail.SmtpServer ="mail.YourDomain.com" SmtpMail.Send(objEmail) The main sections that needs addressing here are the BCC field, the BODY field, and the TO field. For most, the TO field will be fairly trivial. You don't need any of the people in the email addresses for this one. I usually use a mail back to me, in order to be sure the email actually went out. In the BCC field, you see that the list of emails in the 'MyVar' variable goes here, without double quotes surrounding it, since it's a variable and not an explicit email address. The same goes for the BODY section. If you wanted to define a section of text, and assign it to a variable, before this block of code, then, you would merely put the variable name there, without double quotes. Naturally, the SMTP server is important, since that's the mail server which you assign to send the emails out. Hopefully, this takes a little mystery out of the whole 'sending multiple emails at the same time' scenario. The 3 'Execute' Command Methods (A Look at the different Execute Methods) Here, we're going to look at the most often used or needed methods of the command object (OleDbCommand or SQLCommand), their differences and how each one is used. They are the ExecuteReader, ExecuteNonQuery, and ExecuteScalar methods. Once you make a connection to your database and create a command, you're going to need one of these methods to execute the command. Simple Overview: • ExecuteReader -basically, this method returns a DataReader which is filled with the data that is retrieved using the command. This is known as a forward-only retrieval of records -it uses your sql statement to read through the table from the first to the last. There are many DataReader examples on this site. Just go to http://aspnet101.com/aspnet101/aspnetcode.aspx and choose DataReader from the DropDownList Useage: cmd.ExecuteReader • ExecuteNonQuery -this method returns no data at all. It is used mainly with Inserts and Updates of tables. Here, also, we have many code samples using ExecuteNonQuery. Inserting records Updating a Record Useage: cmd.ExecuteNonQuery • ExecuteScalar -Returns only one value after executing the query -it returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is needed. Useage: cmd.ExecuteScalar Understanding Regular Expressions (an Introduction to Regular Expressions and their Syntax) This tutorial is not meant to be an exhaustive one, but merely a 'look' at some of the syntax used in Regular Expressions, so that it will not look quite so 'foreign' to you, the next time you look at a Regular Expression inside the Regular Expression Validator in ASP.Net. The use of regular expressions is based on the contents of a string, matching criteria set in play by the assigned Regular Expression. It tests for a pattern within a string. For instance, let's say the string to search comes from a text box called 'Text1'. Let's say that the Regular Expression (matching characters) we are searching for is any lower case letter. The Regular Expression would be [a-z]. Therefore, the string returned from 'Text1.text' will be searched and matched against the Regular Expression. Regular Expressions in ASP.Net, used in Validator Server Controls are kind of like applying rules to the text input. If the Regular Expression above were put into a validator for 'Text1', then, since anything other than lower case letters would NOT match, if we put in the number 6, it would FAIL validation. On the otherhand, 'top' would PASS validation. At this point, we need to stop and discuss several characters (Metacharacters) we must come to understand when using Regular Expressions. Above, we saw two of them -the brackets ([])and the dash (-). First of all, we call any characters we use for search or matching, 'Literals'. The 'a' and the 'z' in the example above are 'Literals'. Next we come to the 'Metacharacter'. Metacharacters in the above example are the brackets and the dash. You can also use the caret (^)/(Shift-6). Also, we can use the dollar sign ($), the question mark (?), the asterisk (*), the plus sign (+), and the period (.). The meanings for these Metacharacters are described below. Metacharacter Meanings: The brackets denote searching for anything laid out inside the brackets. The dash is a 'range separator'. Instead of listing the entire lowercase alphabet, we can merely list a-z, as above, to show all the characters. Therefore, in this example, basically, using [a-z] for the regular expression would mean that we would search the text, and only match, lower case alphabetic characters. That brings up another anomaly about Regular Expressions -case sensitivity. Yes, Regular Expressions ARE case sensitive. This means that if we wanted any alphabetic character to be matched, we would need to put in [a-z], plus [A-Z]. Of course, we could put numeric ranges here, too, like '[0-9]' to match ONLY numeric characters. Another special identifier '\d' does the same thing -the 'd' stands for a digit character. The Caret (^)/(Shift-6), if it is INSIDE brackets will match anything BUT what is listed in the characters next to it -but -it 'negates' whatever is in the Regular Expression (like [^Aa] -this will match anything except the lower or upper case 'A'. However, if it is quite different when used outside brackets. Here, it will look for the characters next to it, and test them against only the BEGINNING of the string, but it looks for an exact match. For instance: '^Dav' will be found in the string 'David is here today', but it will not be matched in 'We're going to find David', since it's not at the beginning of the string. The dollar sign ($), as opposed to the Caret, will look at the END of the target string. For instance, '$fox' will find a match in 'silver fox' but not in 'the fox jumped over the log' The period (.) can be used like a wildcard. Anyone who has used databases should know a little about wildcards, hopefully. Let's say the Regular Expression was 'exp.' -It would match if it found 'expression', 'experience', or 'exponential'. The question mark (?) matches the preceding character 0 or 1 times The asterisk (*) matches the preceding character 0 or more times. It is also sort of like a wildcard. The plus sign (+) matches the previous character 1 or more times. If we need to use one of the metacharacters, literally, then we need an 'escape' character. In this case, we'd precede the metacharacter with a backwards slash mark (\). For instance, since the dash is a range separator, to include the dash itself in the character sequence, we'd have to do it like this: [\-] Two additional metacharacters are the parentheses and the vertical bar (|), sometimes called a pipe, in the Dos/Windows world. Parentheses can be used to group sections of the search expression together, while the pipe will have characters on the right and left of it, and it's used as an either/or type of search. For instance, gr(a|e)y will find 'gray' or 'grey'. What we've seen here is a hint or glimpse into the syntax of Regular Expressions. Hopefully, this will help you the next time you check out any of the Regular Expressions you encounter. This isn't all there is to know about Regular Expressions at all. In later tutorials, we will delve deeper into other characters and how to assemble Regular Expressions. In the mean time, if you would like to see a web site full of Regular Expressions, go to http://www.regexlib.com/. Intro to Parsing Strings (in ASP.Net, of course) There may come a situation where you have a string which needs to be broken up into parts for a particular reason. Learning how to do this is not the hardest thing to understand, but for someone just starting with ASP.Net, it may seem a little difficult. Let's say you have a string to manipulate that is someone's full name. However, your database is set up to have the first name and last name separate from one another. This is an example that requires parsing the string -separating the whole, separating it into multiple (in this case, two) parts. There are many ways this string may come into the page, but for this tutorial, let's say it is received with a queysrtring: myPage.aspx?fullname=John Hancock The first thing we need to do, is to convert the querystring data into a varaible, for ease of use, and create variables for the First and Last names: Dim sFullName as String Dim sFirst, sLast as String It would be best to make these 'global' variables, so they can be more easily reussed When using INLINE coding, to create a global variable, it needs to be dimensioned OUTSIDE any Sub or Function, but INSIDE the SCRIPT tags. In Code-Behind, you also create the variable OUTSIDE any Sub or Function. A variable is considered 'global' due to the fact that it can be used anywhere on the page, from the time it is populated. Otherwise, it is only available within the SUB or FUNCTION in which it is dimensioned. Then, in the Page_Load event (for this scenario), we populate the variable: sFullName = Request.Querystring("fullname") Now comes the fun part. There are two methods in the String class that you will probably use a lot -Substring and IndexOf. 'Substring' is rather self-explanatory, as is 'IndexOf'. Substring takes the string you give it and finds a 'sub' string inside it. 'IndexOf' is numerical and is used to find a location within a string, of a certain character or characters. In this case, we know the First and Last name in the string, are separated by a space, so we can use 'IndexOf' to find that space: Dim lgSpace as long lgSpace=myName.IndexOf(" ") Here, 'lgSpace' gets populated with the numerical 'Index' or position of the space between the First and Last Names. Now, what we need to do is use 'lgSpace' (the number returned from the above method), and 'Substring' to separate the First and Last names from the main string: sFirst=myName.Substring(0, lgSpace) sLast=myName.Substring(lgSpace) In the first line above, we are assigning the first 'Substring' of 'myName' to the 'sFirst' variable. There are two 'arguments' inside the parentheses for the Substring method. The '0' tells ASP.Net to start at the very beginning of the string, in order to look for the substring. Then, the second 'argument' is lgSpace -the postion inside the 'myName' variable where the space is.In the second line, we are assigning the first 'Substring' of 'myName' to the 'sLast' variable. Here, we don't need two arguments. We only need one, which is 'lgSpace'. This tells ASP.Net to start at that particular position in the 'myName' string/variable, and put everything from that point, until the end of the string, into the 'sLast' variable. Voila -that's all there is to it. We now have the First and Last name residing in two variables, sFirst and sLast. From that point, we can do anything we'd like with them, like inserting into a database, using one or both to search a database, or merely use it in other places inside that page. If you would like to see a more expanded look at how to parse strings, check out: Examining New String Properties -Part 1 and 2 DataGrid Tips and Tricks Here, you'll see one of the more complicated code samples on this site. Here, you'll see how to: 1. Use ReadyOnly BoundColumns with a DataGrid 2. Use a DropDownList in an Editable DataGrid 3. Control the size of a TextBox in an Editable DataGrid 4. Use the DataKeyField property of the DataGrid We'll also show how to, in the DropDownLists, select the correct item, based on the data retrieved from the database. For the DropDownList and the controled TextBox size, we use a TemplateColumn, inside of which we assign an ItemTemplate (for data when not in Edit Mode), and an EditItemTemplate. As you will see, in the ReadOnly Bouncdolumn, when the DataGrid goes into Edit Mode, a TextBox is NOT created, since we don't want this data editable. As you'll most likely notice, it's also not referenced in the SQL statement for that same fact. By assigning the DataKeyField property in the DataGrid, we are able to reference the exact record, when updating the table by using: dgCust.DataKeys(e.Item.ItemIndex)) in the ID parameter. C# 1. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and it’s datatype depends on whatever variable we’re changing. 2. How do you inherit from a class in C#? Place a colon and then the name of the base class. 3. Does C# support multiple inheritance? No, use interfaces instead. 4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace. 5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are. 6. Describe the accessibility modifier protected internal. It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in). 7. 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? 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. 8. What’s the top .NET class that everything is derived from? System.Object. 9. How’s method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. 10. What does the keyword virtual mean in the method definition? The method can be over-ridden. 11. Can you declare the override method static while the original method is non-static? No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override. 12. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access. 13. Can you prevent your class from being inherited and becoming a base class for some other classes? 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. 14. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed. 15. What’s an abstract class? 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. 16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? 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. 17. What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes. 18. Why can’t you specify the accessibility modifier for methods inside the interface? 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. 19. Can you inherit multiple interfaces? Yes, why not. 20. And if they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay. 21. What’s the difference between an interface and abstract class? 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. 22. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters. 23. 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? 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. 24. What’s the difference between System.String and System.StringBuilder classes? System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. 25. Is it namespace class or class namespace? The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.

flag this doc
3512
241
1(3)
0
2/13/2008
English
Preview

Interview Questions and Answers

Richard_Cataman 9/10/2008 | 771 | 35 | 0 | business
Preview

Interview Questions and Answers

Richard_Cataman 9/3/2008 | 518 | 41 | 0 | business
Preview

common interview Q&A

David77 4/15/2008 | 1313 | 182 | 0 | business
Preview

Interview Questions Answers

MaryJeanMenintigar 9/12/2008 | 239 | 16 | 0 | business
Preview

Interview Answers

MaryJeanMenintigar 9/12/2008 | 154 | 12 | 0 | business
Preview

Interview Answers

PastorGallo 8/26/2008 | 266 | 33 | 0 | business
Preview

Free Interview Answers

PastorGallo 9/11/2008 | 180 | 7 | 0 | business
Preview

Job Interview Questions And Answers

Richard_Cataman 9/12/2008 | 112 | 3 | 0 | business
Preview

Interview Questions

PastorGallo 8/26/2008 | 318 | 19 | 0 | business
Preview

Interview Questions

Ben_Longjas 9/29/2008 | 128 | 2 | 0 | business
Preview

Interview Questions

PastorGallo 9/13/2008 | 440 | 9 | 0 | business
Preview

Interview Questions

Richard_Cataman 9/3/2008 | 133 | 7 | 0 | technology
Preview

Good Interview Questions

MaryJeanMenintigar 9/12/2008 | 330 | 12 | 0 | business
Preview

Interview Question

Richard_Cataman 9/13/2008 | 289 | 5 | 0 | business
Preview

job interview questions

MaryJeanMenintigar 8/6/2008 | 403 | 25 | 0 | business
 
review this doc