Wednesday, September 9, 2009

Restore SQL Server Database

Backup and Restore operation on any database is a common operation. Some times it becomes very tedious when not handled properly.
There are some points that needs to be kept in mind while restoring a database. Here i am providing the code for restoring SQL Server Database from C# Code.

While restoring Database use should keep in mind that, only one user is using the Database, what i mean to say is Database should be in SINGLE_USER Mode.

you need to fire this SQL Command before Restre

ALTER DATABAES DatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

this will make the Database in SINGLE_USER Mode and as soon as the Restore process is complete, it will automatically set back to MULTI_USER Mode.

Below is the Code For restoring the Database.

Make following declerations

using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

if Required make reference to
Microsoft.SqlServer.Smo


Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem("BackupFile", DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = "DatabaseName";

//ConnectionString Just make the connection with the Server
//I.E. without providing Initial Catalog Value

SqlConnection sqlCon = new SqlConnection(ConnectionString);
ServerConnection connection = new ServerConnection(sqlCon);
Server sqlServer = new Server(connection);

Database db = sqlServer.Databases["DatabaseName"];
sqlRestore.Action = RestoreActionType.Database;
sqlRestore.ReplaceDatabase = true;

sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.PercentCompleteNotification = 1;
sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
sqlRestore.Information += new ServerMessageEventHandler(sqlRestore_Information);

sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases["MEDICALDATABASE"];
db.SetOnline();
sqlServer.Refresh();

this Code Restore backup database.
also one thing that needs to remember is that, the Backup file must be on the Server machine where you have Installed the SQL Server.

Check yourself....

Thursday, July 9, 2009

Swaping two values without using any third variable

Hello,
many times in interviews, A quesion is being asked that "How to swap two values with out using thrid variable".

We know how to swap using thrid vaiable i.e.
a=10;
b=20;
c=0;

c=a;
a=b;
b=c;

Now, if you want to swap two string variables without using third variable use

string A= "string A";
string B= "string B";

A+=b;
B = A.substring(0,A.Length-B.Length);
A = A.substring(B.Length);

in order to swap two integer values you can do the same as

int a = 10;
int b = 20;

A = A+B;
B = A-B;
A = A-B;

OR

A = A ^ B;
B = A ^ B;
A = A ^ B;

but there are exception in using the first option in swaping integer values. second will always give you the result, but sometimes first will result in over/under flow.

check it yourself.

Friday, June 26, 2009

MultiLingual (in different speaking languages) support in your .NET Application

I am supporting a project which is in market, developed by our company. All of a sudden our client appeared and asked for multi-language support for the software. i was very much confused on how to deliver that. But later i found that with the Help of VS.NET it is very much easy to deliver any application with multiple language support.

So, i decided to write this article on my blog about how to create a Multilingual application using .NET, and also what to consider while developing a Multilingual application.

selection of the database is one of the factor for saving data as user has entered. MS SQL Server is one of the option that can be used, as the developement evvironment is Windows and we are using VS i suggest SQL Server 2005 or above as a better option.
SQL Server provides to dataTypes nvarchar and nchar which can used to store data in different language format.

inorder to use the Localization in your application make reference to two namespaces

System.Threadig and System.Globalization

Globalization is the namespace that provides feature for setting the Current Cultur as per user desire.

when you go for localization you should alos consider the input language what i mean to say is that if your providing your application in french language then you should proivde provision for inputing data in french language.

inorder to provide the facility of inputing data in specific language you must have those languages installed if not you can install them. if you can install languages from
Start->Settings->Control Panel->Regional and Language options
Select Language Tab -> Select Details there you can see the list of languages installed and you can add New languages.

for my example i am checking for french language installed on my machine
foreach(InputLanguage Language in InputLanguage.InstalledInputLanguages)
{
if(Language.LayoutName=="French")
{
InputLanguage.CurrentInputLanguage = Language;
break;
}
}

Now lets create Step-by-Step Application for US and French Language
step 1. Create a Blank Windows Applciation.
step 2. Select Form1 that is your default Form, make its Localizable property to true and make its Language property to default, which is already by default.
step 3. Drag and drop a button on the form and set its Text property to "Click Me", Save the application
step 4. Select Form1 and Set it Language property to French (France)
step 5. Select button1 set its Text Property to "Cliquez-moi"
step 6. Save and build your application.
step 7. press F5 to run the application, you will find the button displaying the button1 text as "Click Me" it is because your default language is "US" you need to change the Culture. Inorder to do that, Add following code before callingInitializeComponent();

Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
and then press F5 you will see your application displayed French language.

The main magic behind is the resource file that VS studio creates when you set the Language option for your form. Go to Solution explorer and click on Show All Files you will find file named form1.fr-FR.resx double click on it. see the content VS has created mapping data for you. Whenever you change your Culture info your application will look for appropriate file. If found it will look for the actual data and will display the mapped data. If it is not found it will display the default language i.e. "US"

Tuesday, June 16, 2009

Get Distinct value from an ArrayList

int[] Arr = { 1, 2, 1, 24, 25, 1, 5, 5, 8, 7, 96, 3, 8, 4, 12, 45, 8, 6, 9, 5 };
ArrayList Array = new ArrayList(Arr);
Hashtable ht = new Hashtable();
foreach (int item in Array)
ht[item] = null;
ArrayList AList = new ArrayList(ht.Keys);

Friday, April 10, 2009

A Simple password generator

Here is a simple password generator.
there is nothing special in this code, i have just used the Random class in C# to generate random number and some range of character from Character Array, below code illustrate is more easily.

public string GetRandomPassword(int numChars , int seed)
{
string[] chars = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2" ,"3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N","O","P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z" };

Random rnd = new Random(seed);
string random = string.Empty;
for(int i = 0 ; i < numChars ; i++)
{
random += chars[rnd.Next(0 , 62)];
}
return random;
}

Call to the Method above

Random random = new Random();
string Password = GetRandomPassword(15 , random.Next(100000))); //15 character long password

