Handling new line and carriage return with Textbox

Introduction

Handling newline and carriage return with Textbox while working with Databases.

The Scenario

If any data contain new line or carriage return or both, while displaying on input box, the data after these characters will not come. Though we can use TextArea for such type of data, sometime such situation comes in an unavoidable way.

In some case we need to refer to some external database and populate data depending on some predefined criteria for our further processing and submit them to another database. In such case, if we are using text box for the fields, we need to handle the newline and carraiage return characters in different way.

The GUI:

Searching and Populating the Data:

In some case we need to refer to remote database (external) and populate the data from that database depending on some predefined criteria for our further processing.

//Inside the loop of reading the records from DataReader

.

.

strEmpID = . . . ; //get the Emp ID

strName = . . . ; //get the Name

strAddress = . . . ; //get the Address

//Replacing the \n and \r with respective value to display

strAddress = strAddress.Replace("\n","\\\\n");

strAddress = strAddress.Replace("\r","\\\\r");

//strAddress can be use now for displaying

//Making the complete data for passing to the js Function for populating

//strData will used for populating the data in the input box

strData = strEmpID + "|" + strName + "|" + strAddress ;

.

.

//Now build up the java Script

strJScript = strJScript + " + strEmpID + "\" onClick="return setValues('" + strData + "');"

// setValues(strAdd) : This function will populates the data in the TextBox

.


.

Search then populated by clicking the radio button:

Submitting the data:

Before submitting the data to the dataset, we need to revert back our changes. We will replace '\\n' by (char)10 and '\\r' by (char)13.



.


.


strAddress = ReplaceForNewLineChar(strAddress);


strAddress = ReplaceForCarriageReturnChar(strAddress);


.


.

The replacement Algorithm:

public string ReplaceForNewLineChar(string strInput)

{

int tmpCounter = 0;

string strTmp1 = "";

string strTmp2 = "";

tmpCounter = strInput.IndexOf("\\n");

if (tmpCounter == -1)

{

return strInput;

}

else

{

strTmp1 = strInput.Substring(0,tmpCounter);

strTmp2 = strInput.Substring(strTmp1.Length + 2 ,strInput.Length

-(tmpCounter+2) );

strTmp1 = strTmp1 + (char)10 + strTmp2;

return ReplaceForNewLineChar(strTmp1);

}

}

public string ReplaceForCarriageReturnChar(string strInput)

{

int tmpCounter = 0;

string strTmp1 = "";

string strTmp2 = "";

tmpCounter = strInput.IndexOf("\\r");

if (tmpCounter == -1)

{

return strInput;

}

else

{

strTmp1 = strInput.Substring(0,tmpCounter);

strTmp2 = strInput.Substring(strTmp1.Length + 2 ,strInput.Length

-(tmpCounter+2) );

strTmp1 = strTmp1 + (char)13 + strTmp2;

return ReplaceForCarriageReturnChar(strTmp1);

}


}

DataSource controls in .NET 2.0

Introduction

In this article, we're going to learn how to connect a database for querying data and binding the result set to ASP.NET controls in a very easy way with no looping or control manipulation required, thus avoiding writing any data source code.

DataSource control is doing the work for me

DataSource is defined as ASP.NET controls that manage the tasks of connecting to a data source and reading and writing data. Data source controls do not render any user interface, but instead act as an intermediary between a particular data store (such as a database, business object, or XML file) and other controls on the ASP.NET Web page. It's acting as our business entities' placeholder in the application logic. The data source controls include any control that implements the IDataSource interface.

The .NET Framework includes the following data source controls:

  • ObjectDataSource. It enables you to work with a business object or other class and create Web applications that rely on middle-tier objects to manage data.
  • SqlDataSource. It allows you to connect to any data source that has an ADO.NET data provider (Microsoft SQL Server, OLE DB, ODBC, or Oracle).
  • AccessDataSource. It enables you to work with a Microsoft Access database.
  • XmlDataSource. It enables you to work with an XML file.
  • SiteMapDataSource. It is used for our site navigation.

