Interview Tips Interview Tips, Interview Questions and Answers

13Sep/110

Filtering Data in Web Forms Model Binding

To enable filtering, we’ll update our GetProducts() method to take a keyword parameter like below:

public IQueryable<Product> GetProducts([QueryString]string keyword)

{

    IQueryable<Product> query = db.Products;

 

    if (!String.IsNullOrWhiteSpace(keyword))

    {

        query = query.Where(p => p.ProductName.Contains(keyword));

    }

 

    return query;

}

If the keyword is empty or null, then the method returns all of the products in the database.  If a keyword is specified then we further filter the query results to only include those product’s whose names contain the keyword.

Understanding Value Providers

One of the things you might have noticed with the code above is the [QueryString] attribute that we’ve applied to the keyword method argument.  This instructs the Model Binding system to attempt to “bind” a value from the query string to this parameter at runtime, including doing any type conversion required.

These sources of user values are called “Value Providers”, and the parameter attributes used to instruct the Model Binding system which Value Provider to use are called “Value Provider Attributes”. The next version of Web Forms will ship with value providers and corresponding attributes for all the common sources of user input in a Web Forms application, e.g. query string, cookies, form values, controls, viewstate, session and profile. You can also write your own custom value providers.  The value providers you write can be authored to work in both Web Forms and MVC.

By default, the parameter name will be used as the key in the value provider collection, so in this case, a value will be looked for in the query string with the key “keyword”, e.g. ~/Products.aspx?keyword=chef. This can be easily overridden by passing the desired key in as an argument to the parameter attribute. In our example, we might like the user to be able to use the common “q” query string key for specifying the keyword:

public IQueryable<Product> GetProducts([QueryString("q")]string keyword)

24May/110

Events and Delegates in c#

1. What’s a delegate?
A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

3. 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.

4. How do you inherit from a class in C#?
Place a colon and then the name of the base class.

5. Does C# support multiple inheritance?
No, use interfaces instead.

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

7. 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.

8. 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).

9. 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.

10. What’s the top .NET class that everything is derived from?
System.Object.

25Sep/100

COM Interop in c# 4.0

// Code simplified for this example
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;

object foo = "MyFile.txt";
object bar = Missing.Value;
object optional = Missing.Value;

Document doc = (Document)Application.GetDocument(ref foo, ref bar, ref optional);
doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional);

There are (at least) three problems with the code above. First, you have to declare all your variables as objects and pass them with the ref keyword. Second, you can't omit parameters and must also pass the Missing.Value even if you are not using the parameter. And third, behind the scenes, you are using huge (in file size) interop assemblies just to make one method call.

C# 4.0 will allow you to write the code above in a much simpler form that ends up looking almost exactly like 'normal' C# code. This is accomplished by using some of the features already discussed; namely dynamic support and optional parameters.

// Again, simplified for example.
using Microsoft.Office.Interop.Word;

var doc = Application.GetDocument("MyFile.txt");
doc.CheckSpelling();

18Jun/100

Cookies with More Than One Value in asp.net

You can store one value in a cookie, such as user name or last visit. You can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as subkeys.  For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.

You might use subkeys for several reasons. First, it is convenient to put related or similar information into a single cookie. In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information.

A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the "Cookie Limitations" section, cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

To create a cookie with subkeys, you can use a variation of the syntax for writing a single cookie. The following example shows two ways to write the same cookie, each with two subkeys:
Response.Cookies["userInfo"]["userName"] = "patrick";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

17Jun/100

Writing Cookies in asp.net

The browser manages cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

You can also set a cookie's date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now.

Note: Users can clear the cookies on their computer at any time. Utilities such as CCleaner ("crap cleaner") allow you to set the cookies you want to keep, and delete all the rest.

If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained in memory as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.

18Mar/100

asp.net interview questions and answers

How do we do paging in gridview?
Make Allowpaging=true also specify the PageIndex as some value

Namespace and Assembly?
Namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

Diff b/w dataset.clone and dataset.copy
dataset.clone copies just the structure of dataset (including all the datatables, schemas, relations and constraints.); however it doesn’t copy the data. On the other hand dataset.copy, copies both the dataset structure and the data.

Diff b/w Const and readonly?
A const can not be static, while readonly can be static.

A const need to be declared and initialized at declaration only, while a readonly can be initialized at declaration or by the code in the constructor.

A const’s value is evaluated at design time, while a readonly’s value is evaluated at runtime.

Diversities between static or dynamic assemblies ?
Assemblies can be static or dynamic.

Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on).

Static assemblies are stored on disk in portable executable (PE) files.

You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution.You can save dynamic assemblies to disk after they have executed.

How can you show the number of visitors of your app
By havving an application variable and Incrementing it in every session start.
TO Achieve it use the Global.asax file's Application_Start and Session_Start Events.

28Feb/100

C# interview questions with answers

What are the different method parameter modifiers in C#?
out
ref
params

What are the different Iteration Constructs in C#?
for loop
foreach/in loop
while loop
do/while loop

What is the use of ?? operator in C#?
This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.

What is the CIL representation of implicit and explicit keywords in C#?
The CIL representation is op_Implicit and op_Explicit respectively.

Which operators in C# provides automatic detection of arithmetic overflow and underflow conditions?
'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow and underflow conditions.

What is the use of stackalloc keyword in C#?
In an unsafe context it is used to allocate C# array directly on the stack.

Which keyword in C# is used to temporarily fix a variable so that its address may be found?
fixed keyword

What are the different C# preprocessor directives?
#region , #endregion :- Used to mark sections of code that can be collapsed.

#define , #undef :-Used to define and undefine conditional compilation symbols.

#if , #elif , #else , #endif :- These are used to conditionally skip sections of source code.

What is the use of GetInvocationList() in C# delegates?
GetInvocationList() returns an array of System.Delegate types, each representing a particular method that may be invoked.

C# delegate keyword is derived form which namespace?
C# delegate keyword is derived form System.MulticastDelegate.

What will be the length of string type variable which is just declared but not assigned any value?
As variable is not initialized and it is of reference type. So it's length will be null and it will throw a run time exception of "System.NullReferenceException" type, if used.