Friday 30 March 2012

var keyword in dotnet

Why var keyword is used and when it is the only way to get query result?
var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalised keyword. The compiler infers the actual type from the static type of the expression used to initialise the variable. One must use var with the query that returns anonymous type. E.g. 
// anonymous type returned
var query = from w in words
            select new
                {
                    LetterCount = w.Length,
                    UpperString = w.ToUpper()
                };

foreach (var item in query)
{
    Console.WriteLine(item.LetterCount + " " + item.UpperString);
}

What Is LINQ?

LINQ is a uniform programming model for any kind of data access. LINQ enables you to query and manipulate data independently of data sources. Below figure 'LINQ' shows how .NET language stands over LINQ programming model and works in a uniformed manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.
LINQ can serve as a good entity for middle tier. So it will sit in between the UI and data access layer.
 


Figure - LINQ



Below is a simple sample of LINQ. We have a collection of data ‘objcountries’ to which LINQ will is making a query with country name ‘India’. The collection ‘objcountries’ can be any data source dataset, datareader, XML etc. Below figure ‘LINQ code snippet’ shows how the ‘ObjCountries’ can be any can of data. We then query for the ‘CountryCode’ and loop through the same.


Figure: - LINQ code snippet

What is the difference between the Select clause and SelectMany() method in LINQ?

What is the difference between the Select clause and SelectMany() method in LINQ?
Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, theSelectMany() method produces a single result that contains a concatenated collection from the query.

What is a LinqDataSource

What is a LinqDataSource control?
The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource andObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, theLinqDataSource control is designed to bind a LINQ enabled data model.

What is Object Relational Designer (0/R Designer)?

What is Object Relational Designer (0/R Designer)?
The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.

What is the DataContext class and how is it related to LINQ?

What is the DataContext class and how is it related to LINQ?
After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.

Write the basic syntax of a LINQ query in Visual Basic as well as in C#

Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

Pros and cons of LINQ

Pros and cons of LINQ (Language-Integrated Query) 

Pros of LINQ:
  • Supports type safety
  • Supports abstraction and hence allows developers to extend features such as multi threading.
  • Easier to deploy
  • Simpler and easier to learn
  • Allows for debugging through .NET debugger.
  • Support for multiple databases
Cons of LINQ:
  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries
  • LINQ is generic, whereas stored procedures etc can take full advantage of database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed.

What are the four LINQ Providers that .NET Framework ships?

What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.

Linq Interview Question

What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers

How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.

How are Standard Query Operators useful in LINQ?
Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results


List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions

dll

DLL stands for Dynamic Link Library. In short Windows based programs needs codes, functions and other resources to run properly. DLL provides those codes to programs. Therefore DLL is an executable file that is necessary to run programs in Windows environment.
It is not necessary that DLL should have .dll extension only. It also comes with .exe extension. But generally the file extension is .dll. Ntoskernl.dll, hal.dll, rpcrt4.dll, ntdll.dll are some most popular dll files which are necessary to run your OS properly. On the other hand dll files with .exe extensions are Kernel.exe, User.exe and Gdi.exe

The main advantage of using dll file is it reduces the duplication of code (which should have happened when multiple programs use same code). It also helps in increasing the performance of programs running in foreground and background.
Also DLL update is easily deplyed in Windows environment. It means whenever DLL file gets updated, there is no need of update of those programs which uses DLL files. There is no need of upation or relink of program whenever DLL is updated or deployed.
So these are the basic things you should know about DLL. There are many other DLL files and functions about which we’ll talk in next articles. If you have any queries about DLL files then you can ask them in the comments section.

In .Netframework how CLR(Commom language runtime) has work???

In .Netframework how CLR(Commom language runtime) has work???


1st--- CLS (common language specification) 
2nd-- CTS (common type system) 
cts will check line by line typesafty checking. 
3rd-- JIT (just in time) JIT will change the code into MSIL 
4th-- MSIL (Microsoft Intermidiate language) MSIL will change the code in .exe 

and we run the .exe files....

What is the command name to shrink the data file and log file size in SQL server 2005

What is the command name to shrink the data file and log file size in SQL server 2005

The command name is : DBCC SHRINKDATABASE (Database Name) 

This command will shrink the data file and log file size. With this command you can specify that how much percentage space you want to free. 


How can we find the open transactions details in sql server

How can we find the open transactions details in sql server

 

Yes, it is possible. 

select * from sysprocesses where open_tran > 0

 

What is the difference between First() and Single() extension methods in LINQ

First() - There is at least one result, an exception is thrown if no result is returned. 

Single() - There is exactly 1 result, no more, no less, an exception is thrown if no result is returned.

