Monday, 30 August 2010

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Try adding a Connect Timeout in the web.config

<add key="DBConnection" value="server=LocalHost;uid=sa;pwd=;database=DataBaseName;Connect Timeout=200; pooling='true'; Max Pool Size=200"/>


Tuesday, 17 August 2010

Textbox Set Focus on Load while using AJAX Controls on Page

Textbox Set Focus on Load while using AJAX Controls on Page


Whenever you are using AJAX Controls on Page, always remember that
normal way of making set Focus to textbox controls won't work.

Solution to this Problem:
protected void Page_Load(object sender, EventArgs e)
{
AjaxControlToolkit.Utility.SetFocusOnLoad(txtEmailId);
}

Where, txtEmailId is control name.

In every other case where you are not using AJAX Control on Page load and your
.Net Application is in VS.Net 2005 or above version, you can try using following

protected void Page_Load(object sender, EventArgs e)
{

this.Form.DefaultFocus = this.txtEmailId.ClientID;
}


Note: There are various techniques i have discuss most commonly used
technique to set focus for textbox control.

Disable button in onclick and process the button click event

This is what I need to implement for one of my project. I am using Ajax and if user tries to hit the submit the button more than once, only the very first request should submit to server and all other requests shouldn't make any request. So, for this I need to disable the button when first time click on button and enable it after processed. But, I faced a problem that when I try to disable the button in javascript of client side click event then the postback event not raising at all. There are couple of ways we can implement this. First, I tried from server side code.

Solution 1:

  1. btnSubmit.Attributes.Add("onclick","javascript:" + btnSubmit.ClientID + ".disabled=true;" + this.GetPostBackEventReference(btnSubmit));
But, this solution won't work in all scenarios and especially if there are validations.

Solution 2:

  1. OnClientClick='javascript:this.disabled=Page_ClientValidate("");' UseSubmitBehavior="false"
For ASP Button the two properties onclientclick and usesubmitbehavior will do magic for us. In onclientclick event I am disabling the button if and only if the validation passed. Go back to my previous post. It describes how to validate the controls in client side and give the result true or false. And because of using the UseSubmitBehavior property it will automatically re-enable the button once the request processed.

Hope this gives you the enough idea. Like to know what you think.

DropDownList Autopostback Problem with Chrome

I was trying to perform Autopostback on Asp.net DropDownList, Selection and found that it was working in IE and Firefox, but not working in Chrome.


Cause of Problem
Required field Validator control is not working as expected for DropDownList Control

Solution to perform Page Postback on making selection to DropDownList
You need to set EnableClientScript="false" in order to make it work in Chrome.

Example:
ToolTip="Select Language" Width="190" AutoPostBack="true"
onselectedindexchanged="ddlLanguage_SelectedIndexChanged">

EnableClientScript="false" ControlToValidate="ddlLanguage" InitialValue="0" TabIndex="1" Text="*" ErrorMessage="Please Select Language" Display="None">

How to open .MBOX File

How to open MBOX File?

Gmail email format are in following format


myemailaddress@gmail.com.mbox

Now, first time i come across .mbox extension, so how should i open file with .MBOX Extension.

Answer is: Word Pad

How to get Sql server 2008 intellisense working for schema changes

The new feature "intellisense" added in sql server 2008 is making my life easier. And I am enjoying this feature a lot. But I noticed many times that when we make any changes to DB schema like creating / modifying database objects (tables, sprocs, ...) we don't notice the schema changes in intellisense in the same session. This made me too bad and many times I cursed Microsoft for this inclomplete feature. But after making some research on this, I have found the solution to get intellisense for new schema changes in current session.

Actually what happens when you connect to sql server 2008 using sql server management studio is, it queries for the current database schema and saves it somewhere. And It uses this schema information for showing the intellisense when the user is writing queries. But when we create/update the sql objects (sprocs, tables, views, ...) these won't be updated and the intellisense is pulled from old schema. That's why we don't notice the schema changes in intellisense unless we explicitly refresh the cache. In order to get new chema changes we must clear the intellisense cache.

To clear the intellisense cache we need to click Edit -> Intellisense -> RefreshLocalCache in sql server 2008 management studio as shown in below screen.

Visual Studio intellisense for HTML 5


It's the time to use the new technologies like HTML 5. Everyone of us knew about what this is and how easy now to generate some nice and rich UI without put much efforts. No complex javascript, no silverlight or flash is required most of the time and many more advantages. There are plenty of changes in CSS too. So, I believe we should start using HTML 5 in our applications. Because almost all browsers are supporting it.
After I have written some posts on Visual Studio intellisense on
Jquery and SharePoint 2010 ECMAscript Client OM, I want to write similar on the intellisense for HTML 5.