Using a DataSource control in a Web application is fairly simple. Open a Web Form, and then, from the Toolbox at the Data tab, drag and drop a DataSource control to the form. This object represents business entities persisted in any storage medium which uses ADO.NET providers. Now, we must configure the control.

Click on the little icon, at the upper right corner for executing a configuration wizard which allows picking up a database connection according the actual connection strings in the connectionStrings section of the Web.config file (listing 1.) for query information and objects schema and writing Sql statements or defining store procedure calls for select, insert, update and delete commands. If you're using parameters, the configuration wizard presents a window for mapping some input information to these parameters. Parameters are always indicated with an @ symbol, as in @Region (listing 4.). You can define as many symbols as you want, but you must map each provider to another value. In this example, the value for the @Region parameter is taken from the ddlRegions.SelectedValue property of the DropDownList Control. (listing 4.)

The .NET Framework includes the following parameters:

  • Control property: A map to property value from another control on the page.
  • Query string: A map to a value from the current query string.
  • Session state: A map to value stored in the current user's session.
  • Cookie: A map to a parameter that can be used to bind to the value of a session variable.
  • Profile: A map to a value from the current user's profile.
  • Form variable: A map to a value posted to the page from an input control. Usually, you'll use a control property instead, but you might need to grab a value straight from the forms collection if you've disabled view state for the corresponding control.

There are some drawbacks associated to DataSource controls.

  • Data access logic is embedded in the page, so it's difficult to change issues for tuning or profiling after the application deploying.
  • Some code is duplicate because you have several DataSource control per page sometimes they have the same Sql statement.
  • Lack of flexibility because every Sql statement has separate DataSource, so if you want to provide different views for the data is very complicated.

I develop a little program for explanatory purpose.

Listing 1 is the configuration of the Web Application.

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<
connectionStrings>
<
add name="NorthwindConnectionString "
connectionString="Data Source=localhost;Initial Catalog=Northwind;
Integrated Security=SSPI"/>
connectionStrings>
...
configuration>

Listing 1. Web.config

Listing 2 is the code for the configuration of SqlDataSource1 object which is querying the database Northwind for gathering all Region which maps to current customers.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="select distinct Region from dbo.Customers">asp:SqlDataSource>

Listing 2. Form1.aspx

In listing 3, DropDownList WebControl binds all data of SqlDataSource1 which allows the customer to pick up a region. Notice that this control is able to do a postback action.

<asp:DropDownList ID="ddlRegions" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Region" AutoPostBack="True">

asp:DropDownList>

Listing 3. Form1.aspx

When you select a Region, a postback action is triggered, and the second data source retrieves all the customers in that region using the ddlRegions.SelectedValue as parameter for the query. Here's the definition for the second data source in the listing 4.

<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="select CustomerID, ContactName, Address, Country from dbo.Customers where Region=@Region">

<SelectParameters>

<asp:ControlParameter ControlID="ddlRegions" Name="Region" PropertyName="SelectedValue" />

SelectParameters>

asp:SqlDataSource>

Listing 4.

And finally in the listing 5 is the code for the configuration of the GridView control which binds the data from SqlDataSource2 in the Web Form for showing the group of customer associated to the selected region.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource2">

<Columns>

<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
SortExpression="CustomerID" />

<asp:BoundField DataField="ContactName" HeaderText="ContactName"
SortExpression="ContactName" />

<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />

<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />

Columns>

asp:GridView>

Listing 5.

Conclusion

This is an explanatory article for showing how to use another easy model of data access developed by the Microsoft.NET architects.

Outlook Style Menu with Collapsable Side Menu


Introduction

I have read an article at http://www.codeproject.com/useritems/XPMenu.asp which explains the dropdown XP style menu.