What is the difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ

FirstOrDefault() = gets the first item that matches a given criteria. 

SingleOrDefault() = if you specify this extension method that means you are specifically saying that there can be only one value that matches the criteria. If there are more then 1 value that matches the criteria, throw an exception.

What is Smart Navigation ?

 What is Smart Navigation ?
Ans : Is the attribute of the page tag which allows the browser to sections of the form that have changed. The advantage of Smart Navigation is that the screen does not flash as it updated, instead, the scroll postion is maintained and the “last page” in the history is maintained. It is only availabe to the users with Microsoft Internet Explorer 5 or later.

What is SQL Server Agent

It plays an important role in the tasks of Database Administrator(DBA). 
Its purpose is to ease the implementation of tasks for the DBA. 
Using its full- function scheduling engine, you can schedule your own jobs and scripts

The 3 ways to get an accurate count of the number of records in a table are as below

The 3 ways to get an accurate count of the number of records in a table are as below: 

1) SELECT * FROM table1 

2) SELECT COUNT(*) FROM table1 

3) SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

What is the difference between Response.Write() and Response.Output.Write()

Both the commands are used to display the output on the screen. 

Response.Write() is used to display a single line output. 

Response.Output.Write() is used to display a formatable output. 

Example: 
Response.Write("Hi");



Response.Output.Write("x={0},y={1},x,y");

What are different methods of session maintenance in ASP.NET?

What are different methods of session maintenance in ASP.NET?
Three types of session maintenance:
In-process storage.
Session State Service.
Microsoft SQL Server.

Regular expression for validating the IP Address using Javascript?

Regular expression for validating the IP Address using Javascript?
[JavaScript]
function isValidIPAddress(ipaddr) {
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
if (re.test(ipaddr)) {
var parts = ipaddr.split(".");
if (parseInt(parseFloat(parts[0])) == 0) { return false; }
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts[i])) > 255) { return false; }
}
return true;
} else {
return false;
}
}

How to get distinct values from an array in C#?

How to get distinct values from an array in C#?
[C#]

public int[] GetDistinctValues(int[] arr)
{
List<int> lst = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (lst.Contains(arr[i]))
continue;
lst.Add(arr[i]);
}
return lst.ToArray();
}

Which DLL translate XML

Which DLL translate XML to SQL in IIS?
Sqlisapi.dll

Which dll is required to translate XML to SQL in IIS ?
Microsoft.data.sqlxml.dll

What is the base class of .NET?
System.Object is the base class of .NET.

Name Spaces Available in .NET Framework 4:

System
System.Activities Namespaces
System.AddIn Namespaces
System.CodeDom Namespaces
System.Collections Namespaces
System.ComponentModel Namespaces
System.Configuration Namespaces
System.Data Namespaces
System.Deployment Namespaces
System.Device.Location
System.Diagnostics Namespaces
System.DirectoryServices Namespaces
System.Drawing Namespaces
System.Dynamic
System.EnterpriseServices Namespaces
System.Globalization
System.IdentityModel Namespaces
System.IO Namespaces
System.Linq Namespaces
System.Management Namespaces
System.Media
System.Messaging Namespaces
System.Net Namespaces
System.Numerics
System.Printing Namespaces
System.Reflection Namespaces
System.Resources Namespaces
System.Runtime Namespaces
System.Security Namespaces
System.ServiceModel Namespaces
System.ServiceProcess Namespaces
System.Speech Namespaces
System.Text Namespaces
System.Threading Namespaces
System.Timers
System.Transactions Namespaces
System.Web Namespaces
System.Windows Namespaces
System.Workflow Namespaces
System.Xaml Namespaces
System.Xml Namespaces
Accessibility
Microsoft.Aspnet.Snapin
Microsoft.Build Namespaces
Microsoft.CSharp Namespaces
Microsoft.Data.Entity.Build.Tasks
Microsoft.JScript Namespaces
Microsoft.SqlServer.Server
Microsoft.VisualBasic Namespaces
Microsoft.VisualC Namespaces
Microsoft.Win32 Namespaces
Microsoft.Windows.Themes
UIAutomationClientsideProviders
XamlGeneratedNamespace

What is the Pre-Compilation feature of ASP.NET 2.0?

What is the Pre-Compilation feature of ASP.NET 2.0?

Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users.

There is a pre-defined folder structure for enabling the pre-compilation feature:

* App_Code: stores classes
* App_Themes: stores CSS files, Images, etc.
* App_Data: stores XML files, Text Files, etc.
* App_GlobalResources: stores all the resources at global level E.g. resx files, etc
* App_LocalResources: stores all the resources at local/Page level

