Tuesday, 27 November 2012

Aarrlist , List and array basic details.

 
 
 
 
A ArrayList or List object is a sophisticated version of an array. The ArrayList class and the List generic class provide some features that are offered in most System.Collections classes but that are not in the Array class. For example:
  • The capacity of an Array is fixed, whereas the capacity of an ArrayList or a List is automatically expanded as required. If the value of the ArrayListCapacity property is changed, the memory reallocation and copying of elements are automatically done.
  • ArrayList and List provide methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time.
  • A synchronized version of ArrayList is easy to create by using the Synchronized method; however, this type of synchronization is relatively inefficient. The Array and List classes leaves it up to the user to implement synchronization. The System.Collections.Concurrent namespace does not provide a concurrent list type, but it does provide a ConcurrentQueue and ConcurrentStack type.
  • ArrayList and List provide methods that return read-only and fixed-size wrappers to the collection. Array does not.
On the other hand, Array offers some flexibility that ArrayList and List do not. For example:
  • You can set the lower bound of an Array, but the lower bound of an ArrayList or a List is always zero.
  • An Array can have multiple dimensions, but an ArrayList or a List always has exactly one dimension. However, you can easily create a list of arrays or a list of lists.
  • An Array of a specific type (other than Object) provides better performance than an ArrayList. This is because the elements of ArrayList are of type Object; therefore, boxing and unboxing typically occur when you store or retrieve a value type. However, a List can provide performance similar to an array of the same type if no reallocations are required; that is, if the initial capacity is a good approximation of the maximum size of the list.
Most situations that call for an array can use an ArrayList or a List instead; they are easier to use and, in general, have performance similar to an array of the same type.
Array is in the System namespace; ArrayList is in the System.Collections namespace; List is in the System.Collections.Generic namespace.


Difference between array and Arraylist..
ARRAY
ARRAYLIST
1.
Char[] vowel=new Char[];
ArrayList a_list=new ArrayList();
2.
Array is in the System namespace
ArrayList is in the System.Collections namespace.
3.
The capacity of an Array is fixed
ArrayList can increase and decrease size dynamically
4.
An Array is a collection of similar items
ArrayList can hold item of different types
5.
An Array can have multiple dimensions
ArrayList always has exactly one dimension


 
Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions
Serializer
Xml Serializer
Data Contract Serializer
Dynamically Add Meta tags to Aspx Page in Asp.net using C#


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1"runat="server">
<div>
<b>Mukramjah.blogspot.in</b>
</div>
</form>
</body>
</html>

Add the  following name space references
using System;
using System.Web.UI.HtmlControls;
In the page load event add the following code.
 
protected void Page_Load(object sender, EventArgs e)
{
// set page title
Page.Title = "Add meta tags dynamically to aspx page in asp.net";
//Page description
HtmlMeta pagedesc = newHtmlMeta();
pagedesc.Name = "Description";
pagedesc.Content =
"Mukramjah.blogspot.in";
Header.Controls.Add(pagedesc);
//page keywords
HtmlMeta pagekeywords = newHtmlMeta();
pagekeywords.Name = "keywords";
pagekeywords.Content = "online material";
Header.Controls.Add(pagekeywords);
}
 
 
Now run the application
If you observe in design metadata tage is added dynamically with attributes.
 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head><metadata name="Description" content="Mukramjah.blogspot.in"/>
<metadata name="keywords" content=""online material"/>
<body>
<form id="form1"runat="server">
<div>
<b>Mukramjah.blogspot.in</b>
</div>
</form>
</body>
</html>

Monday, 19 November 2012

Difference between HTTP and HTTPS Protocols                                                                    
                                            
Hypertext Transfer Protocol Secure (HTTPS) is a combination of the Hypertext Transfer Protocol with the SSL/TLS protocol to provide encrypted communication and secure identification of a network web server. HTTPS connections are often used for payment transactions on the World Wide Web and for sensitive transactions in corporate information systems. HTTPS should not be confused with Secure HTTP (S-HTTP) specified in RFC 2660.