Just I would like to add new features,

  1. Collapsable side menu.

  2. Change the XP style menu in to Outlook style bar.(Using CSS File "SlideMenu.css")

I think that most developers suffer from the problem of the design of the menu, needs thier application GUI like Outlook or XP Style,

Therefore I think that this menu will provide solution to their problem.

Source code contains

  • SlideMenu.css file
  • menu.js file

Import Css file in your page

<LINK href="SlideMenu/images/SlideMenu.css" type="text/css" rel="stylesheet">

Collapsable side menu feature permit to hide side menu from page as a client script

Hide menu function:

<script type="text/javascript">

function lefthide()

{

var fr = parent.document.getElementById("sbCont");

if(fr.style.display=="")

{

fr.style.display="none";

change('outlookside', 'outlookBarExpand')

}

else

{

fr.style.display="";

change('outlookside', 'outlookBarcollapse')

}

}

function change(id, newClass)

{

identity=document.getElementById(id);

identity.className=newClass;

}

script>

I hope that I have succeeded in making this article and I wish to be useful to others.

Multiview Control in ASP.NET 2.0

One task common to web applications is data collections. For example one may need to collect some information from the end user, as in some sort of registration or some survey process. A rated good practice has been to often split the questions across multiple pages, so that the end user doesn't have jitters scrolling down the pages and by seeing the number of questions he/she would be made to answers. After all who likes to answers questions!!!

ASP.Net1.x offered developers to accomplish this by using panels and then selectively hiding and unhiding a set/group of controls. Or the way around was to create separate pages altogether, which sometimes became too cumbersome. ASP.Net2.0 offers the all new Multiview control to takes out the drudgery of creating multiple pages and thereby making life easier for the developers.

How To Do That?

Drag the Multiview control (located in the Standard Tab) from the toolbox onto the form, and drag two more view controls onto the Multiview. Populate the two view controls as shown below in the figure.

Multiview Control in ASP.NET 2.0

In the properties for the Multiview control set the ActiveViewIndex = 0. This means that view1 will be shown by default when the page gets loaded. All the views appearing in the Multiview control are a part of the view collection which itself is a part of the Multiview control. So by setting the ActiveViewIndex to 0 we make the first view (zeroth in the collection) to be the default view.

To add some functionality to the Next button (btnNext) double click button in the design view, and Visual Studio2005 generates the event for you in the code-file (Multiview.aspx.cs, in my case). Add the following code to the generated event: -

MultiView1.ActiveViewIndex += 1; //Make view2 as the next visible view

In the above code we are making the ActiveViewIndex of the Multiview to be 1. This is to make view2 visible, and hide view1.
Similarly double click the Back button (btnBack) and add the following line of code to the generated event:-

MultiView1.ActiveViewIndex -= 1; //Make view1 to be visible again.

Similar to the code for btnNext click event, here also we have set the ActiveViewIndex to -1, to make view1 visible and hide view2 on clicking btnBack.

The above is just some very elementary code written for illustrative purpose. Complex business logic can be written in a similar way. And any number of views can be added to the Multiview control, suiting to ones individual requirements.

Seeing It Work, Finally!!

Hit the F5 key on your keyboard to run the sample, and to see it work in completeness.

Multiview Control in ASP.NET 2.0

Multiview Control in ASP.NET 2.0

Visual WebGui application

Introduction

While web development environments such as ASP.NET and JSP have made huge strides in creating a rich environment for developing web applications, they have always targeted a very wide range of applications from content rich sites to OWA like applications. By doing so, they forced a compromise that was very painful for applications developers. Concepts like pages, html, requests and responses, which originated from the historical evolution of web development, are not really suitable for developing applications. While AJAX frameworks such as Atlas make a very nice edition to those enviroments they are still based on web development concepts which adds a great deal of complexity over desktop development concepts.

  • Download Visual WebGui SDK - 1.08Mb
  • Visual WebGui web site.

