Friday, December 31, 2010

Some Sites which i frequently used

3) for create HTML form
4) -- basics tutorials
5) -- for apply captcha
6) -- Tools for documentation / development
7) -- create website
8) --create free website
9) -- create free social network and website
10) --Create E-commerce website
11) standards for health care websites
12) -- Online tool for create CSS online
13) -- Tool for create CSS online
13) A. -- Design a new button
14) -- Search for HTML entity codes for speacial characters
16) --What is the font used in the webpage
18) -- Create round corner box / div online
19) -- Create back ground image
20) b) -- Create Ajax loader gif.
22) --Share store fiels online but never used
27) -- Get ruler / scale for measure screen
28) --Edit / Create image online
b) Test the loading of webpage on browser
30) --Tutorials
31) -- Free Images
32) -- For Manage Projects, Bug, Docs,

Thursday, December 23, 2010

Null Coalescing Operator ??

For example, the myfunction whose return value may be a nullable int. In such cases, you can use the coalescing operator to quickly check if it is null and return an alternate value.

int myExpectedValueIfNull = 10;
int expectedValue = myfunction() ?? myExpectedValueIfNull

Add text in new line

In many time Email body, Message Box, we need to display text, or some time we need to display text starting in new line, we use \r\n for this purpose. but environment class having property of newline for example

string newline = string.Concat("1",Environment.NewLine,"2",Environment.NewLine,"3",Environment.NewLine,"4",Environment.NewLine,"5");
// Response.Write(newline);
showNewLine.Text = newline;

Mahesh K. Shama

OverCome of string.Split(char) limitation

String split method take chat as input, bur some time may be possible that this char added on string by user. so we need to add some combination of char for less possibility of this incident.

Example code is as follows :

const string DelimiterAndSpliter = "||";
string delimitedString = string.Concat("Str1",DelimiterAndSpliter,"Str2",DelimiterAndSpliter,"Str3",DelimiterAndSpliter,"str4", DelimiterAndSpliter,"str5");
string[] stringArray = System.Text.RegularExpressions.Regex.Split(delimitedString, System.Text.RegularExpressions.Regex.Escape(DelimiterAndSpliter));

Mahesh K Sharma.

What is Explicit and Implicit Interface Implementation

Yes, very much. Did you know other than the syntax difference between the two, there existed a fundamental difference.

Implicit interface implementation on a class would be a public method by default and is accessible on the class's object or the interface.

Explicit interface implementation on a class would be a private method by default and is only accessible through the interface and not through the class object unlike the implicit implementation. Yes, through this you can force you clients to use the Interface and not the objects that implement it.

public interface IMyInterface
void MyMethod(string myString);
public MyImplicitClass: IMyInterface
public void MyMethod(string myString)
public MyExplicitClass: IMyInterface
void IMyInterface.MyMethod(string myString)
MyImplicitClass instance would work with either the class or the Interface:
MyImplicitClass myObject = new MyImplicitClass();
IMyInterface myObject = new MyImplicitClass();
MyExplicitClass would work only with the interface:
//The following line would not work.
MyExplicitClass myObject = new MyExplicitClass();
//This will work
IMyInterface myObject = new MyExplicitClass();

Set Title Case

Hi ,
I need to display user name in title case. for example if user enter his first name as mahesh and middle name as kumar and surname as sharma than it should be display as "Mahesh Kumar Sharma".. irrespective of users enter format.
so i need a function which set the initial character of word in large. abc xyx def tuv

ChangeToTitleCase("abc xyx def tuv") should be return Abc Xyz Def Tuv.

The body of function is as follows :

private string ChangeToTitleCase(string inputText)
return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase((inputText?? string.Empty).ToLower());

Mahesh K Sharma

Friday, December 17, 2010

How to download any content from server.

for download any content you need to redirect to other page.
sya downloadContent.aspx?FileName="UniqueNameOfContentAsonServer.exe"&Name="NameWhichYouwantToShowInDownloadDialogBox"

call following function on page load event. :)