The main idea of HTTPS is to create a secure channel over an insecure network. This ensures reasonable protection from eavesdroppers and man-in-the-middle attacks, provided that adequate cipher suites are used and that the server certificate is verified and trusted.


As opposed to HTTP URLs which begin with "http://" and use port 80 by default, HTTPS URLs begin with "https://" and use port 443 by default.



HTTP operates at the highest layer of the OSI Model, the Application layer; but the security protocol operates at a lower sublayer, encrypting an HTTP message prior to transmission and decrypting a message upon arrival. Strictly speaking, HTTPS is not a separate protocol, but refers to use of ordinary HTTP over an encrypted Secure Sockets Layer (SSL) or Transport Layer Security (TLS) connection.

Wednesday, 14 November 2012

Web Application Projects versus Web Site Projects

.NET Framework 4
 

In Visual Studio you can create Web application projects or Web site projects. Each type of project has advantages and disadvantages, and it is helpful to understand the differences between them in order to select the best project type for your needs. You must select the appropriate project type before you create a project, because it is not practical to convert from one project type to the other.
NoteNote
For some scenarios you do not have a choice. For example, if you want to create an ASP.NET MVC application, you must use a Web application project.
This topic contains the following sections:
Scenarios in which Web application projects are the preferred choice include the following:
  • You want to be able to use the Edit and Continue feature of the Visual Studio debugger.
  • You want to run unit tests on code that is in the class files that are associated with ASP.NET pages.
  • You want to refer to the classes that are associated with pages and user controls from standalone classes.
  • You want to establish project dependencies between multiple Web projects.
  • You want the compiler to create a single assembly for the entire site.
  • You want control over the assembly name and version number that is generated for the site.
  • You want to use MSBuild or Team Build to compile the project. For example, you might want to add pre-build and post-build steps.
  • You want to avoid putting source code on a production server.
  • You want to use the automated deployment tools that are available in Visual Studio 2010.
Scenarios in which Web site projects are the preferred choice include the following:
  • You want to include both C# and Visual Basic code in a single Web project. (By default, a Web application is compiled based on language settings in the project file. Exceptions can be made, but it is relatively difficult.)
  • You want to open the production site in Visual Studio and update it in real time by using FTP.
  • You do not want to have to explicitly compile the project in order to deploy it.
  • If you do precompile the site, you want the compiler to create multiple assemblies for the site, which can include one assembly per page or user control, or one or more assemblies per folder.
  • You want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.
  • If you precompile the site, you want to be able to update individual ASP.NET Web pages (.aspx files) without having to recompile the entire Web site.
  • You like to keep your source code on the production server because it can serve as an additional backup copy.
The following table summarizes the main differences.
AreaWeb application projectsWeb site projects
Project file structureA Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
Compilation
  • You explicitly compile the source code on the computer that is used for development or source control.
  • By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
  • The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.
    You can precompile the site (compile in advance on a development computer or on the server).
  • By default, compilation produces multiple assemblies.
NamespacesExplicit namespaces are added to pages, controls, and classes by default.Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.
Deployment
  • You copy the assembly to a server. The assembly is produced by compiling the application.
  • Visual Studio provides tools that integrate with the IIS Web deployment tool to automate many deployment tasks.
  • You copy the application source files to a computer that has IIS installed on it.
  • If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server.
  • Visual Studio provides tools for deployment, but they do not automate as many deployment tasks as the tools available for Web application projects.
Web application projects use Visual Studio project files (.csproj or .vbproj) to keep track of information about the project. Among other tasks, this makes it possible to specify which files are included in or excluded from the project, and therefore which files are compiled during a build.
For Web site projects, all files in a folder structure are automatically considered to be included in the Web site. If you want to exclude something from compilation, you must remove the file from the Web site project folder or change its file-name extension to an extension that is not compiled and is not served by IIS.
An advantage of using project files in Web application projects is the following:
  • It is easy to temporarily remove files from the site but still make sure that you do not lose track of them, because they remain in the folder structure. For example, if a page is not ready to be deployed, you can temporarily exclude it from the build without deleting it from the folder structure. You can deploy the compiled assembly, and then include the file in the project again. This is especially important if you are working with a source control repository.