WebGui application

Background

Visual WebGui is a new AJAX framework that took a different approach to web application development, specially designed to simplify building highly complex applications like Outlook Web Access (OWA). Visual WebGui makes it possible for developers to create web applications by using full WinForms server side API that includes design-time capabilities. By adopting the WinForms object module and development concepts Visual WebGui has completely simplified the development of web applications. Alowing you to program as a VB/WinForms programmer and not as a web programmer makes much more sense when developing web applications like Outlook Web Access.

Visual WebGui is completly free to use and deploy for non-commercial purposes and is will also be available as an open source project in SourceForge.net. The Visual WebGui site has multiple free license that you can apply to inorder to use it freely in your production site

This article creates a fully AJAX enabled incremental explorer application browsing the wwwroot directories on the left pane and on the right pane the current selected folder files are displayed.

Using the code

In order to start developing Visual WebGui you need to download the SDK from the Visual WebGui download page. The installation will install a couple of assemblies to your GAC adding the Visual WebGui capabilities to your development enviroment. Installing the Visual WebGui SDK will add a two new projects to your Visual Studio (WebGui Application and WebGui Control Library). The WebGui Application project will create you a ASP.NET new project that one class named Form1.cs instead of the WebForm1.aspx file usualy created by the ASP.NET project template. Inheriting from the Gizmox.WebGUI.Forms.Form class the Form1.cs automaticly causes this file to have a WinForms like design time behavior. When you enter the design surface of the Form1.cs class you will have an aditional WebGUI toolbox available in the toolbox pane. These components can be draged to the design surface and be used exactly as WinForms components are used on a WinForms design surface. In the properties pane of any givven component you can change the component attributes including layout properties such as Dock and Anchoring which are WinForms way of layouting components and are fully supported by Visual WebGui.

Before you can run your application you need to have your form registerd in Visual WebGui web.config configuration section to a virtual page and have Visual Studio start page set to this virtual page. Visual WebGui uses a ".wgx" IIS script map extension that needs to be added to the IIS with the same definitions as the ".aspx" script map extension but without the check file exist check box as Visual WebGui uses virtual pages mapped to Gizmox.WebGUI.Forms.Form inherited classed. After setting these configurations you can start debugging your application exactly as you debug a WinForms application.

Step 1 - Creating a new WebGui Application project

Open the new project dialog and select the WebGui Application project. In the project name textbox enter WebGUIExplorer and press OK.

WebGui application

Visual WebGui will create you a new WebGui Application project that is both ASP.NET and WinFroms, as the structure is that of ASP.NET and the form classes behave like a WinForm form forms. Double clicking the Visual WebGui form1.cs page will open the design surface that is exactly the same as the WinForm design surface. The Visual Studio tool box has an added pane named WebGUI and you can find there Visual WebGui components which are identical to WinForms components. You can drag and drop components on the design surface exactly as you do in a WinForms application and the Visual WebGui designer will generate the code with in the InitializeComponent method.

WebGui application

Step 2 - Creating the main form

From the WebGUI toolbox pane drag a treeview component on to the design surface. The designer will create you a new treeview and it the properties pane you can change the component properties. From the properties pane select Dock property and change that property to Left. This will cause the designer to dock you treeview to the left. You can drag the right handle of the tree view to change the width of the treeview. Now, from the WebGUI toolbox pane select a splitter component and drag it to the design surface. By default the designer will apply left docking to a splitter which in this case works just fine. Drag a listview to the design surface and change it's docking to fill. The fill docking value causes the component to take all the remaining space.

Step 3 - Populating the tree view

Go to the properties pane of the form by clicking on the design form title while the properties pane is open. Change the properties pane mode to show events and double click the Load event. The designer will create you an empty event handler to handle the Load event. Which is executed when a Visual WebGui form is loaded. Create a new method that recieves TreeNodeCollection nodes and string path arguments. From the event handler we are going to call a the LoadFolder method with treeview1.Nodes and @"c:\inetpub\wwwroot", this will load the first level folders when the folder is loaded.