How does .NET remoting work?

How does .NET remoting work?

.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).

Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.

There are a number of styles of remote access:

SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.
Singleton. All incoming requests from clients are processed by a single server object.
Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.

Distributed garbage collection of objects is managed by a system called ''leased based lifetime''. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.

Jump statement in C#

Jump statement in C#
break, continue, goto, return, throw

Difference between convert.tostring() and .tostring()

Difference between convert.tostring() and .tostring()
convert.tostring() supports null whereas .tostring() will not support null

How to assign width to label/button/textbox in vb.net ?

How to assign width to label/button/textbox in vb.net ?



With some scenarios you need to assign width to the controls rubtime. Generally we tend to make it soecified with percentage. At runtime we can use following way to make such assignments.

Label1.Width = Unit.Percentage(12.12)


You can have “pixel” or “point” as measurement unit and get your desired result set.

Sorting in data structure

Comparison of algorithms

In this table, n is the number of records to be sorted. The columns "Average" and "Worst" give the time complexity in each case, under the assumption that the length of each key is constant, and that therefore all comparisons, swaps, and other needed operations can proceed in constant time. "Memory" denotes the amount of auxiliary storage needed beyond that used by the list itself, under the same assumption. These are all comparison sorts. The run time and the memory of algorithms could be measured using various notations like theta, omega, Big-O, small-o, etc. The memory and the run times below are applicable for all the 5 notations.
Comparison sorts
Name Best Average Worst Memory Stable Method Other notes
Quicksort \mathcal{} n \log n \mathcal{} n \log n \mathcal{} n^2 \mathcal{} \log n Depends Partitioning Quicksort is usually done in place with O(log(n)) stack space.[citation needed] Most implementations are unstable, as stable in-place partitioning is more complex. Naïve variants use an O(n) space array to store the partition.[citation needed]
Merge sort \mathcal{} {n \log n} \mathcal{} {n \log n} \mathcal{} {n \log n} Depends; worst case is  \mathcal{} n Yes Merging Used to sort this table in Firefox [2].
In-place Merge sort  \mathcal{} -  \mathcal{} -  \mathcal{} {n \left( \log n \right)^2}  \mathcal{} {1} Yes Merging Implemented in Standard Template Library (STL): [3]; can be implemented as a stable sort based on stable in-place merging: [4]
Heapsort \mathcal{} {n \log n} \mathcal{} {n \log n} \mathcal{} {n \log n} \mathcal{} {1} No Selection
Insertion sort  \mathcal{} n  \mathcal{} n^2  \mathcal{} n^2  \mathcal{} {1} Yes Insertion O(n + d), where d is the number of inversions
Introsort \mathcal{} n \log n \mathcal{} n \log n \mathcal{} n \log n \mathcal{} \log n No Partitioning & Selection Used in SGI STL implementations
Selection sort  \mathcal{} n^2  \mathcal{} n^2  \mathcal{} n^2  \mathcal{} {1} No Selection Stable with O(n) extra space, for example using lists [5]. Used to sort this table in Safari or other Webkit web browser [6].
Timsort  \mathcal{} {n}  \mathcal{} {n \log n}  \mathcal{} {n \log n}  \mathcal{} n Yes Insertion & Merging \mathcal{} {n} comparisons when the data is already sorted or reverse sorted.
Shell sort \mathcal{} n \mathcal{} n (\log n)^2

or

\mathcal{} n^{3/2}
Depends on gap sequence; best known is \mathcal{} n (\log n)^2 \mathcal{} 1 No Insertion
Bubble sort \mathcal{} n \mathcal{} n^2 \mathcal{} n^2 \mathcal{} {1} Yes Exchanging Tiny code size
Binary tree sort \mathcal{} n \mathcal{} {n \log n} \mathcal{} {n \log n} \mathcal{} n Yes Insertion When using a self-balancing binary search tree
Cycle sort  \mathcal{} n^2  \mathcal{} n^2 \mathcal{} {1} No Insertion In-place with theoretically optimal number of writes
Library sort  \mathcal{} {n \log n}  \mathcal{} n^2  \mathcal{} n Yes Insertion
Patience sorting \mathcal{} n \log n \mathcal{} n No Insertion & Selection Finds all the longest increasing subsequences within O(n log n)
Smoothsort \mathcal{} {n} \mathcal{} {n \log n} \mathcal{} {n \log n} \mathcal{} {1} No Selection An adaptive sort - \mathcal{} {n} comparisons when the data is already sorted, and 0 swaps.
Strand sort \mathcal{} n \mathcal{} n^2 \mathcal{} n^2 \mathcal{} n Yes Selection
Tournament sort \mathcal{} n \log n \mathcal{} n \log n

