Speed Up Your LINQ Statements with “Let”
This post being last post of the year 2011. Have a great going for year 2012! Wish all of you a happy prosperous new year
Using Linq Let keyword :
Old way :
var cheapCategories = from cat in Categories
where cat.Products.Average(p => p.Price) p.Price) };
New Way :
var cheapCategories = from cat in Categories
let AvgPrice = cat.Products.Average(p => p.Price)
where AvgPrice < 100
select new { cat.Name, AvgPrice };
Its code is pretty straight forward to the point!
GridView – Pass multiple values to Command Argument
<asp:TemplateField HeaderText="Start">
<ItemTemplate>
<asp:Button ID="btnTest" runat="Server" CommandName="Test" Text="Select"
CommandArgument='<%#Eval("carid") + ","+Eval("year") %>' />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Test")
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
Label1.Text= commandArgs[0];
Label2.Text = commandArgs[1];
}
}
HTTP handler & HTTP module
An ASP.NET HTTP handler is the process (frequently referred to as the “endpoint”) that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
Typical uses for custom HTTP handlers include the following:
- RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
- Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler’s response.
Typical uses for HTTP modules include the following:
- Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
- Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
- Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
Shortcuts i use in Visual Studio 2010
- Hold Alt while selecting = column select mode (don’t need to continue holding).
- ctrl+K, ctrl+C = comment out a section
- ctrl+K, ctrl+U = uncomment a section
- ctrl+M, ctrl+O = collapses all regions (functions, etc.)
- ctrl+M, ctrl+L = shows all regions (functions, etc.)
- ctrl+. (dot) = Show smart menu (whenever you see that weird blue underline, it brings up a menu of options related)
- ctrl+N = New file dialog
- Shift+Alt+Enter = Full screen mode (I only use this when I’m trying to show code to people on a projector or something)
- ctrl+tab = goes between child windows and brings up the nice “active files” window so you can pick the file you want (at least in 2010 anyway).
- F5 = debug (also in break mode causes the execution to continue, but if you don’t know that, that’s rather worrisome)
- Ctrl+F5 = compiles and runs the app (no debug)
- Shift+F5 = kills debugging session
- F4 = displays the properties window
- ctrl+K,ctrl+D = formats the code in the window
- Shift+del = deletes a row
- F12 = Go to definition
Error : Unable to load the specified metadata resource.
Recently while working on a generic Learning Management System product i came across this error – ” Unable to load the specified metadata resource. “
Stack Trace would read like : “[MetadataException: Unable to load the specified metadata resource.] System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver) +2510308 System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver) +180 System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver) +8564268 System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths) +271 System.Data.Common.Utils.<>c__DisplayClass2.<Evaluate>b__0() +19 System.Data.Common.Utils.Result.GetValue() +100 System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg) +181 System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections) +292 System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection() +29 System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor) +205 System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) +27 eLMSDAL.eLMSEntities..ctor() in F:\Users\Machine\Documents\Visual Studio 2010\Projects\eLMS\eLMSDAL\eLMSModel.Designer.cs:34 eLMSDAL.UserDAL.UserInsert(String FirstName, String MiddleName, String LastName, DateTime DOB, String Address1, String Address2, String City1, String City2, String State1, String State2, String Country1, String Country2, String ZipCode1, String ZipCode2, String Email, String Password, String Mobile, String Resume, Boolean Status, DateTime CreatedDateTime, DateTime UpdatedDateTime, String UserRole) in F:\Users\Machine\Documents\Visual Studio 2010\Projects\eLMS\eLMSDAL\UserDAL.cs:13 eLMSBLL.UserBLL.Save(ArrayList& validationErrors) in F:\Users\Machine\Documents\Visual Studio 2010\Projects\eLMS\eLMSBLL\UserBLL.cs:42 UserRegistration.btnSubmit_Click(Object sender, EventArgs e) in e:\MyWork\eLMS\UserRegistration.aspx.cs:44 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563″
After wrecking my head for about 1 hour, i got the solution.
Please make sure you update the app.config file in (probably in Data Access Layer) and web.config (Probably be in Presentation layer)
App.config and web.config must work in harmony.
hope this help someone!
Completed MCTS Certification 070 515
Today i managed to complete MCTS Certification for .NET Framework 4, Web Application Development.
I have been planning to do it for quite some time, happy atleast i completed it.
How to handle Empty Data in ASP.NET DataList and GridView
Go to your aspx web form and try this
<asp:DataList ID="dlContacts" runat="server"> <ItemTemplate> <!-- Add your Item Template Here --> </ItemTemplate> <FooterTemplate> <asp:Label ID="lblEmpty" Text="no result" runat="server" Visible='<%#bool.Parse((dlContacts.Items.Count==0).ToString())%>'> </asp:Label> </FooterTemplate> </asp:DataList> For GridView: <EmptyDataTemplate> <table border="0px" cellpadding="5" cellspacing="5"> <tr><td> Error Message here! </td> </tr> </table> </EmptyDataTemplate> <EmptyDataRowStyle CssClass="empty" ForeColor="Red" />
Handy script cleans all views, SPS, functions PKs, FKs and tables.
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
SELECT @SQL = ‘DROP PROCEDURE [dbo].[' + RTRIM(@name) +']‘
EXEC (@SQL)
PRINT ‘Dropped Procedure: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘P’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP VIEW [dbo].[' + RTRIM(@name) +']‘
EXEC (@SQL)
PRINT ‘Dropped View: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘V’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP FUNCTION [dbo].[' + RTRIM(@name) +']‘
EXEC (@SQL)
PRINT ‘Dropped Function: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N’FN’, N’IF’, N’TF’, N’FS’, N’FT’) AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = ‘ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']‘
EXEC (@SQL)
PRINT ‘Dropped FK Constraint: ‘ + @constraint + ‘ on ‘ + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘FOREIGN KEY’ ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = ‘ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']‘
EXEC (@SQL)
PRINT ‘Dropped PK Constraint: ‘ + @constraint + ‘ on ‘ + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = ‘PRIMARY KEY’ ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = ‘DROP TABLE [dbo].[' + RTRIM(@name) +']‘
EXEC (@SQL)
PRINT ‘Dropped Table: ‘ + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = ‘U’ AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
Tips to keep your web applications healthy and performance tuned (PRODUCTION ENVIRONMENTS)
- Always set debug=”false” in web.config production environment.
- Always set trace=”false” in web.config production environment
- If you are using asp.net 2.0 or higher version then always use precompiled version of your code and also prefer web application project over website. If you are using website then always publish it and then upload that precompiled version of your site in production environment.
- Always compile your project in Release Mode before uploading application to production environment.
- Use cache api as much as possible it will decrease your server roundtrip and boost application performance. ASP.NET 2.0 or higher version provides functionality called sqlcachedependancy for your database caching. It will validate cache with your database operation like insert,update and delete and if not possible with it then use the file base caching.
- Remove blank spaces from your html it will increase your kb. You can use regular expression to remove white spaces.
- For asp.net 2.0 and higher version use master pages. It will increase your performance.
- Prefer database reader over dataset unless and until you have specific reason to use database.
- Use ADO.NET asynchronous calls for ado.net methods. asp.net 2.0 or higher version is supporting your performance. If you are using same procedure or command multiple time then use ADO.NET Prepare command it will increase your performance.
- Do IIS performance tuning as per your requirement.
- Disable view state for your controls if possible. If you are using asp.net 2.0 or higher version then use asp.net control state instead of view state. Store view state in session or database by overriding the default methods for storing view state.
- User Server.Transfer instead of response.redirect.
- Always use inproc session state if possible.
- Use Ajax for your application wisely. Lots of Ajax calls for a page will also decrease your performance.
- Measure your application performance with tools like redgate profiler,firebug and whyslovw from yahoo.
- User System.Text.StringBuilder for string concatenation its 4 times more faster then the normal strings.
- Right JavaScript in .Js files and place it as bottom of the application.
- Use Separate CSS files for styling of application.
- User database paging over normal paging while displaying huge amount of data.
- Call web service from java script instead of server side. Use asynchronous calls to call a web method from web service.
Quotes from Mike Lipkin
The human mind cannot tell the difference between imagination and reality.
When you focus on what’s wrong in your life, you get into a hole.
When the fire dies down the predators come in.
Where ever you are is where you are meant to be.
What lies behind and before us are tiny compared to what is within us.
Crisis can take you to the next level.
Regret drives you insane; it’s worse than the 7 deadly sins. You can live with embarrassment but regret is a horrible companion.
Everybody is a potential teacher, even someone who drives you crazy.
We become the company we keep. If we rub up against magic, it sticks.
Nobody truly knows what’s going on!
Hope is not a strategy; faith is.
We are all angels with one wing. We can only fly when we are embracing one another.
How are you? If I’m in front of you, I’ve won.
I’m getting older. It’s a privilege denied to many.
Focus on the things that put you in an “up” state.
I am where I’m supposed to be.
We at CCAC see life at its toughest.
Your impression can last a lifetime.
Success and fear are Siamese twins. Success means you are given bigger problems to solve.
The mind works best when it’s like a parachute—open.
SNAG=sensitive new age guy
Focus on what is important, not what is urgent.
You have control of what you focus on.
What you focus on influences what you feel.
The way you listen to others becomes the way they think/feel about themselves.
CPA=continuous partial attention
If you speak with uncertainty, people will be indifferent to what you say.
Talk with the authority you have learned.
People will believe you if you talk as if you believe.
Bring a beginners mind. (more motivated)
Objects in the future are smaller than they currently appear.
All of us are going where we’ve never been before.
Make friends with your fear.
It will all be ok in the end. If it is not ok, it’s not the end.
Back yourself absolutely. You have no idea of what you are capable.
Nothing influences people like good stories.
Do your job mind-fully.
Kaizen=constant never ending improvement.
his URL: http://www.mikelipkin.com/