private void Form1_Load(object sender, System.EventArgs e)

{

LoadFolders(treeView1.Nodes,@"C:\inetpub\wwwroot");

}

private void treeView1_BeforeExpand(object sender, Gizmox.WebGUI.Forms.TreeViewCancelEventArgs e)

{

if(!e.Node.Loaded)

{

LoadFolders(e.Node.Nodes,e.Node.Tag as string);

e.Node.Loaded = true;

}

}

private void LoadFolders(TreeNodeCollection nodes,string path)

{

DirectoryInfo dir = new DirectoryInfo(path);

bool hasFolders = dir.GetDirectories().Length>0;

// Loop all sub directories

foreach(DirectoryInfo subdir in dir.GetDirectories())

{

// Create a new tree node

TreeNode node = new TreeNode();

node.Text = subdir.Name;

node.Tag = subdir.FullName;

node.IsExpanded = !hasFolders;

node.Loaded = !hasFolders; // This property is an extension to the WinForms API

node.HasNodes = hasFolders;

nodes.Add(node);

}

}

In the LoadFolder method we will add code that will enumarate the folders in the current path and create TreeNode objects appended to the nodes collection.

Step 4 - Populating the list view

Go to the Form1 constructor and add new column headers as shown in the next code snippet and set the UseInternalPaging property to true to enable Visual WebGui to handle paging internaly.

public Form1()

{

// This call is required by the WebGUI Form Designer.

InitializeComponent();

listView1.Columns.Add(new ColumnHeader("Name","Name"));

listView1.Columns.Add(new ColumnHeader("Extension","Extension"));

listView1.UseInternalPaging = true;

}

Go back to the designer and create a new event handler for the treeview AfterSelect event and with in the event handler you use e.Node.Tag to retrive the path that you need to show files from. Before you start adding items to the listview you should clear all the previous items.

private void treeView1_AfterSelect(object sender, Gizmox.WebGUI.Forms.TreeViewEventArgs e)

{

DirectoryInfo dir = new DirectoryInfo(e.Node.Tag as string);

listView1.Items.Clear();

// Loop all files in directory

foreach(FileInfo file in dir.GetFiles())

{

ListViewItem item = listView1.Items.Add(file.Name);

item.SubItems.Add(file.Extension);

}

}

Step 4 - Adding icons to spice up the UI

Visual WebGui has a diffrent resource management than WinForms as the execution context is diffrent handling actual images would be slightly heavy for a multithreaded enviroment and that way instead of images Visual WebGui has a concept of resource handles which are actuary references to actual resources. This way the Visaul WebGui server can optimize caching and retrival for resources as two resource handles pointing to the same resource handle are equal when compared. Visual WebGui contains some default resource handles such as IconResourceHandler and ImageResourceHandle that are references to directories defined with in the Visual WebGui configuration section. The resource handle uses java style file location method which means that folders are delimited by a dot.

Add a new using directive to the Form1.cs so you can create a resource handle object:

using Gizmox.WebGUI.Common.Resources;

Add icons to the creation of the TreeNode and the ListViewItem:

private void LoadFolders(TreeNodeCollection nodes,string path)

{

DirectoryInfo dir = new DirectoryInfo(path);

bool hasFolders = dir.GetDirectories().Length>0;

// Loop all sub directories

foreach(DirectoryInfo subdir in dir.GetDirectories())

{

// Create a new tree node

TreeNode node = new TreeNode();

node.Text = subdir.Name;

node.Tag = subdir.FullName;

node.IsExpanded = !hasFolders;

node.Loaded = !hasFolders; // This property is an extension to the WinForms API

node.HasNodes = hasFolders;

// Add icon to tree node

node.Image = new IconResourceHandle("folder.gif");

nodes.Add(node);

}

}

