.Net All About

.Net All About

How to configure SQL Server 2005 to allow remote connections?

To configure SQL Server 2005 to allow remote connections, complete all the following steps.

• Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
• Turn on the SQL Server Browser service.
• Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Enable remote connections for SQL Server 2005 Express

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.

2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.

3. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.

Note Click OK when you receive the following message:
Changes to Connection Settings will not take effect until you restart the Database Engine service.

4. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Service, click Stop. wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.

Enable the SQL Server Browser service

1.Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.

2.On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.

3.On the Surface Area Configuration for Services and Connections page, click SQL Server Browser, click Automatic for Startup type, and then click Apply.

Note When you click the Automatic option, the SQL Server Browser service starts automatically every time that you start Microsoft Windows.

4.Click Start, and then click OK.

Create exceptions in Windows Firewall

SQL Server 2005 uses an instance ID as part of the path when you install its program files. To create an exception for each instance of SQL Server, you must identify the correct instance ID. To obtain an instance ID, follow these steps:
1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
2. In SQL Server Configuration Manager, click the SQL Server Browser service in the right pane, right-click the instance name in the main window, and then click Properties.
3. On the SQL Server Browser Properties page, click the Advanced tab, locate the instance ID in the property list, and then click OK.
To open Windows Firewall, click Start, click Run, type firewall.cpl, and then click OK.

Create an exception for SQL Server 2005 in Windows Firewall
To create an exception for SQL Server 2005 in Windows Firewall, follow these steps:
1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe executable program, click Open, and then click OK.

Note The path may be different depending on where SQL Server 2005 is installed. MSSQL.1 is a placeholder for the instance ID that you obtained in step 3 of the previous procedure.
4. Repeat steps 1 through 3 for each instance of SQL Server 2005 that needs an exception.

Create an exception for the SQL Server Browser service in Windows Firewall
To create an exception for the SQL Server Browser service in Windows Firewall, follow these steps:

1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe executable program, click Open, and then click OK.

Hope this helps everyone.

December 19, 2009 Posted by | SQL, SQL Server 2005 | , , | Leave a Comment

Statement cannot appear within a method body. End of method assumed

Today when I was developing web pages using asp.net,I encountered a problem as below:
Server Error in ‘/BC30289 Application.

Compilation Error Description:
An error occurred during the compilation of a resource required to service  this request. Please review the following specific error details and modify your  source code appropriately.
Compiler Error Message:
BC30289:  Statement cannot appear within a method body. End of method assumed.

Error Line: Sub showImage(Byval id as string)
I replaced “<% %>” with

<script language=”vbscript” runat=”server”></script>

And then everything works fine.
That is because we cannot define asp ‘sub’ or ‘function’ between the body tag

Happy Programming

November 12, 2009 Posted by | .NET, Asp.net, HTML, JAVA SCRIPT | , , , , | 1 Comment

Multiple File Upload using JQuery

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.

Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

<head id=”Head1″ runat=”server”>
<title>Multiple File Upload using JQuery</title>
<script src=”Scripts/jquery-1.3.2.js”
type=”text/javascript”>
</script>
<script src=”Scripts/jquery.MultiFile.js”
type=”text/javascript”>
</script>
</head>

Step 2: Add File Upload Control & Button on the Page.

<asp:FileUpload ID=”FileUpload1″ runat=”server”
accept=”gif|jpeg|bmp|png|jpg”
maxlength=”5″ />
<br />
<asp:Button ID=”btnUpload” runat=”server”
Text=”Upload All” OnClick=”btnUpload_Click” />
<br />
<asp:Label ID=”lblMsg” runat=”server” Text=”">\
</asp:Label>

class=”multi” is used to specify that user can select multiple files.

maxlength property specify that user can upload maximum 5 files not more than that.

accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

protected void btnUpload_Click(object sender, EventArgs e)
{
if (ServerSideValidation() == true)
{
string SavePath, Msg = null;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
+ GetUniqueKey() + GetFileExtension(hpf.FileName);
hpf.SaveAs(Server.MapPath(SavePath));
//SavePath can be saved in DB.
Msg += GetFileName(hpf.FileName.ToString()) + ” , “;
}
}
lblMsg.Text = Msg + ” Uploaded Successfully.”;
}
}

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