Wednesday, April 8, 2009

Late binding in C#

There are situations where some time it is viable to go for late binding.
though it is a tedious to perform and also needs carefull overall programming.

I was working on a project where clients were continious asking for new changes and want in Auto updates and at that time found late binding better for the situation.

Though early binding is considered as better option than late binding, but late binding has its own benefits. Late bind is most of used for generic object which needs to be known a run time.

in order to illustrate i have created of class library called Calculation which contains Calculate Class. code of that is below:


using System;
using System.Collections.Generic;
using System.Text;

namespace Calculation
{
public class Calculate
{
public Calculate()
{
}

public Int64 Add(Int64 Value1 , Int64 Value2)
{
return Value1 + Value2;
}

public Int64 Multiply(Int64 Value1 , Int64 Value2)
{
return Value1 * Value2;
}
}
}


in order to use this Calculation.dll at run time don't don't make a reference to Calculation.dll. i have placed the dll on the Startup path of my test application.
code for that is listed below:
do not forget to make a reference to System.Reflection

private void button1_Click(object sender , EventArgs e)
{
Assembly assemblyinfo = Assembly.LoadFile(Application.StartupPath+@"\Calculation.dll");
Type[] types = assemblyinfo.GetTypes();

foreach(Type type in types)
{
MethodInfo[] MI = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
object Latebind = Activator.CreateInstance(type);
MessageBox.Show(MI[0].Invoke(Latebind , new object[] { Convert.ToInt64(textBox1.Text),Convert.ToInt64(textBox2.Text)}).ToString());
}
}

here MI[0] referes to Add Method.
you can check the Method order by itterating through MI object

Friday, April 3, 2009

FTP Upload/Download using C#

Here is a very simple method for uploading and downloading files from FTP server.
you need to have FTP Host Name and UserName and Password for Authentication credentials

Make a reference to System.Net

DownLoad:

//Filepath is the path to your local machine where you want to download the file
//Filename is the name of the file which you want to download from FTP Server
private void Download(string filePath, string fileName,string UserName,string Password)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtPath.Text + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(UserName,Password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];

readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}

ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Upload:

//Filename is the file from your local machine to upload
private void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = FTPPath+ "/" + fileInf.Name; //FTPPath points to the directory on FTP Server where you want to upload file
FtpWebRequest reqFTP;

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(txtUserName.Text, txtpassword.Text);
reqFTP.KeepAlive = false;

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;

reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}

Hope this will be helpful to you. some of codes i have taken from Code Project

Wednesday, January 28, 2009

Download Any File using ASP.NET

Very recently i have been shifted to ASP.NET programming. In the beginning i was facing a lots of problem. but now, I find myself bit comfortable with this.

i am providing a simple code for downloading any file from Web Server located in any directory on the Web Application folder.

make a reference to System.IO, and check that your web application has rights for Read/Write/Modify/Execute permission on the folder where you have placed all the files that you want your users to download.

FileStream fstream = new FileStream(Server.MapPath("FileToDownload"), FileMode.Open);
string file="";
file = "PrivacyPolicy.pdf";
byte[] bytBytes = new byte[fstream.Length];
fstream.Read(bytBytes, 0, (int)fstream.Length);
fstream.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + file);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(bytBytes);