private void treeView1_AfterSelect(object sender, Gizmox.WebGUI.Forms.TreeViewEventArgs e)

{

DirectoryInfo dir = new DirectoryInfo(e.Node.Tag as string);

listView1.Items.Clear();

// Loop all files in directory

foreach(FileInfo file in dir.GetFiles())

{

ListViewItem item = listView1.Items.Add(file.Name);

item.SubItems.Add(file.Extension);

// Add icon to item

item.Image = new IconResourceHandle("file.gif");

}

}

Conclusion

As you can see from this example Visual WebGui simplifies application development by using WinForms as its basis. The designer, object model and syntax are exactly like WinForms which means you can quickly migrate existing WinForms projects, code and experience to the Visual WebGui platform. Creating complex, interactive browser based applications doesn't have to entail mastering AJAX, Javascript, XML or HTML. All it requires is familiarity with desktop application programming techniques which have proven themselves as productive.

SQL Server Backup file in Zip format

Introduction

This is SQL Server Backup and restore tool, the system will store the backup files in standard Zip format, the user-friendly screen let you backup and restore SQL Server database to local harddisk or remote network driver easily and quickly.The program can restore database easily.

To do:

  1. First Enter Your Sql Server username and password on corresponding Text Box.
  2. Click on Backup Button.
  3. It will take backup on folder ("application path"\Backup). if folder not found then program will create folder automatically in application path.
  4. After finish the job then check bkpfile on folder "Application path \Backup" bkp file created or not.

Important Functions

Add reference to SQL-DMO dll

You can do this by right clicking the project in Solution Explorer, then selecting 'Add Reference', COM components and the latest version of "Microsoft SQLDMO Object Library".

Available Server

public void dIsplayServerList(ComboBox cboListName)

{

try

{

SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();

Info.informationLayer info = new Info.informationLayer();

SQLDMO.NameList oNameList;

oNameList = oSQLServerDMOApp.ListAvailableSQLServers();

for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)

{

if (oNameList.Item(intIndex as object) != null)

{

cboListName.Items.Add(oNameList.Item(intIndex).ToString());

}

}

if (cboListName.Items.Count > 0) cboListName.SelectedIndex = 0;

else cboListName.Text = "(Local)";

}

catch

{

}

}

Available databases

public void dIsplayDatabases(ComboBox cboDatabase,Info.informationLayer info)

{

try

{

SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

cboDatabase.Items.Clear();

SQLServer.Connect(info.strServerName,info.strLoginName,info.strPwd);

foreach (SQLDMO.Database db in SQLServer.Databases)

{

if (db.Name != null)

cboDatabase.Items.Add(db.Name);

}

cboDatabase.Sorted = true;

if (cboDatabase.Items.Count == 0)cboDatabase.Text = "";

}

catch (Exception err)

{

info.ErrorMessageDataLayer = err.Message;

}

}

Create backup in zip format :

public void cReateSQLDatabaseBackup(InfoSQLDMO.informationLayer InSQLDMO)