private void DownlaodContent()
if (Request.QueryString["FileName"] == null || Request.QueryString["Name"] == null)
string _filePath = "";
System.IO.FileInfo _targetFile = null;
_filePath = Server.MapPath( Request.QueryString["FileName"].ToString());
_targetFile = new System.IO.FileInfo(_filePath);
if (_targetFile.Exists)
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString["Name"].ToString());// + ".txt");
Response.WriteFile(_targetFile.FullName, true);
//_targetFile.Delete(); If you want to delete phycally after download a image

catch (Exception ex)

// Error logging as per existing application.
_targetFile = null;

Mahesh K. Sharma

Show default div instead of default tooltip with controls !!!

For this we have text in title attribute of controls so we have to create a div on mouse over and hide on mouse out event. So we can create a function and call this fuction with desired controls.

In this fucntion we must have customized div propery say color etc. and we can use fade funcions of jQuery

this function is follwos :

(function($) {
$.fn.tooltip = function(options) {

defaults = {
background: '#fffdf0',
color: 'black',
rounded: true

settings = $.extend({}, defaults, options);

this.each(function() {
var $this = $(this);
var title = this.title;

if ($this.attr('title') != '') {
this.title = '';
$this.hover(function(e) {
// mouse over
if ($this.children("div[tooltip]").length < 1) {

.html(title)//If we want to show decorate text with HTML styles
//.text(title)//If we need to show simple text
backgroundColor: settings.background,
color: settings.color,
top: e.pageY + 10,
left: e.pageX + 20


else {


if (settings.rounded) {
}, function() {
// mouse out

$this.mousemove(function(e) {
top: e.pageY + 10,
left: e.pageX + 20

// returns the jQuery object to allow for chainability.
return this;

We have to call this function :)

[script language="javascript" type="text/javascript"]
$(document).ready(function() {



Where "a" in control type and it It will apply only in div SectionOfPage.

Mahesh K. Sharma

How to enable accept button when user complete crolled down than message

function checkScrollPosition(divFrame)

if (divFrame.scrollHeight - divFrame.scrollTop + 17 - divFrame.offsetHeight < 50) {
document.getElementById('<%=ButtonAccept.ClientID%>').disabled = false;
document.getElementById('<%=LabelScrollMessage.ClientID%>').style.display = 'none';


Mahesh K. Shamra

How to Create common javascript custom validator

If in update panel
ScriptManager.RegisterExpandoAttribute(CustomValidatorTextBoxDOB, CustomValidatorTextBoxDOB.ClientID, "Date", TextBoxDOB.ClientID, false);
in in page
Page.ClientScript.RegisterExpandoAttribute(CustomValidatorTextBoxDOB.ClientID, "Date", TextBoxDOB.ClientID, false);


function ClientValidate(sender, arguments)
arguments.IsValid = false;
return false;


protected void DateValidate(object source, ServerValidateEventArgs args)
args.IsValid = CommonClass.ValidateDate(args.Value);

How to localize with master page dropdown

1) Add followoing code on index change event of Master page Dropdown

protected void DropDownListSelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
Session["Culture"] = DropDownListSelectLanguage.SelectedValue;

2) Create a base class and inherit the content pages with it or call fuction on contents page
InitializeCulture() envet.

protected override void InitializeCulture()


if ((Session["Culture"] != null))
LanguageCulture = Session[EMDMCConstants.SessionCulture ].ToString();
if (LanguageCulture != "0")
Thread.CurrentThread.CurrentUICulture = new CultureInfo(LanguageCulture);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(LanguageCulture);


catch (Exception ex)
string _customException = "###Class Name - BaseClass.cs Source Function Name -InitializeCulture, ParameterCount - 0###";
LogManager.SetException(ex, null, _customException);

throw ex;



3) Do not forgot to add resx files of same page for this you can take reff of any site.

Regulare Expressions

USER Name:
Accept username, user_name, username_123,
Not accept user name, 123Username, _username,

ControlToValidate="TextBoxUserId" Display="None" SetFocusOnError="True"runat="server" ErrorMessage="Invalid User name"meta:resourcekey="REVUserNameResource1">

Display="None" SetFocusOnError="True" ValidationExpression="(?!^[0-9@,|()[\]{}#.$%&_'*+:;^`'~?=!-]*$)(?!^[a-zA-Z@,|()[\]{}#.$%&_'*+:;^`'~?=!-]*$)^([a-zA-Z0-9@,|()[\]{}#.$%&_'*+:;^`'~?=!-]{6,25})$"
ControlToValidate="TextBoxPassword" meta:resourcekey="RegularExpressionValidator5Resource1">

Accept New yourk not accep numaric,special characters

ValidationExpression="^[a-zA-Z\s]{1,40}$" runat="server" Display="None" ErrorMessage="Enter Only Character"

ErrorMessage="Enter Valid Blood Group." Display="None" runat="server"

ErrorMessage="Can't upload exe or msi" Display="None">
Display="None" ErrorMessage="Limit Exceed"
SetFocusOnError="True" ValidationExpression="(.|\r|\n){0,10}">

// valid date format for exp (mm/dd/yyyy )
//This R.E used for validate date with leap year I used this in javascript :
var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
if(EntredDate.match(RegExPattern) == null)//If entred date is not matched then show message
arguments.IsValid = false;
return false;//show error message

How to save session after Directory.Delete() method.

use out proc session
Paste following code on global.asax page

<%@ Import Namespace="System.Reflection" %>

void Application_Start(object sender, EventArgs e)
// Code that runs on application startup

//Preventing sessions after delete folder
PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
object o = p.GetValue(null, null);
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
object monitor = f.GetValue(o);
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
m.Invoke(monitor, new object[] { });

Mahesh K. Sharma

Set The defalut button of a form

Page.Form.DefaultButton = ImageButtonCompleterOrder.UniqueID

When to Use RegisterStartupScript & RegisterClientScriptBlock in code.

Assume you have a control named "TextBox1" in aspx file, and its value is "2"
also, you have a javascript function called "ShowValue" which will alert the value of TextBox1.
so, your aspx file like this:

[title]Untitled Page[/title]
ShowValue = function()
[form id="form1" runat="server"]
[asp:TextBox ID="TextBox1" runat="server" Text="2"][/asp:TextBox]

now, in server-side, at Page_Load method, you set value of "TextBox1" to "9" and call "ShowValue" from server.


TextBox1.Text = "9";
Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "ShowValue()", true);

that is.

The RegisterClientScriptBlock method adds a script block to the top of the rendered page.

while, the script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised.
(it means the RegisterStartupScript method adds a script block to the end of the rendered page.)

Mahesh K. Sharma

How to set the focus on controls when ajax toolkit modal popup comes true

1)In which control you want to focus set this as behaviour id of modalpopup
2)use this code block
In following example we set the focus on emergency code text box.

if ((!Page.ClientScript.IsStartupScriptRegistered("Startup"))) {
StringBuilder sb = new StringBuilder();
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sb.ToString());

Mahesh K. Sharma

How to add buttons for fullpost back in gridview while using update panels

Add following code on row_databound

ImageButton ImageButtonDocumentDownLoad = (ImageButton)e.Row.FindControl("ImageButtonDocumentDownLoad");

ScriptManager scriptManager = ScriptManager.GetCurrent(this);

//If grid view in user control

ScriptManager scriptManager = new ScriptManager();

Mahesh K. Sharma

Tuesday, April 20, 2010

How to prevent duplicate record instertion on Page referesh,considering i dont have any primary key.

Hello Everyone,

Suppose I had Inserted one record, Now, when I refresh Page same record is inserted again though I had cleared all the textboxes after insertion. How can i avoid this???

For This you to put the following code

protected void Page_Load(object sender, EventArgs e)

if (!Page.IsPostBack)
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());

protected void btnSubmit_PreRender(object sender, EventArgs e)
ViewState["update"] = Session["update"];

protected void btnSubmit_Click(object sender, ImageClickEventArgs e)

if (Session["update"].ToString() == ViewState["update"].ToString())
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());

//Write your Insert Code.



Thank you.
Sanjeev Kumar