This is very simple process than any other we have followed.

1. Download the HTML5 intellisense file from the official vs tools site.
Visual Studio intellisense for HTML 5. Applies to both VS 2010 and VS 2008.
Note: In internet there are few sites already written related to this post. But, they are not providing the valid HTML 5 XSD files. They are downloading files from somewhere else and giving us. Those files are not up to date. So, try to download the files always from the site who created them. In this case Microsoft. The link I have given is official VS tools web site.
2. Now run the file and select the preferences and finish the installer.
3. Now you can see new files updated with the name HTML_5.XSD at the location: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Packages\schemas\html [For VS 2008] and C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\schemas\html [For VS 2010].
4. And the MSI update we have ran automatically updates the registry key and other settings. So, no more changes we have to do manually.
5. Now, if you have opened the Visual Studio, please close it and reopen it.
6. Now, from the Visual Studio toolbars, "HTML Source Editing" we have a drop down for selecting the HTML version as shown below.
7. Once we have selected that option we are good to go and write HTML 5 code as shown below.
8. In the above code sample, I am trying to render a video and it is showing me all the attributes for the video tag.

That is it!!! There we are.
Hope you liked it.

Check string contains numbers in T-SQL


I know this is looking very simple when we read. But, I had a requirement where I need to filter strings from string data type column in T-SQL. Means, some strings in database having numbers in them, and I need to get them out and do some processing. When I started implementing this, I had so many ideas and thought like, looping through all characters in each string and check whether it has numbers in it or not. But, this is not efficient and may be a stupid implementation. And after thought about it sometime, started reading T-SQL documentation and found a wonderful function which is already built in in T-sql. I am saved. Very happy to see that function and that is working very great.


The function name called "
PATINDEX". Which requires two parameters. 1. Regular expression and another is 2. input string. It returns the value of the index where it finds the given expression. If it is greater than 0 then it found the match, otherwise no.

Usage:

DECLARE @inputStr Varchar(100);
SET @inputStr = 'This costs 35$';

IF PATINDEX('%[0-9]%',@inputStr) > 0
BEGIN
--Write some logic here
PRINT 'YES, The string has numbers';
END
ELSE
BEGIN
--Write some logic here.
PRINT 'NO, The string does not have numbers';
END

It's very simple. Right? Now, I can use this in the single SELECT query and using CASE, WHEN I can display all strings which has the numbers in it from a table.

And now, vice versa.. How to find whether a string contains alphabets. [There are possibilities that in database may have bad data. The numbers are also stored in the string type. A very bad design, but when we got to working on these type of projects, we have to find a way to refine it and make it more reliable and efficient.] So, in the same code, just change the first parameter of PATINDEX from '%[0-9]%' to '%[a-z]%'. That's it. The expression change is what we need to do there. You can try with any expression as per your requirements and solve the problems.

Hope you like this post and still we need to know plenty of options already exists in technologies. Explore more and know more and save time.

label does not exist in current context


Error: label does not exist in current context


Scenario:
I have MyPage.aspx which have number of controls, it was working fine, till the point I made heavy changes. After making lot of changes to MyPage.aspx, when i tried to compile project, it started giving me error: label does not exist in current context. The problem here was my label control was there on .aspx page, but it was still giving me error at compile time.

Few things I tried which didn't worked

  • Try to switch design view and source view of MyPage.aspx
  • Tried to comment control and try to create same control again.
Cause of Issue:
I have notice even though label control was there on MyPage.aspx it was not their in MyPage.aspx.designer.cs. So there was something wrong with designer file.

Solution:
  • Delete designer file (Eg: MyPage.aspx.designer.cs)
  • Try to recreate designer file.
  • delete MyPage.aspx.designer.cs file, now right click on MyPage.aspx and select "Convert to web application" it will create new MyPage.aspx.designer.cs file.
  • At this point when I tried to create designer file i received error, unable to create designer file due to improper html. After i rectified html on MyPage.aspx and follow the same steps to create designer file, it have created MyPage.aspx.designer.cs
  • Finally my project gets compiled.

Moral of story
I figured out that VS.Net was giving weired error message. Even though label control was on MyPage.aspx it was throwing wrong error "label does not exist in current context". Appropriate error message would be something "Resolve improper html..." which would help me to figure out where exactly the problem is... "Don't trust on error message blindly"

Fix to Report viewer problems in IIS 7 or later