private string GetFileExtension(string FileName)
{
char saperator = ‘.’;
string[] temp = FileName.Split(saperator);

return “.” + temp[1].ToString();
}

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a;

a = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890″;

chars = a.ToCharArray();

int size = maxSize;
byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);

foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}

return result.ToString();
}

This function help to get Filename from the filepath.

private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

private bool ServerSideValidation()
{
string errorMsg = string.Empty , temp=null;
bool errorFlag = true;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
temp = ValidateImage(hpf);
if(temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + ” has error : ” + temp;
temp = null;
}
}
}

if (errorMsg != “”)
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}

This function used to check file type & file size. If file is invalid than it will return error message.

private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;
int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
//Check Length of File is Valid or Not.
if (myFile.ContentLength > FileMaxSize)
{
msg = msg + “File Size is Too Large.”;
}
//Check File Type is Valid or Not.
if (!IsValidFile(myFile.FileName))
{
msg = msg + “Invalid File Type.”;
}
return msg;
}

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
{
bool isValid = false;

string[] fileExtensions = { “.bmp”, “.jpg”, “.png”, “.gif”, “.jpeg”, “.BMP”, “.JPG”, “.PNG”, “.GIF”, “.JPEG” };

for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;
}
}
return isValid;
}

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.
Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the &lt;head&gt; section of your page as shown below:

&lt;head id=”Head1″ runat=”server”&gt;
&lt;title&gt;Multiple File Upload using JQuery&lt;/title&gt;
&lt;script src=”Scripts/jquery-1.3.2.js”
type=”text/javascript”&gt;
&lt;/script&gt;
&lt;script src=”Scripts/jquery.MultiFile.js”
type=”text/javascript”&gt;
&lt;/script&gt;
&lt;/head&gt;

Step 2: Add File Upload Control & Button on the Page.

&lt;asp:FileUpload ID=”FileUpload1″ runat=”server”
accept=”gif|jpeg|bmp|png|jpg”
maxlength=”5″ /&gt;
&lt;br /&gt;
&lt;asp:Button ID=”btnUpload” runat=”server”
Text=”Upload All” OnClick=”btnUpload_Click” /&gt;
&lt;br /&gt;
&lt;asp:Label ID=”lblMsg” runat=”server” Text=”"&gt;\
&lt;/asp:Label&gt;
class=”multi” is used to specify that user can select multiple files.

maxlength property specify that user can upload maximum 5 files not more than that.

accept property used to restrict user to upload only certain type of file only.
Step 3: Double click on Upload Button & Write the code that is used to upload files.

protected void btnUpload_Click(object sender, EventArgs e)
{
if (ServerSideValidation() == true)
{
string SavePath, Msg = null;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i &lt; hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength &gt; 0)
{
SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
+ GetUniqueKey() + GetFileExtension(hpf.FileName);
hpf.SaveAs(Server.MapPath(SavePath));
//SavePath can be saved in DB.
Msg += GetFileName(hpf.FileName.ToString()) + ” , “;
}
}
lblMsg.Text = Msg + ” Uploaded Successfully.”;
}
}

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

private string GetFileExtension(string FileName)
{
char saperator = ‘.’;
string[] temp = FileName.Split(saperator);

return “.” + temp[1].ToString();
}

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a;

a = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890″;

chars = a.ToCharArray();

int size = maxSize;
byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);

foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}

return result.ToString();
}

This function help to get Filename from the filepath.

private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

private bool ServerSideValidation()
{
string errorMsg = string.Empty , temp=null;
bool errorFlag = true;

// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i &lt; hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength &gt; 0)
{
temp = ValidateImage(hpf);
if(temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + ” has error : ” + temp;
temp = null;
}
}
}

if (errorMsg != “”)
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}

This function used to check file type & file size. If file is invalid than it will return error message.