An advantage of using folder structure without project files in Web site projects is the following:
  • You do not have to manage the project's structure exclusively in Visual Studio. For example, you can copy files into the project or delete them from the project by using Windows Explorer.
For Web application projects, you typically build the project in Visual Studio or by using the ASP.NET batch compiler on a computer that is not the production IIS server. All code-behind class files and standalone class files in the project are compiled into a single assembly, which is then put in the Web application project's Bin folder. (The .aspx and .ascx files are compiled dynamically in a manner similar to what is done for Web site projects.)
For Web site projects, you do not have to manually compile the project. Web site projects are typically compiled dynamically by ASP.NET (on both the development computer and the production IIS server). You can choose between batch compilation mode, which typically produces one assembly per folder, and fixed compilation mode, which typically produces one assembly for each page or user control.
Advantages of the compilation model for Web application projects include the following:
  • You can use MSBuild to create a custom batch-compilation process.
  • It is easy to specify assembly attributes such as name and version.
  • Compiling in advance makes sure that users do not have to wait while the site compiles on the production server. (If the site is very large, dynamic compilation of a Web site project might take a noticeable amount of time. Dynamic compilation occurs when a request for a site resource is received after an update to the site, and the request that triggers compilation might be delayed while the required resources are compiled. If the delay is unacceptable, you can precompile the site. However, then some of the advantages of dynamic compilation are lost.)
  • You have complete control over where you put code files in the project folder structure, and how you how classes in the project refer to each other. (Dynamic compilation requires that the source code for any classes that are used throughout the site must be in the App_Code folder. You cannot refer to a page or user control class from a class in App_Code.)
Advantages of the compilation model for Web site projects include the following:
  • You can test specific pages regardless of the state of other pages. This is because running an individual page does not require that the whole site compile successfully, only the page and any components it depends on, such as code in the App_Code folder or the Global.asax file. (In a Web application project, if there are compilation errors anywhere in the site, you cannot create the assembly and therefore cannot test even the pieces of the site that compile.)
  • It is easy to update a Web site in production. You can update individual source code files on the production server without having to explicitly recompile the site. You can update individual files that are ready for deployment even if other files are not ready due to compile errors. You can also open the Web site on the production IIS server directly in Visual Studio and update the Web site in real time.
  • Precompiling to multiple assemblies can have a performance advantage in some scenarios. A typical example is a site that has many pages with lots of code written for them. Most of the pages are rarely requested and only some are used frequently. If you compile a site like this into multiple assemblies, the production server can load only the assemblies that are required for the current requests. If a page is not requested, its corresponding assembly is not loaded.
Note Note
There is no difference in performance between a Web site project and a Web application project. The only significant exceptions are the ones that have already been noted, and as a practical matter they apply only to very large sites. The first request to the Web site might require the site to be compiled, which can result in a delay. And if the Web site is running on an IIS server that is short on memory, including the entire site in a single assembly might use more memory than would be required for multiple assemblies.
To deploy a Web application project, you copy the assembly that is created by compiling the project to an IIS server. In contrast, to deploy a Web site project, you typically copy the project source files to an IIS server.
Advantages of the deployment strategy for Web application projects include the following:
  • You can avoid deploying source code to the IIS server. In some scenarios, such as shared hosting environments, you might be concerned about unauthorized access to source code on the IIS server. (For a Web site project, You can avoid this risk by precompiling on a development computer and deploying the generated assemblies instead of the source code. However, in that case you lose some of the benefits of easy site updates.)
  • Deployment often involves other tasks in addition to copying assemblies or code to a server. For example, database scripts might have to run in production, and connection strings in the Web.config file might have to be changed for a production server. Visual Studio provides tools such as one-click publish that work with Web application projects to automate many of these tasks. These tools are not available for Web site projects.