When we migrate web applications from IIS 6 to IIS 7 or IIS 7.5, we will face some problems in http handlers, mappings etc. I faced some problems with reportviewer control. So, below are all problems I have faced and solutions to them. And one more thing is, the server to which we migrated the application may or may not have all the report viewer dlls available in the system. If they didn't install then we need to install them. Otherwise you will get compilation error as we are using that in our application.


First of all, before proceed what are the dlls needed for the report viewer to run?
Microsoft.reportviewer.common.dll
Microsoft.reportviewer.processingobject.dll
Microsoft.reportviewer.webforms.dll
Microsoft.reportviewer.winforms.dll - For windows applications.

So, to get the dlls you need to install the redistributable packages for 2005/2008. Below are details to get that. Find the matched version[2005/2008] and isntall the correct patch. Once installed you will find all above dlls in the GAC.

Microsoft Report Viewer Redistributable 2008
File name : ReportViewer.exe
Version : 9.00.21022.08
Download Size : 2.8 MB

Microsoft Report Viewer Redistributable 2005
File name : ReportViewer.exe
Version : 2007
Download Size : 1.8 MB

Microsoft Report Viewer Redistributable 2005 SP1 (Upgrade)
File name : VS80-KB933137-X86.exe
Version : 1
Download Size : 1.7 MB

Microsoft Report Viewer Redistributable 2005 SP1 (Full Installation)
File name : ReportViewer.exe
Version : 1.0
Download Size : 1.8 MB

ReportViewer Samples for Microsoft Visual Studio 2008
File name : ReportViewerSamples2008.exe
Version : 1.0
Download Size : 172 KB

ReportViewer Samples for Visual Studio 2005
File name : ReportViewerSamples.exe
Version : 1.0
Download Size : 173 KB

With the installed patch, you can solve the compilation error. But, the report viewer control won't render correctly on the browser. What are the possible problems come?
  1. 'RSClientController' is undefined
  2. Report resource images are not coming or loading.
  3. RSParamaters not defined.
  4. ReportViewerHoverButton not defined etc...
  5. Other javascript errors which caused the report viewer failed to load correct.
The only fix to the problems are below.
Solution:
We need to configure the report viewer auto generated axd files[Reserved.ReportViewerWebControl.axd] in the IIS.
See below pictures to understand it well.
1. Open the IIS by typing the "inetmgr" in run command.
2. Goto your site in the list of web sites and select it as shown below.
3. Now, see the Features view area. Here, you can see all options available for the web site. From all the options select "Handler Mappings".
4. Now, click on the "Handler Mappings" section then you will see all the mappings applied for that web site. Now, on the right side panel, you are able to see all the options available for the handler mappings. Select the option "Add Managed Handler" as shown below.
5. When you click that link, you will see a popup window with the text boxes as shown below.
Fill, Path =
Reserved.ReportViewerWebControl.axd,
Type =
Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Name=
Reserved.ReportViewerWebControl.axd
Note: Please change the version number[9.0.0.0] in the Type above given depends on your requirement.
6. Click OK and do IISRESET.
Now, browse the page where you have report viewer control. And you see no more issues and everything renders fine. Hope this will help you to understand well and please let me know, if you have any questions or issues.

Date formatting in Sql server reporting services

When we work with reporting services, we come across with different requirements to display the date in different formats. So, we need to know the formats we can give to get required value. Sql server reporting services supports different formats as T-sql and C# does. So, I just want to give the valid formats I use to display the date in required format.

  1. =Format(Fields!DateCreated.Value, "M/d/yy") - 3/14/1986
  2. =Format(Fields!DateCreated.Value, "d-MMMM-yy") - 14-March-86
  3. =Format(Fields!DateCreated.Value, "MM/dd/yyyy") - 03/14/1986
  4. =Format(Fields!DateCreated.Value, "M/d/yyyy H:mm") - 3/14/1986 22:10
  5. =Format(Fields!DateCreated.Value, "dd-MMM-yyyy") - 14-March-1986
  6. =Format(Fields!DateCreated.Value, "MMM-dd-yyyy") - Mar-14-1986
  7. =Format(Fields!DateCreated.Value,"dd-MMM-yy") - 14-Mar-86

You can try different combinations of above to get desired output. Hope this helps and love to hear the comments

Installing FullText Search on SQL Server 2008

1. Download SQL Express with FullText Search capability for SQL Server 2008
http://www.microsoft.com/express/Database/InstallOptions.aspx


2. Select Installation Type as New Installation


















3 During Feature Selection, select Full-Text Search

