private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;
int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
//Check Length of File is Valid or Not.
if (myFile.ContentLength &gt; FileMaxSize)
{
msg = msg + “File Size is Too Large.”;
}
//Check File Type is Valid or Not.
if (!IsValidFile(myFile.FileName))
{
msg = msg + “Invalid File Type.”;
}
return msg;
}

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
{
bool isValid = false;

string[] fileExtensions = { “.bmp”, “.jpg”, “.png”, “.gif”, “.jpeg”, “.BMP”, “.JPG”, “.PNG”, “.GIF”, “.JPEG” };

for (int i = 0; i &lt; fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;
}
}
return isValid;
}

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!

November 7, 2009 Posted by | .NET, Asp.net, C#, JAVA SCRIPT | , , , | Leave a Comment

Text Box Enter Key in ASP.NET

One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.

In HTML or classic ASP pages is not hard to submit forms using the enter key on keyboard. Programmer use a to make a default button. If web site visitor click on that button or press enter key, the form will be submited.

Of course, you can have a more than one form on your page and individual submit button for every form.
You don’t want to submit a form with Enter key?

Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:

if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}

Common ASP.NET problems with Enter key

If you try to use Enter key in ASP.NET, according to your browser’s type, you can get really weird results. For example, try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:

Response.Write(“The button was clicked!”);

Now start debugging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button’s click event will not be executed.

Stop the debuging and place one more simple HTML textbox to the form. You will not write anything in this textbox, so you can even make it invisible. Just place it somewhere inside of your form tag.

Start debugging again. You cannot see the second textbox, and everything looks like before. Try again to write something in first textbox. If you press enter now, form will submit, and your code for button’s click event will now be executed. This is extremely different behavior, and you did nothing except you placed one invisible textbox on web form. :)

Maybe it is not best practice, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, or more than one text box with only one button, or many text boxes and many buttons with different code for each button, and all that on one form?

Different browsers have a different behavior in these cases. In case that you have more buttons, only first button will be “clicked” every time. So, we need some other approach to get an universal solution.

Enter Key in ASP.NET

One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.

In HTML or classic ASP pages is not hard to submit forms using the enter key on keyboard. Programmer use a to make a default button. If web site visitor click on that button or press enter key, the form will be submited.

Of course, you can have a more than one form on your page and individual submit button for every form.
You don’t want to submit a form with Enter key?

Rarely, you will need to disable an Enter key and avoid to submit form. If you want to prevent it completely, you need to use OnKeyDown handler on tag of your page. The javascript code should be:

if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}
Common ASP.NET problems with Enter key

If you try to use Enter key in ASP.NET, according to your browser’s type, you can get really weird results. For example, try to place one ASP.NET textbox and a button to the web form. Write a code on a OnClick event of a button. That could be something simple, like:

Response.Write(“The button was clicked!”);

Now start debugging and write something to textbox. If you press enter while focus is on textbox, form will submit, but your code for button’s click event will not be executed.

Stop the debuging and place one more simple HTML textbox to the form. You will not write anything in this textbox, so you can even make it invisible. Just place it somewhere inside of your form tag.

Start debugging again. You cannot see the second textbox, and everything looks like before. Try again to write something in first textbox. If you press enter now, form will submit, and your code for button’s click event will now be executed. This is extremely different behavior, and you did nothing except you placed one invisible textbox on web form. :)

Maybe it is not best practice, but placing invisible textbox could be simple solution for you if you have only one button on your web form. But, what if you have a different situation? What if you have a few buttons with only one textbox, or more than one text box with only one button, or many text boxes and many buttons with different code for each button, and all that on one form?

Different browsers have a different behavior in these cases. In case that you have more buttons, only first button will be “clicked” every time. So, we need some other approach to get an universal solution.

How to make a default button in ASP.NET

We need to specify exactly which button will be “clicked” when visitor press Enter key, according to which textbox currently has a focus. The solution could be to add onkeydown attribute to textbox control with this code:

TextBox1.Attributes.Add(“onkeydown”, “if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById(‘”+Button1.UniqueID+”‘).click();return false;}} else {return true}; “);