Advantages of the deployment strategy for Web site projects include the following:
  • If you make a small change to a Web site, you do not have to redeploy the whole site. Instead, can copy just the changed file or files to the production IIS server. You can also edit files directly on the production server. (Because a Web application project's code files are compiled into a single assembly file, you must deploy the whole site even for small changes, unless the only change is to an .aspx or .ascx file.)

Difference between Table Variable and temporary table

FeatureTable VariablesTemporary Tables
ScopeCurrent batchCurrent session, nested stored procedures. Global: all sessions.
UsageUDFs, Stored Procedures, Triggers, Batches.Stored Procedures, Triggers, Batches.
CreationDECLARE statement only.CREATE TABLE statement.
SELECT INTO statement.
Table nameMaximum 128 characters.Maximum 116 characters.
Column data typesCan use user-defined data types.
Can use XML collections.
User-defined data types and XML collections must be in tempdb to use.
CollationString columns inherit collation from current database.String columns inherit collation from tempdb database.
IndexesCan only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement.Indexes can be added after the table has been created.
ConstraintsPRIMARY KEY, UNIQUE, NULL, CHECK, but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY not allowed.PRIMARY KEY, UNIQUE, NULL, CHECK. Can be part of the CREATE TABLE statement, or can be added after the table has been created. FOREIGN KEY not allowed.
Post-creation DDL (indexes, columns)Statements are not allowed.Statements are allowed.
Data insertionINSERT statement (SQL 2000: cannot use INSERT/EXEC).INSERT statement, including INSERT/EXEC.
SELECT INTO statement.
Insert explicit values into identity columns (SET IDENTITY_INSERT).The SET IDENTITY_INSERT statement is not supported.The SET IDENTITY_INSERT statement is supported.
Truncate tableNot allowed.Allowed.
DestructionAutomatically at the end of the batch.Explicitly with DROP TABLE statement. Automatically when session ends. (Global: also when other sessions have no statements using table.)
TransactionsLast only for length of update against the table variable. Uses less than temporary tables.Last for the length of the transaction. Uses more than table variables.
Stored procedure recompilationsNot applicable.Creating temp table and data inserts cause procedure recompilations.
RollbacksNot affected (Data not rolled back).Affected (Data is rolled back).
StatisticsOptimizer cannot create any statistics on columns, so it treats table variable has having 1 record when creating execution plans.Optimizer can create statistics on columns. Uses actual row count for generation execution plan.
Pass to stored proceduresSQL 2008 only, with predefined user-defined table type.Not allowed to pass, but they are still in scope to nested procedures.
Explicitly named objects (indexes, constraints).Not allowed.Allowed, but be aware of multi-user issues.
Dynamic SQLMust declare table variable inside the dynamic SQL.Can use temporary tables created prior to calling the dynamic sql.

Sunday, 11 November 2012

Sql Query Optimization


Sql Query Optimization in MS SQL Server To Improve Performance of ASP.NET web applications.


Data retrieval FROM database in asp.net applications is a most common task and writing optimized queries can have a huge impact on perfirmance of application if database is huge or containing thousands of records in table.

Here i am mentioning few tips to remember while writing sql queries for optimal performance.

1. Use columns name instead of * in SELECT statements.

Use:
 
SELECT column1,column2,column3 FROM TableName
 
Insted of
 
SELECT * FROM TableName

by doing so we reduce 1 extra step of converting * into column names by sql server when query is processed.


2. Always create primary key in table.

Making primary key in table ensures that table has a clustered index created.
By doing this SELECT statements using the primary key will make data retrieval very fast because of clustered index on it.


3. Create non-clustered indexes on columns

Columns frequently used in search criteria,joins,foreign keys or used in ORDER BY clause should have index on.

the following query perform better if it has index on column department.



SELECT firstname,lastname FROM Employee
WHERE department ='HR'


4. Avoid using function calls in queries.

function calls prevent sql server to use indexes.
SELECT OrderId,Amount FROM Orders
WHERE OrderDate > GetDate()

In this query despite of having index on OrderDate, a full table scan will be performed to search each and every record of table because of function call, hence no advantage of indexes and a huge loss in performance.

better solution for this query would be to avoid calling get date in query like this
Declare @DTime DateTime Set @DTime = GetDate()
SELECT OrderId,Amount FROM Orders
WHERE OrderDate > @DTime


5. avoid using COUNT() in a query to check existance of record.

COUNT() counts all matching values by doing a table scan.
In case of EXISTS,When it finds the first matching value, it returns TRUE and stops.
SELECT column1 FROM TableName WHERE 0 < (SELECT count(*) FROM TableName2 WHERE condition)
 
 
better solution would be:
SELECT column1 FROM TableName WHERE EXISTS (SELECT * FROM TableName2 WHERE condition)


6. Always try to use joins on indexed fields.

7. Avoid triggers as much as possible.

8. Use table variables insted of temporary tables.

Table variables reside in memory while temporary tables reside in the TempDb database So temporary tables require interaction with tempdb database.

9. Use UNION ALL instead of Using UNION.

UNION ALL is faster than UNION as it does not sort the result set for distinguished value.

10. Avoid using Cursors if we need records one by one, use while loop insted.

11. Avoid HAVING clause as it is just like filter after after all rows are SELECTed.

12. Use WHERE clause to narrow the search criteria and to reduce number of records returned in SELECT statment.

13. Use TOP keyword if we want TOP N records in SELECT statement.

and last but not the least

14. Use stored procedure instead of text queries.

In stored procedures

1. Always use object name with schema this helps in directly finding the compiled plan insted of searching other objects
Use:
SELECT * FROM dbo.TableName
 
insted of
 
 
SELECT * FROM TableName


2. Use SET NOCOUNT ON

sql server returns number of rows effected in any SELECT or DML statement and we can reduce this step by setting NOCOUNT ON like this
    CREATE PROC dbo.MyProc
AS
SET NOCOUNT ON;


How to read a connection string from a web.config in asp.net

have connection string stored in web.config file, like this:

< connectionStrings >
< clear / >
< add name="SqlServerConnStr" connectionString="server=MySqlServer;Initial Catalog=MyDatabase;User ID=myUserName;Password=myPassword" providerName="System.Data.SqlClient" / >
< /connectionStrings >

To read connection string from web.config with ASP.NET server side code, you can use simple code line like this:

[ C# ]

string myConnStr = ConfigurationManager.ConnectionStrings["SqlServerConnStr"].
ConnectionString;

[ VB.NET ]

Dim myConnStr As String = _
ConfigurationManager.ConnectionStrings("SqlServerConnStr").
ConnectionString

What is the difference between abstract class and interface?

We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.
We can not make instance of Abstract Class as well as Interface. They only allow other classes to inherit from them. And abstract functions must be overridden by the implemented classes. Here are some differences in abstract class and interface.
• An interface cannot provide code of any method or property, just the signature. we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. An abstract class can provide complete code of methods but there must exist a method or property without body.

• A class can implement several interfaces but can inherit only one abstract class. Means multiple inheritance is possible in .Net through Interfaces.

• If we add a new method to an Interface then we have to define implementation for the new method in every implemented class. But If we add a new method to an abstract class then we can provide default implementation and therefore all the existing code might work properly
Question: What are Meta Tags?

Answer: Meta tags are HTML codes that are inserted into the header on a web page, after the title tag. In the context of search engine optimization, when people refer to meta tags, they are usually referring to the meta description tag and the meta keywords tag.

 The meta description tag and the meta keywords tag are not seen by users. Instead, these tags main purpose is providing meta document data to user agents, such as search engines. In addition to the well-known meta description and meta keywords tags, there are other useful meta tags, including the meta http-equiv tag, meta refresh tag, the meta robots tag, the meta copyright tag, and the meta author tag, etc. These tags are used to give web browsers and search engine spiders directions or data on various information.