4. While Instance Configuration, Create new Instance Configuration.
- Select Named Instance and give new name. Example: I have given name: MyShriGanesh

















5. Main steps for installation are done, now simply press next with default choices and complete the installation.

6. After Installation login with new instance name created.
- Example: Earlier I have created named instance MyShriGanesh, so i need to login with same named instance in order to take benefit of FullText Search feature.
















7. Now, Create New Database, Run Tables and SPs Scripts and restore database with data. If you don't have one already,
download sample database and use that database.

After installation of sample database your object explorer will look like as follow:

















8. Open Query Window and type following command to test whether FullText Search is installed or not.

Select SERVERPROPERTY('IsFullTextInstalled')
If this query returns a value of '1' then the component is installed.

Now, lets go step by step to run Full Text Search on SQL Server 2008

Step 1: Creating Full Text Catalog in SQL Server 2008
Syntax:
Create FullText Catalog DatabaseNameCatalog

Example:
Create FullText Catalog AdventureWorksCatalog


Step 2: Create FullText Index in SQL Server 2008
Syntax:
Create FullText Index on TableName
(Column1, Column2, ...., ColumnN)
Key Index PK_TablesPrimaryKey on DatabaseNameCatalog
with Change_Tracking Auto
Note:
  • TableName is name of table you would like to create fulltext index.
  • ColumnName is column on which you would like to create fulltext index, it is column you would like to perform search on.
  • PK_TablesPrimaryKey is primary key of table you are creating on fulltext search index.
  • DatabaseNameCatalog is fulltext search catalog created earlier.
Example:
Create FullText Index on Production.ProductDescription
([Description])
Key Index PK_ProductDescription_ProductDescriptionID on AdventureWorksCatalog
with Change_Tracking Auto



Step 3: Running FullText Search Query
There are many different examples of running fulltext query, I would be giving 2 examples of fulltext search query.
Example 1: Using FreeText


Select [Description]
from Production.ProductDescription
Where
FREETEXT([Description], 'Entry Level Bike')


















Example 2: Using Contains
Select [Description]
from Production.ProductDescription
Where
Contains([Description], '"Entry" and "Level" and "Bike"')


















Example 3: Using Weight keyword

Select [Description]
from Production.ProductDescription
Where
Contains([Description],
'ISABOUT (Entry Weight(.8), Level Weight(.4), Bike Weight (.2))')






















Example 4: Using Inflectional keyword


Select [Description]
from Production.ProductDescription
Where
Contains([Description],
'FormsOf (INFLECTIONAL, Entry, Level, Bike)')















Monday, 16 August 2010

Difference between [Shared Function/Sub] V.S. [Function/Sub]

So if I am to create a class, what should I consider when deciding whether to make a method shared or not? Both ways seem to be capable of doing the same thing.
Code:
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

'shared member
txtShared.Text = SharedTest.ReturnString

'non shared member
Dim NST As New NOTSharedTest
txtNotShared.Text = NST.ReturnString
End Sub

End Class

Class SharedTest

Shared Function ReturnString() As String
Return "I am Shared"
End Function

End Class


Class NOTSharedTest

Function ReturnString() As String
Return "I am not Shared"
End Function

End Class

Saturday, 14 August 2010

Visual Studio 2010 All-in-One For Dummies

Visual Studio 2010 is a complete rewrite of the user interface, but it still has the familiar commands and tools from previous releases. Visual Studio 2010 provides a dizzying array of editors, controls, designers, and supporting tools for developing software. In addition to building traditional applications, you can use Visual Studio 2010 to build and manage solutions for SQL Server databases, SharePoint sites, Windows Workflow applications, BizTalk packages, and other enterprise server solutions.

Visual Studio 2010 Keyboard Shortcuts for General Development Environment

Visual Studio 2010 keyboard shortcuts for the general development environment increase developer productivity by allowing you to perform most common tasks without taking your hands off the keyboard.