Selection
Cocktail sort \mathcal{} n \mathcal{} n^2  \mathcal{} n^2 \mathcal{} {1} Yes Exchanging
Comb sort \mathcal{} n \mathcal{} n \log n  \mathcal{} n^2  \mathcal{} {1} No Exchanging Small code size
Gnome sort  \mathcal{} n  \mathcal{} n^2  \mathcal{} n^2  \mathcal{} {1} Yes Exchanging Tiny code size
Bogosort  \mathcal{} n  \mathcal{} n \cdot n!  \mathcal{} {n \cdot n! \to \infty}  \mathcal{} {1} No Luck Randomly permute the array and check if sorted.
Slowsort  \Omega\left(n^{ \frac{\log_2(n)}{(2+\epsilon)}}\right) No Selection Remarkably inefficient sorting algorithm [7]
The following table describes integer sorting algorithms and other sorting algorithms that are not comparison sorts. As such, they are not limited by a \Omega\left( {n \log n} \right) lower bound. Complexities below are in terms of n, the number of items to be sorted, k, the size of each key, and d, the digit size used by the implementation. Many of them are based on the assumption that the key size is large enough that all entries have unique key values, and hence that n << 2k, where << means "much less than."
Non-comparison sorts
Name Best Average Worst Memory Stable n << 2k Notes
Pigeonhole sort \;n + 2^k \;n + 2^k \;2^k Yes Yes
Bucket sort (uniform keys) \;n+k \;n^2 \cdot k \;n \cdot k Yes No Assumes uniform distribution of elements from the domain in the array.[2]
Bucket sort (integer keys) \;n+r \;n+r \;n+r Yes Yes r is the range of numbers to be sorted. If r = \mathcal{O}\left( {n} \right) then Avg RT = \mathcal{O}\left( {n} \right)[3]
Counting sort \;n+r \;n+r \;n+r Yes Yes r is the range of numbers to be sorted. If r = \mathcal{O}\left( {n} \right) then Avg RT = \mathcal{O}\left( {n} \right)[2]
LSD Radix Sort \;n \cdot \frac{k}{d} \;n \cdot \frac{k}{d} \mathcal{} n Yes No [3][2]
MSD Radix Sort \;n \cdot \frac{k}{d} \;n \cdot \frac{k}{d} \mathcal{} n + \frac{k}{d} \cdot 2^d Yes No Stable version uses an external array of size n to hold all of the bins
MSD Radix Sort \;n \cdot \frac{k}{d} \;n \cdot \frac{k}{d} \frac{k}{d} \cdot 2^d No No In-Place. k / d recursion levels, 2d for count array
Spreadsort \;n \cdot \frac{k}{d} \;n \cdot \left( {\frac{k}{s} + d} \right) \;\frac{k}{d} \cdot 2^d No No Asymptotics are based on the assumption that n << 2k, but the algorithm does not require this.
The following table describes some sorting algorithms that are impractical for real-life use due to extremely poor performance or a requirement for specialized hardware.
Name Best Average Worst Memory Stable Comparison Other notes
Bead sort N/A N/A N/A No Requires specialized hardware
Simple pancake sort \mathcal{} n \mathcal{} n \mathcal{} {\log n} No Yes Count is number of flips.
Spaghetti (Poll) sort \mathcal{} n \mathcal{} n \mathcal{} n \mathcal{} n^2 Yes Polling This A linear-time, analog algorithm for sorting a sequence of items, requiring O(n) stack space, and the sort is stable. This requires n parallel processors. Spaghetti sort#Analysis
Sorting networks \mathcal{} {\log n} \mathcal{} {\log n} \mathcal{} {n \cdot \log (n)} Yes No Requires a custom circuit of size \mathcal{O}\left( n \cdot \log (n) \right)
Additionally, theoretical computer scientists have detailed other sorting algorithms that provide better than \mathcal{O}\left( {n \log n} \right) time complexity with additional constraints, including:
  • Han's algorithm, a deterministic algorithm for sorting keys from a domain of finite size, taking \mathcal{O}\left( {n \log \log n} \right) time and \mathcal{O}\left( {n} \right) space.[4]
  • Thorup's algorithm, a randomized algorithm for sorting keys from a domain of finite size, taking \mathcal{O}\left( {n \log \log n} \right) time and \mathcal{O}\left( {n} \right) space.[5]
  • An integer sorting algorithm taking \mathcal{O}\left( {n \sqrt{\log \log n}} \right) expected time and \mathcal{O}\left( {n} \right) space