Saturday, August 6, 2011
Tuesday, July 5, 2011
Saturday, July 2, 2011
LINQ
| Aggregate | Conversion | Ordering | Partitioning | Sets |
| Aggregate | Cast | OrderBy | Skip | Concat |
| Average | OfType | ThenBy | SkipWhile | Distinct |
| Count | ToArray | Descending | Take | Except |
| Max | ToDictionary | Reverse | TakeWhile | Intersect |
| Min | ToList | | | Union |
| Sum | ToLookup | | | |
| | ToSequence | | | |
Sunday, June 5, 2011
Ajax Frameworks Types
Ajax Frameworks Types
Client Side vs. Server Side Frameworks
Two types of Ajax based frameworks used in the web programming nowadays:
1. Server-side Framework
2. Client-side Framework.
Server-side framework is where the code executed on the Web server is considered as Server-side code and it is installed inside the server.
Client-side framework is where code is executed on the user’s browse.
Internet is an extremely wide area and because of this both the server-side and client –side programmers may not be in the contact and performs their work separately. Both the server-side and client-side functions differently and the code used in the frameworks also varies. The code of both the frameworks has its own pros and cons that suite to different sorts of developers.
Now the question arises, what is the Server-side framework and what is Client-side? In this article, you will get the answer of both these queries. You will also learn about what are the advantages and disadvantages of both these frameworks.
Server Side Framework
The framework that is installed inside the server is known as Server-side framework. The coding of server-side framework is actually not created in JavaScript but it is the same language that API provided for server-side framework. So, it is not mandatory for the developers to be skilled in JavaScript for server-side framework programming. Nearby all the frameworks in server-side accepts the coding of developers and automatically translates it into Ajax when user accesses the website.
The framework that is installed inside the server is known as Server-side framework. The coding of server-side framework is actually not created in JavaScript but it is the same language that API provided for server-side framework. So, it is not mandatory for the developers to be skilled in JavaScript for server-side framework programming. Nearby all the frameworks in server-side accepts the coding of developers and automatically translates it into Ajax when user accesses the website.
Server-side framework can also be used for installing the specific functions from the library to translate and accessed effectively. The server-side framework exactly provides the desired functions and the library needed for developer to render the specific buttons and information in Ajax based website. The developers have to only customize the code during creating the program. Moreover, the server-side framework responds better because it handles a large number of user communications without intervention of server.
Google Web Toolkit (GWT) might be an excellent example of server-side framework that is used as a normal Java Swing kind of programming on the server side in web pages using the GWT API. The other server side frameworks are: Yahoo, Toolkit and DWR.
Server-side framework is basically used for server server-side programming that covers password protection, browser customization, form processing and building and displaying pages created from database.
Pros and Cons of Server Side Frameworks
There is no need for the developers to learn the extra language as server-side coding can be written in the existing language in which the server-side programmer is efficient.
There is no need for the developers to learn the extra language as server-side coding can be written in the existing language in which the server-side programmer is efficient.
Client Side Framework
As opposing the server-side, Client-side framework is accessed and executes within the user’s browsers. For creating Ajax based client-side framework, developers must be efficient enough in JavaScript as well as XML. Because Ajax-based client side website is fully depended upon Ajax and it also needs to a wide range of coding for different browsers.
The different uses of framework for different browsers make the Ajax client-side programming very complex. The frameworks written for Mozilla cannot be executed in Internet Explorer if XMLHttpRequest has not been defined and implemented for the Internet explorer too.
The Request XMLHttpRequest performs like a bridge between the server and the client. The developers have to generate different coding for different platforms to perform it successfully. That’s why the developers must have the knowledge about which browser has been used by his client; otherwise the developer has to develop several customize client-side framework for running their own platforms.
Through Client-side framework, users can execute any technology that supports user’s browser. In Client-side framework, users can modify several features besides codes without sending information to web server.
In the Client-side framework, user can handle multiple asynchronous request, can detect easily error handling and exceptions and can mix and match widget facilities to get extra flexibility in the programming. (Widgets are small interfaces or components that can be integrated with an application easily through client side framework)
Client-side framework is used in online games, customizing the display without reloading the page and getting data about the user’s screen or browser. The examples of client-side framework are Prototype, DOJO Toolkit, Rico, Script.aculo.us and many more.
Pros and Cons of Client Side Frameworks
Client-side framework is more flexible than server-side due to multi-handing frameworks, easily error handling and exceptions while the adding of widgets makes it extra-flexible.
As opposing the server-side, Client-side framework is accessed and executes within the user’s browsers. For creating Ajax based client-side framework, developers must be efficient enough in JavaScript as well as XML. Because Ajax-based client side website is fully depended upon Ajax and it also needs to a wide range of coding for different browsers.
The different uses of framework for different browsers make the Ajax client-side programming very complex. The frameworks written for Mozilla cannot be executed in Internet Explorer if XMLHttpRequest has not been defined and implemented for the Internet explorer too.
The Request XMLHttpRequest performs like a bridge between the server and the client. The developers have to generate different coding for different platforms to perform it successfully. That’s why the developers must have the knowledge about which browser has been used by his client; otherwise the developer has to develop several customize client-side framework for running their own platforms.
Through Client-side framework, users can execute any technology that supports user’s browser. In Client-side framework, users can modify several features besides codes without sending information to web server.
In the Client-side framework, user can handle multiple asynchronous request, can detect easily error handling and exceptions and can mix and match widget facilities to get extra flexibility in the programming. (Widgets are small interfaces or components that can be integrated with an application easily through client side framework)
Client-side framework is used in online games, customizing the display without reloading the page and getting data about the user’s screen or browser. The examples of client-side framework are Prototype, DOJO Toolkit, Rico, Script.aculo.us and many more.
Pros and Cons of Client Side Frameworks
Client-side framework is more flexible than server-side due to multi-handing frameworks, easily error handling and exceptions while the adding of widgets makes it extra-flexible.
Saturday, March 12, 2011
Static Class
- Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName
- A Program can't tell when it is going to load static class but its definitely loaded before the call.
- A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.
- A Static class can contain only static members. So all the members and functions have to be static.
- A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
Static Constructor
This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly. Notes for Static Constructors:
- It is used to initialize static data members.
- Can't access anything but static members.
- The static constructor should be without parameters.
- Can't have access modifiers like Public, Private or Protected.
- There can be only one static constructor in the class.
- A class can have static as well as non static constructor without arg at same time.
The syntax of writing the static constructors is also damn simple. Here it is:
public class Sample{
static Sample()
{
// Only static members are accessible.
// Initialization code can be here.
}
// Other class methods goes here
}
Let us understand features step by step here.
Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it.
Secondly, it is going to be called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor.
Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.
Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.
Now, one question raises here, can we have two constructors as:
public class Sample
{
static Sample()
{
// Only static members are accessible.
// Initialization code can be here.
}
public Sample()
{
// Code for the First Constructor.
}
// Other class methods goes here
}
This is perfectly valid, though doesn't seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation.
Wednesday, February 16, 2011
SQL Server Q & A -1
1. How to optimize stored procedures in SQL Server?
Ans: I. Use where clause
II. Select only required fields
III. Do join on indexed key fields
2. What is the difference between Stored procedure and User defined functions?
3. Why should we go for Stored Procedures? Why not direct queries?
Ans: SP are precompiled and contain an execution plan with it. Hence, they are faster.
4. How many NULL values we can have in a Unique key field in SQL Server?
Ans: Only one. In case of Oracle, we can have multiple NULL values in a Unique key field.
5. What is correlated subquery?
6. What is an index. What are the types?
Indexes in databases are very much similar to Indexes in Books. Indexes help in searching data faster.
Types: Clustered Index
Non-Clustered Index
7. What is the difference between a clustered index and a non-clustered index?
Clustered Index:
1 Only one clustered index allowed per table
2 Physically rearranges the data
3 For use on columns that are frequently searched for range of data
Non-clustered Index:
1 Upto 249 non-clustered index allowed per table
2 Doesn’t rearrange the data. Keeps a pointer to the data.
3 For use on columns that are searched for single value.
8. What is a join? What are the types of joins?
Joins are used to retrieve data from multiple tables.
Following are the types of joins:
Inner join
Left outer join
Right outer join
Full outer join
Cross join
9. What is a transaction?
A SQL transaction is a sequence of operations performed as a single unit of work. If all the tasks are completed successfully, then the transaction is committed (saved). If a single task fails, the transaction is rolled back (discarded).
10. What is ACID property of transaction?
A SQL transaction must exhibit ACID property, i.e Atomicity, Consistency, Isolation, and Durability.
Atomicity: A transaction is always treated as a single unit of work, i.e. either all the tasks are performed or none of them, no intermediate stage.
Consistency: When a transaction is completed, it must leave all data in a consistent state.
Isolation: Modifications made by a transaction must be isolated from the modifications made by other transactions.
Durability: After a transaction is completed, it’s effects are permanently in place in the system.
11. What is SET NOCOUNT ON?
When we perform a SELECT, INSERT, UPDATE or DELETE query, it returns a COUNT (number of rows affected) when SET NOCOUNT OFF. If SET NOCOUNT ON, it doesn’t return the COUNT.
12. How to delete exactly duplicate records from a table?
There are many ways. Simplest answer is:
i. Let the table tab1 contains duplicate records.
ii. Insert distinct records from tab1 in a temporary table #temp
INSERT INTO #temp
SELECT DISTINCT * FROM tab1
iii. Delete all rows from original table tab1
DELETE FROM tab1
iv. Insert from temporary table
INSERT INTO tab1
SELECT * FROM #temp
Try other solutions yourself.
13. How to get nth highest salary from employee table.
The query below demonstrates how to find the 5th highest salary. Replace 5 with any integer to get nth salary.
SELECT TOP 1 SALARY
FROM (SELECT DISTINCT TOP 5 SALARY
FROM EMPLOYEE ORDER BY SALARY DESC) a
ORDER BY SALARY ASC
Ans: I. Use where clause
II. Select only required fields
III. Do join on indexed key fields
2. What is the difference between Stored procedure and User defined functions?
3. Why should we go for Stored Procedures? Why not direct queries?
Ans: SP are precompiled and contain an execution plan with it. Hence, they are faster.
4. How many NULL values we can have in a Unique key field in SQL Server?
Ans: Only one. In case of Oracle, we can have multiple NULL values in a Unique key field.
5. What is correlated subquery?
6. What is an index. What are the types?
Indexes in databases are very much similar to Indexes in Books. Indexes help in searching data faster.
Types: Clustered Index
Non-Clustered Index
7. What is the difference between a clustered index and a non-clustered index?
Clustered Index:
1 Only one clustered index allowed per table
2 Physically rearranges the data
3 For use on columns that are frequently searched for range of data
Non-clustered Index:
1 Upto 249 non-clustered index allowed per table
2 Doesn’t rearrange the data. Keeps a pointer to the data.
3 For use on columns that are searched for single value.
8. What is a join? What are the types of joins?
Joins are used to retrieve data from multiple tables.
Following are the types of joins:
Inner join
Left outer join
Right outer join
Full outer join
Cross join
9. What is a transaction?
A SQL transaction is a sequence of operations performed as a single unit of work. If all the tasks are completed successfully, then the transaction is committed (saved). If a single task fails, the transaction is rolled back (discarded).
10. What is ACID property of transaction?
A SQL transaction must exhibit ACID property, i.e Atomicity, Consistency, Isolation, and Durability.
Atomicity: A transaction is always treated as a single unit of work, i.e. either all the tasks are performed or none of them, no intermediate stage.
Consistency: When a transaction is completed, it must leave all data in a consistent state.
Isolation: Modifications made by a transaction must be isolated from the modifications made by other transactions.
Durability: After a transaction is completed, it’s effects are permanently in place in the system.
11. What is SET NOCOUNT ON?
When we perform a SELECT, INSERT, UPDATE or DELETE query, it returns a COUNT (number of rows affected) when SET NOCOUNT OFF. If SET NOCOUNT ON, it doesn’t return the COUNT.
12. How to delete exactly duplicate records from a table?
There are many ways. Simplest answer is:
i. Let the table tab1 contains duplicate records.
ii. Insert distinct records from tab1 in a temporary table #temp
INSERT INTO #temp
SELECT DISTINCT * FROM tab1
iii. Delete all rows from original table tab1
DELETE FROM tab1
iv. Insert from temporary table
INSERT INTO tab1
SELECT * FROM #temp
Try other solutions yourself.
13. How to get nth highest salary from employee table.
The query below demonstrates how to find the 5th highest salary. Replace 5 with any integer to get nth salary.
SELECT TOP 1 SALARY
FROM (SELECT DISTINCT TOP 5 SALARY
FROM EMPLOYEE ORDER BY SALARY DESC) a
ORDER BY SALARY ASC
Friday, January 14, 2011
Enabling SQL Cache Dependency in ASP.NET
1• Enable notifications for the database.
2• Enable notifications for individual tables.
3• Enable ASP.NET polling using “web.config” file
4• Finally use the Cache dependency object in your ASP.NET code
The above command will cause to create one new table and new stored procedures as specified below in the database.
Essentially, when a change takes place, a record is written in this table. The SQL Server
polling queries this table for changes.
a. This also can be done manually using AspNet_SqlCacheRegisterTableStoredProcedure in query analyzer, for example, as given below:
b. This also can be done with the use of "aspnet_regsql" with parameters as discussed
e.g.
Registering tables for notification internally creates trigger for the tables. For instance for
a "TableName" table the following trigger is created. So any modifications done to the
"TableName" table will update the "AspNet_SqlCacheNotification" table.
updating a record), the change Id column is incremented by 1.ASP.NET queries this table
repeatedly keeps track of the most recent changed values for every table. When this
value changes in a subsequent read, ASP.NET knows that the table has changed.
Continue .......
2• Enable notifications for individual tables.
3• Enable ASP.NET polling using “web.config” file
4• Finally use the Cache dependency object in your ASP.NET code
1. Enabling notifications for the database.a. Enable notifications for the database, that can be done by using aspnet_regsql.exe, a command line utility.
CD c:\[WinDir]\Microsoft.NET\Framework\[Version] directoryb. execute the command at the same location as
c:>[WinDir]\Microsoft.NET\Framework\[Version] directory> aspnet_regsql -ed -E -d MyDBName
| Switch | Description |
| -ed | command-line switch |
| -E | Use trusted connection |
| -S | Specify server name it other than the current computer you are working on |
| -d | Database Name |
The above command will cause to create one new table and new stored procedures as specified below in the database.
Essentially, when a change takes place, a record is written in this table. The SQL Server
polling queries this table for changes.
| Procedure Name | Description |
| AspNet_Sql CacheRegisterTable StoredProcedure | This stored procedure sets a table to support notifications. This process works by adding a notification trigger to the table, which will fire when any row is inserted, deleted, or updated. |
| AspNet_SqlCache UnRegisterTable StoredProcedure | This stored procedure takes a registered table and removes the notification trigger so that notifications won't be generated. |
| AspNet_Sql CacheUpdateChange IdStoredProcedure | The notification trigger calls this stored procedure to update the AspNet_SqlCacheTablesFor ChangeNotification table, thereby indicating that the table has changed. |
| AspNet_SqlCache QueryRegistered TablesStored Procedure | This extracts just the table names from the AspNet_SqlCacheTablesForChangeNotification table. It’s used to get a quick look at all the registered tables. |
| AspNet_SqlCache PollingStored Procedure | This will get the list of changes from the AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling. |
| Table Name | Description |
| AspNet_SqlCacheTablesForChangeNotification | Has three columns: tableName, notificationCreated, and changeId. This table is used to track changes. Essentially, when a change takes place, a record is written into this table. The SQL Server polling queries this table. Also a set of stored procedures is added to the database as well. See the following table. |
2. Enabling notification for individual tablesAfter enabling notification for database, need to enable notification support for each individual table.
a. This also can be done manually using AspNet_SqlCacheRegisterTableStoredProcedure in query analyzer, for example, as given below:
exec AspNet_SqlCacheRegisterTableStoredProcedure 'TableName'
b. This also can be done with the use of "aspnet_regsql" with parameters as discussed
| Parameter | Description |
| -et | to enable a able for sql cache dependency notifications |
| -t | to name the table |
e.g.
aspnet_regsql -et -E -d Northwind -t 'TableName'
Registering tables for notification internally creates trigger for the tables. For instance for
a "TableName" table the following trigger is created. So any modifications done to the
"TableName" table will update the "AspNet_SqlCacheNotification" table.
CREATE TRIGGERWhen you make a change in the table (such as inserting, deleting or
dbo.[Products_AspNet_SqlCacheNotification_Trigger] ON
[TableName]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
EXEC dbo.AspNet_SqlCacheUpdateChangeIdStoredProcedure
N'Products‘
END
updating a record), the change Id column is incremented by 1.ASP.NET queries this table
repeatedly keeps track of the most recent changed values for every table. When this
value changes in a subsequent read, ASP.NET knows that the table has changed.
Continue .......
What are the various ways to maintain state in web application?
√ session variables
√ Hidden fields
√ View state
√ Hidden frames
√ Cookies
√ Query strings
√ Hidden fields
√ View state
√ Hidden frames
√ Cookies
√ Query strings
Thursday, January 13, 2011
What is scavenging ?
The feature of caching is one of the useful technologies that exists in web application to improve the performance of the application in many scenarios but also have drawback that it uses numerous resources of the server that includes a great amount of memory which sometimes causes the complete memory gets exhausted.
So when server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first
So when server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first
Call Back method creation for a cached item
Ensures cache to be updated based on changes after removal of corresponding cached item.
Signature of the delegate:
e.g.
CacheItemRemovedCallback delegate: An instance of this delegate is passed to the insert method when we insert a cache item.Signature of the delegate:
public delegate void CacheItemRemovedCallback( string key, object value, CacheItemRemovedReason reason );
| Parameter | Description |
|---|---|
| key | The index location for the item removed from the cache. |
| value | The object item removed from the cache. |
| reason | The reason the item was removed from the cache, as specified by the CacheItemRemovedReason enumeration. |
CacheItemRemovedReason enumeration: a very useful enumeration used for getting reason of expiration. | Parameter | Description |
|---|---|
| DependencyChanged | The item is removed from the cache because a file or key dependency changed. |
| Expired | The item is removed from the cache because it expired. |
| Removed | The item is removed from the cache by a Remove method call, or by an Insert method call that specified the same key. |
| Underused | The item is removed from the cache because the system removed it to free memory. |
e.g.
public void RemovedCallback(String k,
Object v,CacheItemRemovedReason r) {
// Code to check the reason of expiration.
// Logic to repopulate cache item using new values
}
What is a dependency?
Any change in the resources which our cache item depends on[*], will make our cache item expire.
[*] Expiration policy of the item based on other resources such as physical file(s) in the server, another cache item(s), or time that can be set to be dependency for item to be cached.
There are three types of dependencies:
For multiple file dependencies, we can pass a string array containing the filename to the constructor.
e.g.
[*] Expiration policy of the item based on other resources such as physical file(s) in the server, another cache item(s), or time that can be set to be dependency for item to be cached.
There are three types of dependencies:
- File based dependency
- Key based dependency
- Time based dependency
File based dependency
We can set the validity of the cache item based on an external file or files. When this resource changes, the cached object becomes obsolete and is removed from the cache.e.g.
CacheDependency dependency = new CacheDependency(Server.MapPath("isbn.xml"));For multiple file dependencies, we can pass a string array containing the filename to the constructor.
Key based dependency
Key based dependency enables you to associate one cached item with another item in the cache and invalidates the first item when the second item changes. The following code fragment demonstrates how to insert an item into your application'sCache with a dependency on a key to another item placed in the cache. Since this method uses array syntax, you must define the number of keys the item you are adding to the Cache is dependent on.e.g.
String[] dependencyKey = new String[1];
dependencyKey[0] = "key1";
CacheDependency dependency = new CacheDependency(null, dependencyKey); You can use multiple key dependencies by increasing the array size and adding the keys to the array.Time based dependency.
A time based dependency expires the item at a predefined time. There are two types of time-based dependency: Absolute and Sliding explained in under ASP.NET Cache.Cache Insert() Method
Insert() ---> it overwrites the item if same key already exists in the cache.
e.g.
CacheItemRemovedCallback is a delegate, which defines a callback method for notifying applications when a cached item is removed from the Cache.
public void Insert(string key, object value,CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback );
| Parameter | Description |
|---|---|
| key | The cache key used to reference the object. |
| value | The object to be inserted in the cache. |
| dependencies | The file or cache key dependencies for the item. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains a null reference (Nothing in Visual Basic). |
| absoluteExpiration | The time at which the inserted object expires and is removed from the cache. |
| slidingExpiration | The interval between the time the inserted object was last accessed and when that object expires. If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed. |
| priority | The cost of the object relative to other items stored in the cache, as expressed by the CacheItemPriority enumeration. This value is used by the cache when it evicts objects; objects with a lower cost are removed from the cache before objects with a higher cost. |
| onRemoveCallback | A delegate that, if provided, will be called when an object is removed from the cache. You can use this to notify applications when their objects are deleted from the cache. |
e.g.
Cache.Insert ("DSN", connectionString,new CacheDependency("filepath")
DateTime.Now.AddMinutes(2),
TimeSpan.Zero,
CacheItemPriority.High,
new CacheItemRemovedCallback(this.RemovedCallback)
); dependency and a call back function executed when the cache expires.CacheItemRemovedCallback is a delegate, which defines a callback method for notifying applications when a cached item is removed from the Cache.
e.g. 1. Insert xml data from a file into the cache, eliminating
the need to read from the file on subsequent requests.
Cache.Insert("key", myXMLFileData, newSystem.Web.Caching.CacheDependency(Server.MapPath("users.xml")));
CacheDependency ----> ensures that cache immediately expires while files changes and updated with changes. Similary can happen with array of filenames, if cached data needs to depend on several files.
e.g. 2. Inserting second piece of data that depends on the existing first piece of data ["key" (say)].
Cache.Insert("dependentkey", myDependentData, newSystem.Web.Caching.CacheDependency(new string[] {}, new string[]{"key"}));
If no key existed in the cache called "key", or if the item associated with that key expires or is updated, then the cache entry for "dependentkey" would expire.
e.g. 3. Absolute Expiration:
Cache.Insert("key", myTimeSensitiveData, null,DateTime.Now.AddMinutes(1), TimeSpan.Zero);
Caches time sensitive data for one minute, at which point the cache will expire.Note: absolute expiration and sliding expiration (below) cannot be used together
e.g. 4. Sliding Expiration:
Cache.Insert("key", myFrequentlyAccessedData, null,System.Web.Caching.Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(1));
Caches some frequently used data and remain in cache until one minute passes without anything referencing it.If anyone references even at 59th second then again time of expiration become one minute instead of one second that was expected to expire the data in case it might not referenced during the current minute.
Wednesday, January 12, 2011
ASP.NET Cache
Used while sharing data across users based on dependencies and expiration policies.
Cache values can be accessed using
Name space -System.Web
Class object of - HttpContext or Page
Property - Cache
It has the greatest potential impact on an application's performance
e.g.
The various types of parameters that can be used in this form of caching is discussed as below:
In order to enable separate cache entries for each browser, VaryByCustom can be set to a value of "browser". This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version.
Fragment caching uses the same syntax as page level output caching, but applied to a user control (.ascx file) instead of to a web form (.aspx file).
In addition to parameters used for page level output caching an additional an OutputCache attribute named "VaryByControl" is included in fragment caching, which will vary the caching of the user control depending on the value of a member of that control(typically a control on the page, such as a DropDownList).
If VaryByControl is specified, VaryByParam may be omitted.
By default each user control on each page is cached separately. However, if a user control does not vary between pages in an application and is named the same across all such pages, the Shared="true" parameter can be applied to it, which will cause the cached version(s) of the user control to be used by all pages referencing that control.
e.g. 1. Separate cache for variation of query string and page containing control.
e.g. 2. Separate cache creation with variation of selected value in
VaryByControl="CountryDropDownList" %>
User control cached for 60 sec and cached for each changed
value of control "CountryDropDownList".
e.g. 3. Separate cache creation with each browser name and
variation of major version
Using the Cache object, you can store any serializeable data object, and control how that cache entry expires based on a combination of one or more dependencies.
Storing Data in the Cache
1. The simplest way to store data in the Cache is simply to assign it, using a key, just like a HashTable or Dictionary object:
Cache["key"] = "value";
This will store the item in the cache without any dependencies,
so it will not expire unless the cache engine removes it in order to
make room for additional cached data.
2. To include specific cache dependencies, the Add() or Insert()
method is used. Each of these has several overloads.
Add() --> Returns a reference to the cached object and do nothing if
item with same key already exists
Insert() --> Has no return value and overwrite the item if item with
same key name already exists.
3. Other Options:
a. Specifying the priority of the item (from low to high to NotRemovable): defined in the System.Web.Caching.CacheItemPriority enumeration
b. CacheItemRemovedCallback option allows some interesting possibilities.
Cache values can be accessed using
Name space -System.Web
Class object of - HttpContext or Page
Property - Cache
It has the greatest potential impact on an application's performance
Tip:
Cache Early; Cache Often
Implement caching at every layer of your application. Add caching support to the data layer, the business logic layer, and the UI or output layer. Memory is cheap—by implementing caching in an intelligent fashion throughout the application, you can achieve great performance gains.
| Types of dependencies | |
| Type | Brief Description |
|---|---|
| File dependency | Allows you to invalidate a specific cache item when a disk based file or files change. |
| Time-based expiration | Allows you to invalidate a specific cache item depending on predefined time. |
| Key dependency | Allows you to invalidate a specific cache item depending when another cached item changes. |
| Table 1. |
Cache Callback
As cache object is created according to some dependency (ref table 1) and expires or removed while there is change in corresponding dependency and ASP.NET execute/capable to fire a cache callback method corresponding to this removal of object to add the items back in cache.ASP.NET has a full-featured cache engine that can be used by applications to store arbitrary objects in memory. This mechanism is implemented via the Cache class, an instance of which exists for each application configured on a web server. The application cache provides a simple dictionary interface using key/value pairs that enables you to store and retrieve objects from the cache.
| Forms of caching | |
| Type | Advantages |
|---|---|
| page level output caching, | provides additional flexibility and can be used to take advantage of caching throughout every layer of an application. |
| user control level output caching (or fragment caching) | advantage of being incredibly simple to implement |
| Cache API |
Page Level Output Caching
<%@OutputCache Duration="60" VaryByParam="*"%>
The various types of parameters that can be used in this form of caching is discussed as below:
Param name | Description |
|---|---|
| Duration | Required. Time, in seconds, the page should be cached. Must be a positive integer. |
| Location | Specifies where the output should be cached. If specified, must be one of: Any, Client, Downstream, None, Server or ServerAndClient. |
| VaryByParam | Required. The names of the variables in the Request, which should result in, separate cache entries. "none" can be used to specify no variation. "*" can be used to create new cache entries for every different set of variables. Separate variables with ";". |
| VaryByHeader | Varies cache entries based on variations in a specified header. |
| VaryByCustom | Allows custom variations to be specified in the global.asax (for example, "Browser"). |
Most situations can be handled with a combination of the required Duration and VaryByParam options. VaryByHeader and VaryByCustom are primarily used to allow customization of the page's look or content based on the client that is accessing them.
In order to enable separate cache entries for each browser, VaryByCustom can be set to a value of "browser". This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version.
<%@ OutputCache Duration="60" VaryByParam="None" VaryByCustom="browser" %>
Fragment Caching, User Control Output Caching
Fragment caching uses the same syntax as page level output caching, but applied to a user control (.ascx file) instead of to a web form (.aspx file).
In addition to parameters used for page level output caching an additional an OutputCache attribute named "VaryByControl" is included in fragment caching, which will vary the caching of the user control depending on the value of a member of that control(typically a control on the page, such as a DropDownList).
If VaryByControl is specified, VaryByParam may be omitted.
By default each user control on each page is cached separately. However, if a user control does not vary between pages in an application and is named the same across all such pages, the Shared="true" parameter can be applied to it, which will cause the cached version(s) of the user control to be used by all pages referencing that control.
e.g. 1. Separate cache for variation of query string and page containing control.
<%@ OutputCache Duration="60" VaryByParam="*" %>
Creates a separate cache for control for 60 sec and created
for every variation of query string and page containing control.
e.g. 2. Separate cache creation with variation of selected value in
CountryDropDownList control.<%@ OutputCache Duration="60" VaryByParam="none"
VaryByControl="CountryDropDownList" %>
User control cached for 60 sec and cached for each changed
value of control "CountryDropDownList".
e.g. 3. Separate cache creation with each browser name and
variation of major version
<%@ OutputCache Duration="60" VaryByParam="none"
VaryByCustom="browser" Shared="true %>
Created cache expires after 60 sec which gets created
for every change in browser name and major version.
The cache entries for each browser would then be
shared by all pages referencing this user control (as long
as all pages refer to the control with the same ID).
Caching API, Using the Cache Object
Using the Cache object, you can store any serializeable data object, and control how that cache entry expires based on a combination of one or more dependencies.
Storing Data in the Cache
1. The simplest way to store data in the Cache is simply to assign it, using a key, just like a HashTable or Dictionary object:
Cache["key"] = "value";
This will store the item in the cache without any dependencies,
so it will not expire unless the cache engine removes it in order to
make room for additional cached data.
2. To include specific cache dependencies, the Add() or Insert()
method is used. Each of these has several overloads.
Add() --> Returns a reference to the cached object and do nothing if
item with same key already exists
Insert() --> Has no return value and overwrite the item if item with
same key name already exists.
3. Other Options:
a. Specifying the priority of the item (from low to high to NotRemovable): defined in the System.Web.Caching.CacheItemPriority enumeration
b. CacheItemRemovedCallback option allows some interesting possibilities.
Tuesday, January 11, 2011
Ajax types most know list
| AJAX Library Name | Brief Description |
|---|---|
| ASP.NET AJAX Extensions ("Atlas") | AJAX functionality for ASP.Net via server components, with auto generated JavaScript and tightly related to server controls. |
| AJAXPro | Ajax for ASP.NET development to create a fully client-side based and require a few server-side API calls to get/set data |
| Direct Web Remoting (DWR) | AJAX solution for Java based web solutions. |
| Dojo | |
| Google Web Toolkit (GWT) | For Java based solutions that require to invest more time to get a more robust, easier-to-debug solution |
| Prototype | |
| xAJAX | For PHP development of all stripes |
Note: There are the strengths and weaknesses of popular pure JavaScript libraries and a few options offered by the server-based AJAX libraries.
|
Monday, January 3, 2011
A Simple trigger example
The below is simplest trigger that execute while any record is inserted in the table tbl_registrations and while insert operation is complete it displays all the values inserted in the table
Create trigger tr_MyTrigger1
ON tbl_registrations
FOR INSERT
AS
Begin
SELECT * FROM Inserted
End
Create trigger tr_MyTrigger1
ON tbl_registrations
FOR INSERT
AS
Begin
SELECT * FROM Inserted
End
List of procedures as comma seprated string
Following is the code that can be used to get list of all procedures having name started with string 'Proc' and this returns a single string containing all procedures as comma separated names.
i.e. if there are procedures proc_1 ,proc_2,proc_3 and proc_4 exists in sql server then the returned result will look like
proc_1 ,proc_2,proc_3 , proc_4
Also @listStr variable contains the result that can be used to process this list further according to the requirements.
DECLARE @listStr VARCHAR(MAX)
select @listStr = COALESCE(@listStr+',' , '') + [name]
FROM sysobjects WHERE type ='P' AND name LIKE 'Proc%' AND [name] IS NOT NULL
SELECT @listStr
i.e. if there are procedures proc_1 ,proc_2,proc_3 and proc_4 exists in sql server then the returned result will look like
proc_1 ,proc_2,proc_3 , proc_4
Also @listStr variable contains the result that can be used to process this list further according to the requirements.
DECLARE @listStr VARCHAR(MAX)
select @listStr = COALESCE(@listStr+',' , '') + [name]
FROM sysobjects WHERE type ='P' AND name LIKE 'Proc%' AND [name] IS NOT NULL
SELECT @listStr
Getting List of added/deleted records in trigger
To list of all records that has been added in a table for which trigger executed
records
SELECT * FROM Inserted
To list of all records that has been deleted in a table for which trigger executed
records
SELECT * FROM Deleted
To list of all records that has been modified but not delete modified in a table for which trigger executed
records
SELECT * FROM Inserted
EXCEPT
SELECT * FROM Deleted
records
SELECT * FROM Inserted
To list of all records that has been deleted in a table for which trigger executed
records
SELECT * FROM Deleted
To list of all records that has been modified but not delete modified in a table for which trigger executed
records
SELECT * FROM Inserted
EXCEPT
SELECT * FROM Deleted
Get List of procedure in SQL Server
Select so.name FROM syscolumns sc,master..systypes st,sysobjects so
WHERE sc.id in (select id from sysobjects where type ='P')
AND so.type ='P'
AND sc.id = so.id
AND sc.type = st.type
GROUP BY so.name
WHERE sc.id in (select id from sysobjects where type ='P')
AND so.type ='P'
AND sc.id = so.id
AND sc.type = st.type
GROUP BY so.name
Subscribe to:
Posts (Atom)