Task You Want to PerformFeatureKeyboard Shortcut
Browse data typesClass ViewCtrl+Shift+C
Object BrowserCtrl+Alt+J
Edit codeFormat DocumentCtrl+K, Ctrl+D
Comment SelectionCtrl+K, Ctrl+C
Uncomment SelectionCtrl+K, Ctrl+U
Insert Code SnippetCtrl+K, Ctrl+X
Toggle OutliningCtrl+M
ExpansionCollapse to DefinitionsCtrl+M, Ctrl+O
Toggle Designer and MarkupShift+F7
View CodeF7
DebugStart DebuggingF5
Start without DebuggingCtrl+F5
Step IntoF11
Step OverF10
Toggle BreakpointF9
RestartCtrl+Shift+F5
Find and replaceFind SymbolAlt+F12
Quick FindCtrl+F
Quick ReplaceCtrl+H
Find helpContentsCtrl+Alt+F1
Context-sensitive helpF1
Display Visual Studio HelpCtrl+F1
Help Library ManagerCtrl+Alt+F1
SearchCtrl+Alt+F3
Manage project resourcesProperties WindowF4
Property PagesShift+F4
Data SourcesShift+Alt+D
Server ExplorerCtrl+Alt+S
Solution ExplorerCtrl+Alt+L
ToolboxCtrl+Alt+X
Add New ItemCtrl+Shift+A
Add Existing ItemShift+Alt+A
Build SolutionCtrl+Shift+B
Open files and projectsNew File WindowCtrl+N
New Project WindowCtrl+Shift+N
Open File WindowCtrl+O
Open Project WindowCtrl+Shift+O
Navigate windowsClose DocumentCtrl+F4
Close Tool WindowShift+Esc
Cycle DocumentsCtrl+F6
IDE NavigatorCtrl+Tab
Cycle Tool PanesAlt+F6



Visual Studio 2010 Technology and Terminology

Visual Studio 2010 and the .NET framework included their own terminology for these technologies. The following table includes definitions of some common terms you’ll encounter as you develop applications in Visual Studio 2010.

TechnologyDescription
AssemblyA file for physically storing data types, including the DLL
files where code is compiled
Base Class LibraryA set of managed code that enables developers to create Windows
and Web applications that target the Common Language Runtime
Common Language RuntimeA managed environment for running applications that prevents
memory leaks
Common Type SpecificationA set of rules for how programming languages use data
types
Garbage CollectionA feature of the Common Language Runtime that manages
memory
Global Assembly CacheA repository that stores public versions of assemblies
NamespaceA unique identifier for the logical organization of data
types

Common Visual Studio 2010 Item Templates

When working with projects in Visual Studio 2010, you’ll encounter a dizzying array of item templates to help you create your projects. The following table describes many of the common templates to help you along the way.

Item TemplateDescription
Application Configuration FileStores application settings for a Windows application
ClassEmpty class-definition file
Class DiagramModel of new or existing classes
Crystal ReportReport using Crystal Reports
DataSetStores data using DataSet Designer
HTML PageWeb page using HTML
Icon FileA Windows icon file
ReportReport using SQL Server Reporting Services
Settings FileXML configuration file
Site MapDescribes flow of Web pages in a Web application
SQL DatabaseEmpty database for storing local data
Style SheetCascading Style Sheet
User Control (WPF)Windows Presentation Foundation user control
User ControlReusable custom control
Web Configuration FileStores application settings for a Web application
Web FormUser interface for Web applications
Web ServiceCode file for a Web service
Windows FormUser interface for a Windows application
Windows Script HostA file containing script run as a Windows program
XML FileEmpty XML document
XML SchemaDescribes contents of an XML document
XSLT FileContains a stylesheet used to transform XML documents

Common Visual Studio 2010 Project Types

Visual Studio 2010 comes with many project templates to create the necessary boilerplate code and files you need to start developing applications. In the following table, you’ll find some definitions of project types to help you decide which is the right project template for your needs.

Project TypeDescription
Class libraryComponent library with no user interface
Console applicationCommand line application
Database projectSQL script storage
Device applicationWindows application for a smart device
Empty projectBlank project
SQL Server projectManagement of stored procedures and SQL Server objects
Web serviceASP.NET Web application with no user interface; technically, no
longer a project type
Web siteASP.NET Web application; technically, no longer a project
type
WindowsWindows application with a user interface application
Windows serviceWindows application with no user interface
WPF Browser ApplicationWindows Presentation Foundation browser application

Visual Designers in Visual Studio 2010

Visual Studio 2010 comes with many visual designers to make creating reports, designing classes, designing user interfaces, and modeling data extremely simple and intuitive. The following table lists each designer and describes what you create with it.

DesignerWhat You Can Do with It
Class DesignerModel classes using a class diagram
Crystal Reports DesignerCreate Crystal Reports reports
DataSet DesignerCreate typed DataSets
Project DesignerManage project settings in a centralized place
Report DesignerCreate SQL Server Reporting Services reports
Web FormsDesign user interfaces for ASP.NET Web sites
Windows FormsDesign user interfaces for Windows applications
XML DesignerCreate and edit XML schemas