This line of code will cause that button Button1 will be “clicked” when visitors press Enter key and cursor is placed in TextBox1 textbox. On this way you can “connect” as many text boxes and buttons as you want.

Default buttons in ASP.NET 2.0 and ASP.NET 3.5

ASP.NET 2.0 makes this problems easier and introduce a concept of a “default button”. New defaultbutton attribute can be used with or control. What button will be “clicked” depends of where actually cursor is and what button is chosen as a default button for form or a panel.

———

In asp.net

We can use the Panel/Form Default Button Property to make the button to default press when we press the enter key..

For Panel in asp.net

<asp:Panel ID=”Panel1″ runat=”server” DefaultButton=”">
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:button ID=”btnDefault” runat=”server” Text=”Default Button Panel” OnClientClick=”btnDefault_Click” />
</asp:Panel>

 

for Form tag in asp.net

<form id=”form1″ runat=”server” defaultbutton=”btnDefault”>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:button ID=”btnDefault” runat=”server” Text=”Default Button Form” OnClientClick=”btnDefault_Click” />
</form>

 

After making the default button, press enter key on textbox you will notice that without pressing Button click events, btnDefault’s btnDefault_Click is fired.

 

Enjoy Programming

October 27, 2009 Posted by | .NET, Asp.net, C#, HTML, JAVA SCRIPT | , , , | 6 Comments

Open New Tab/Window (Response.Redirect open in new web page)

Hello Friends,
Here I am going to explain how to open new tab/window on Button click using asp.net.
A week ago, i have to implement that code. I have option to use javascipt windows.open to open new tab.
But I have to insert or update some database entry. Yeah i know that there is another way to use clientscipt in code behind to achieve this.
But in its simplest form, following code open new tab/window.

<asp:Button ID=”btnNewEntry” runat=”Server” CssClass=”button” Text=”New Entry” OnClick=”btnNewEntry_Click” OnClientClick=”aspnetForm.target =’_blank’;”/>

<%– aspnetForm.target =’_blank’ will add handler to open new tab–%>

protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect(”New.aspx”);
}

OR

Response.Write( “<script> window.open( ‘pageName.aspx’ ); </script>”);
Response.End();

// Here we can write javascript code to open new tab

——————–
Happy programming.

September 3, 2009 Posted by | Asp.net, JAVA SCRIPT | , , | 28 Comments

Call WebService using Javascript

TO call any webservice in javascript use following code…

<script>

function CallWebService()
{
PrintService.PrintCode(OnSuccess);
// here i m using PrintServer as webservice to print purpose

}

function OnSuccess(result)
{

document.getElementId(‘result’).value=result;
}

</script>

————————————————————
Following is my web service

public class PrintService : System.Web.Services.WebService
{
public static string strMyPrintCode = string.Empty;
public static string strOfferCode = string.Empty;

public PrintService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string PrintCode()
{
string strCode = GetRandomUniqueAlphaNumericCode(8, false);
strMyPrintCode = strCode;
return strCode; // return unique and random alphanumeric code
}

}
—————————
Notice where i m calling webservice…i m passing one argument when calling webservice method named PrintCode,
when call to webservice succeeded, Javascript function OnSuccess will be call.

You can also create one more function named OnFailure to notify failure of webservice

August 3, 2009 Posted by | Asp.net, JAVA SCRIPT | , | 1 Comment

How to detect browser using JavaScript

var isIE = false;
var isFF = false;
var isOP = false;
var isSafari = false;

function DetectBrowser()
{
var val = navigator.userAgent.toLowerCase();
if(val.indexOf(“firefox”) > -1)
{
isFF = true;
}
else if(val.indexOf(“opera”) > -1)
{
isOP = true;
}
else if(val.indexOf(“msie”) > -1)
{
isIE = true;
}
else if(val.indexOf(“safari”) > -1)
{
isIE = true;
}
}

July 1, 2009 Posted by | Asp.net | | 4 Comments

   

Follow

Get every new post delivered to your Inbox.