{//This is for Creating Database Backup.

try

{

DateTime dt = DateTime.Now;

String[] format = { "dd-MM-yy" };

string date;

date = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);

string FileName = "bkp" + InSQLDMO.strdbName + date + ".bkp";

string myDocPath = InSQLDMO.strmyDocPath;

FileName = myDocPath + "\\Backup\\" + FileName;

// this.txtFile.Text = FileName;

if (Directory.Exists(myDocPath + "\\Backup"))

{

if (File.Exists(FileName) == false)

{

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + InSQLDMO.strdbName+ date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Database Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

else

{

InSQLDMO.ErrorMessageDataLayer = "The Backup file " + InSQLDMO.strdbName + " is already exists !. Do You Want to Continue..... '";

}

}

else

{

System.IO.Directory.CreateDirectory(myDocPath + "\\Backup");

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

}

catch (Exception err)

{

InSQLDMO.ErrorMessageLogicLayer = err.Message;

}

}

Restore database in zip format:

public void cReateSQLDatabaseBackup(InfoSQLDMO.informationLayer InSQLDMO)

{//This is for Creating Database Backup.

try

{

DateTime dt = DateTime.Now;

String[] format = { "dd-MM-yy" };

string date;

date = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);

string FileName = "bkp" + InSQLDMO.strdbName + date + ".bkp";

string myDocPath = InSQLDMO.strmyDocPath;

FileName = myDocPath + "\\Backup\\" + FileName;

// this.txtFile.Text = FileName;

if (Directory.Exists(myDocPath + "\\Backup"))

{

if (File.Exists(FileName) == false)

{

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + InSQLDMO.strdbName+ date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Database Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

else

{

InSQLDMO.ErrorMessageDataLayer = "The Backup file " + InSQLDMO.strdbName + " is already exists !. Do You Want to Continue..... '";

}

}

else

{

System.IO.Directory.CreateDirectory(myDocPath + "\\Backup");

SQLDMO._SQLServer SqlSever = new SQLDMO.SQLServerClass();

SqlSever.Connect(InSQLDMO.strServerName, InSQLDMO.strLoginName, InSQLDMO.strPwd);

SQLDMO.Backup bak = new SQLDMO.BackupClass();

bak.Devices = bak.Files;

bak.Files = FileName;

bak.Database = InSQLDMO.strdbName;

bak.SQLBackup(SqlSever);

string DestFile = myDocPath + "\\Backup" + "\\" + "bkp" + date + ".zip";

zIpDatabseFile(FileName, DestFile);

if (File.Exists(FileName))

{

File.Delete(FileName);

}

InSQLDMO.ErrorMessageDataLayer = "Backup Process " + InSQLDMO.strdbName + " Sucessfully Completed";

}

}

catch (Exception err)

{

InSQLDMO.ErrorMessageLogicLayer = err.Message;

}

}

Create file a zip :

private void zIpDatabseFile(string srcPath, string destPath)

{//This is for Zip a File

byte[] bufferWrite;

FileStream fsSource;

FileStream fsDest;

GZipStream gzCompressed;

fsSource = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read);

bufferWrite = new byte[fsSource.Length];

fsSource.Read(bufferWrite, 0, bufferWrite.Length);

fsDest = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write);

gzCompressed = new GZipStream(fsDest, CompressionMode.Compress, true);

gzCompressed.Write(bufferWrite, 0, bufferWrite.Length);

fsSource.Close();

gzCompressed.Close();

fsDest.Close();

}

Create unzip a file :

private void uNzIpDatabaseFile(string SrcPath, string DestPath)

{// This is for unzip a files.

byte[] bufferWrite;

FileStream fsSource;

FileStream fsDest;

GZipStream gzDecompressed;

fsSource = new FileStream(SrcPath, FileMode.Open, FileAccess.Read, FileShare.Read);

gzDecompressed = new GZipStream(fsSource, CompressionMode.Decompress, true);

bufferWrite = new byte[4];

fsSource.Position = (int)fsSource.Length - 4;

fsSource.Read(bufferWrite, 0, 4);

fsSource.Position = 0;

int bufferLength = BitConverter.ToInt32(bufferWrite, 0);

byte[] buffer = new byte[bufferLength + 100];

int readOffset = 0;

int totalBytes = 0;

while (true)

{

int bytesRead = gzDecompressed.Read(buffer, readOffset, 100);

if (bytesRead == 0)

break;

readOffset += bytesRead;

totalBytes += bytesRead;

}

fsDest = new FileStream(DestPath, FileMode.Create);

fsDest.Write(buffer, 0, totalBytes);

fsSource.Close();

gzDecompressed.Close();

fsDest.Close();

}

Blog Archive