Tutorial on NHibernate and FluentNhibernate
|
|
comments (0)
|
This tutorial will be well-understood with a project , that can be downloaded from here
Background :In the past we all have spent a considerable amount of time writing a data access layer for our application. The overall time spent developing data access code could easily be 30% of the overall time used to implement the solution. There is one problem with this fact. Data access code is nothing special, nothing that adds business value to your application. (Nearly) every business application needs some kind of data access. So why would we continue to spend such a huge amount of time writing boring data access code?
NHibernate can and will take away the burden of our shoulders. Never again you will have to write and maintain stored procedures. Never again you will deal with ADO.NET and the like. When using a modern ORM tool you can concentrate on the core elements of an application, the ones that provide real business value. You can concentrate on the model of the business domain and the business rules there in. But this is enough for now. Let’s start to introduce NHibernate and its sister Fluent NHibernate. To make this introduction a little bit more realistic let’s first find an interesting domain. The domain should be well known to most of you people. What else could be a better fit that an order entry system? At the same time – to not make things too complicated – I have to define a rather simplistic order entry system. So let’s start.
Object Model first approach :One important change to consider when you develop a so called green-field application (a new application) is that you normally start with the object model of the domain for which you want to develop the application. In the past most of the time the data model was developed first. So you started with the entity relationship diagram (ERD). On top of that the application was then built. But in this article we want to first concentrate on the object model and let the database schema be generated automatically by NHibernate based on the object model. Don’t misunderstand me; I am not saying that one cannot use NHibernate to develop applications the other way around. NHibernate is also able to deal with the situation where there already is an existing data model and one has to build an application on top of this.
Mapping the domain model :Once we have our domain model in place we want to be able to store the state (of this model) in some place. Very often this is done by using a relational database management system (RDBMS) like SQL Server, Oracle, IBM DB2 or MySql to name just a few. When you are using NHibernate it doesn’t really matter which database product you’re going to use since NHibernate supports most of the well known database products. Your application will not be tied to a specific database.
NHibernate in a Nutshell :
NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform,it provides an easy way to use framework for mapping an object-oriented domain model to a traditional relational database. NHibernate is a .NET based object persistence library which helps to persist our .NET objects to and from an underlying relational database. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
“If we use an RDBMS to store our data (or state) then the data is stored in tables. Thus we have to map our object model to corresponding tables in the database. This mapping doesn’t necessarily have to be one to one (and most often it is not). That is we do not always have mapping where one object maps to one table. Very often the content of one table maps to different object.”
FluentNHibernate in a Nutshell :
To be formal – “Fluent NHibernate provides a way for you no longer need to write the standard NHibernate mapping file (. Hbm.xml), but you can use the C # mapping file to write. Doing so, facilitate the reconstruction of our code to provide the code readability, and streamlining the project code.”
The greatest advantage of FluentNHibernate is – the mapping is type-safe since it is not based on strings.
In the past the mapping between the object model and the underlying database has been mainly done by defining XML documents.
Fluent NHibernate canceled the xml file.
Why needs to replace the XML file?
a. XML is not real-time compiled. When your XML configuration file has errors, you can see only in the run-time what went wrong.
b. XML is very cumbersome. Indeed, in the NHibernate configuration file, xml node is very simple, but still can not cover up the cumbersome nature of XML file itself.
c. Repeat mapping file attributes set. For example, in xml, we need to set for each string type fields are not allowed to be empty, the length is greater than 1000, int type had to have a default value is -1, the end of the xml configuration file so you will find a lot of repetition work.
one can define the mappings in C# which is a full blown programming language and not only a data description language as XML is. This fact opens the door for many – previously unthinkable – possibilities since the mapping can now contain logic.
Step By Step Approach:
Now we will build a very simple web application which will store, update, read and delete Car data using NHibernate and FluentNhibernate.
Step 1:
From the VS editor we will create a new web application. We will add reference of NHibernate and FluentNhibernate from here……
Step 2:
We will create a new class file by giving a name “Tables.cs”. In this class file we will add all the classes that we planned to map to the Database. At first we will create a very simple class named “Car” with properties (all class should contain property)
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
Step 3:
Ok, so now we have to tell NHibernate how to map our entities to the database. We’re going to use the FluentNHibernate interface to do this, so all configuration is in code. We will create another class such as CarMap that inherits ClassMap<Car>. This is what lets FluentNHibernate know to use these mappings with the Car class we’ve just defined. If we look at the configuration, it’s saying what’s the Id field. Handily called Id in this example. NHibernate has the ability to generate auto Ids and there are many options which are beyond our scope here. Lets have look to the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
LazyLoad();
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
Table(“Car”);
}
}
}
With this statement we define the mapping of the property Title which is mandatory and thus cannot be null. We also tell the system that its maximal length is 100 characters. If we do not explicitly define the name of the column in the corresponding table on the database will be the same as the name of the mapped property. In our case this is Title. Of course this can be changed anytime by using the appropriate syntax.
You might wonder what the LazyLoad() means. A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only when it is used. I recommend you to read this Article1 & Article2 to know more about lazy loading.
LazyLoad() is an optional field.
Step 4:
Now the challenge appears- we need to tell NHibernate how to connect to the database.
At First We have to choose the Database. Here I have used SQLEXPRESS 2008 which is provided with VS 2010. Here I have created a database named ”nhub”. We will access this database through Server Explorer of the VS Editor.
Here is the place where we will apply our business logic and reduce the number and necessity of writing cumbersome stored procedures.
When we impose CRUD on RDBMS through NHibernate, all the operations is held by the NHibernate Session (Nhibernate session is different from ASP.NET session and they are totally different). It may be easier to think of a session as a cache or collection of loaded objects relating to a single unit of work. NHibernate can detect changes to the objects in this unit of work..To handle these sessions we will use some interfaces that comes form NHibernate.These interfaces are the main point of dependency of application business/control logic on NHibernate.
Five basic Interfaces used as shown in the figure below; where IQuery and ICriteria performs the same operation.
ISession interface
1. The ISession interface is the primary interface used by NHibernate applications, it exposes NHibernates methods for finding, saving, updating and deleting objects.
2. An instance of ISession is lightweight and is inexpensive to create and destroy. This is important because your application will need to create and destroy sessions all the time, perhaps on every ASP.NET page request. NHibernate sessions are not thread safe and should by design be used by only one thread at a time. The NHibernate notion of a session is something between connection and transaction.
3. We sometimes call the ISession a persistence manager because it’s also the interface for persistence-related operations such as storing and retrieving objects. Note that a NHibernate session has nothing to do with an ASP.NET session.
ISessionFactory interface
1. The application obtains ISession instances from an ISessionFactory. Compared to the ISession interface, this object is much less exciting.
2. The ISessionFactory is certainly not lightweight! It’s intended to be shared among many application threads. There is typically a single instance of ISessionFactory for the whole application-created during application initialization, for example. However, if your application accesses multiple databases using NHibernate, you’ll need a SessionFactory for each database.
3. The SessionFactory caches generated SQL statements and other mapping metadata that NHibernate uses at runtime.
4. It can also hold cached data that has been read in one unit of work, and which may be reused in a future unit of work or session. This is possible if you configure class and collection mappings to use the second-level cache.
ITranscation interface
1. The ITransaction interface, next to the ISession interface. The ITransaction interface is an optional API. NHibernate applications may choose not to use this interface, instead managing transactions in their own infrastructure code.
2. A NHibernate ITransaction abstracts application code from the underlying transaction implementation-which might be an ADO.NET transaction or any kind of manual transaction-allowing the application to control transaction boundaries via a consistent API. This helps to keep NHibernate applications portable between different kinds of execution environments and containers.
IQuery and ICriteria interfaces
1. The IQuery interface gives you powerful ways of performing queries against the database, whilst also controlling how the query is executed.
2. It is the basic interface used for fetching data using NHibernate. Queries are written in HQL or in the native SQL dialect of your database. An IQuery instance is lightweight and can’t be used outside the ISession that created it. It is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
3. The ICriteria interface is very similar; it allows you to create and execute object-oriented criteria queries.
Now, I will discuss some points from my written code for configuring the FluentNibernate . We have create a class called ModelClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace ModelClass
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
InitializeSessionFactory();
return _sessionFactory;
}
}
private static void InitializeSessionFactory()
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(
@”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<Car>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(true, true))
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
There’s quite a bit going on here. .Database(MsSqlConfiguration.MsSql2008 is where we tell NHibernate to use the SQL Server driver, there are numerous others, including MySql and SQLLite which are the popular one’s I’m aware of. The .ConnectionString is obvious we’re connecting to the database we defined above.
The next bit is optional .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true)) tells NHibernate to actually create the tables in the database if they’re not there. We don’t really want to leave this on otherwise eachtime we run our app it’ll drop the tables with all our Cars in them and recreate them. the Create(true,true) also refers to whether to show the SQL generated to drop the tables, which we’ve turned on so we can see it work its magic.
Finally we BuildSessionFactory() which will build the session factory and we assign it to a static variable so as to only use one Session for the lifetime of our application
Step 5:
All configuration is completed so far, now we will create a very simple webpage that prompt a user to create a table name “Car” for the first time if the table does not exist and then insert data into “Car” table.
We create a page just like below
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Add Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:TextBox ID=”txtTitle” runat=”server”></asp:TextBox>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
<asp:Label ID=”lblsatat” runat=”server” Text=”" ForeColor=”#FF5050″></asp:Label>
</asp:Content>
Step 6:
Now in the “ModelClass.cs” we will add this piece of code to add Car to the “Car” table.
public static void Add<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
We will add an event in the Page Class which will fire when the Save button is clicked
protected void btnSave_Click(object sender, EventArgs e)
{
Create(txtTitle.Text.ToString(), txtDesc.Text.ToString());
}
}
Notice we’re using the Session we just new up a Car class simply give it a name and then session.Save(entity) but note that it doesn’t actually get added to the database until you Commit the Transaction.
There’s a simple order here:
Open SessionBegin TransactionDo SomethingCommit the TransactionClose the transactionClose the SessionNow because we have a using statement we’re automatically calling Dispose on the Transaction and the session. The session.save(entity) figures out the appropriate SQL to generate for us.
Step 7:
This time we will recreate the “Car” class and create another class “Manufacturer”. We will assume that A Car has a Manufacturer and it is a One to Many relation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
namespace NHibernateTutorial
{
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual Manufaturer ManuFacturedBy { get; set; }
}
public class Manufaturer : Core
{
public virtual string Name { get; set; }
}
}
Step 9:
We have to Map the classes again like below -
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
References(x => x.ManuFacturedBy).Column(“ManufacturerID”).Not.LazyLoad();
Table(“Car”);
}
}
public class ManufaturerMap : ClassMap<Manufaturer>
{
public ManufaturerMap()
{
Id(x => x.Id);
Map(x => x.Name);
Table(“Manufacturer”);
}
}
}
Step 10:
We will write the following code to save data now-
public void Create(string carTitle, string carDesc)
{
Car cr = new Car();
cr.Title = carTitle;
cr.Description = carDesc;
cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() };
ModelCode.Add<Manufaturer>(cr.ManuFacturedBy);
ModelCode.Add<Car>(cr);
}
Here, “cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() }” is initaing the “Car” object with “Manufacturer” object. While saving data we have to save the manufacturere object first then Car object.
Step 11:
Now we will retrieve data from the database. to show the data we first add a GridView named “gdvShowCar” to a newly created Webform “ShowCar.aspx”.
Now we will add a method named “Get” in out ModelCode class.
public static IList<T> Get<T>()
{
IList<T> centers;
using (ISession session = OpenSession())
{
centers = session.CreateCriteria(typeof(T))
.List<T>();
}
return centers;
}
This method will return a list to us. the CreateCriteria() take a class which will be queried as a parameter and return an ICriteria Object.
Now in “ShowCar.aspx.cs” we will write -
public partial class ShowCar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
public void LoadData()
{
IList<Car> Icar = ModelCode.Get<Car>();
var cars = from car in Icar select new { car.Title, car.Description };
gdvShowCar.DataSource = cars;
gdvShowCar.DataBind();
}
}
This code will fill the griedview with data.
Step 12:
Now we will update data . we will first create a page named ”UpdateCar”. there we will create a drop down list of Car’s name. We will select a name from the list and update data according to this particular Car name.
<%@ Page Title=”" Language=”C#” MasterPageFile=”~/Site.Master” AutoEventWireup=”true” CodeBehind=”UpdateCar.aspx.cs” Inherits=”NHibernateTutorial.UpdateCar” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”server”>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Update Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:DropDownList ID=”ddlCarTitle” runat=”server” AutoPostBack=”True”></asp:DropDownList>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Manufacturer Name:
</td>
<td>
<asp:TextBox ID=”txtMan” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
</asp:Content>
we did not bind data to the dropdownlist yet. To do that we will simply call the “Get” method fromModelCode class.
we can write -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initData();
}
}
public void initData()
{
IList<Car> cars = ModelCode.Get<Car>();
ddlCarTitle.DataSource = cars.ToList();
ddlCarTitle.DataTextField = “Title”;
ddlCarTitle.DataValueField = “Id”;
ddlCarTitle.DataBind();
}
The DropDownList is filled with data now. Next, we have to Load our text boxes with appropriate data. For this we will create an overloaded method of “Get” inside the “DataModel” class. this method may looks like below -
public static IList<T> Get<T>(string property, object value)
{
IList<T> centers;
using (ISession session = OpenEngineSession())
{
centers = session.CreateCriteria(typeof(T))
.Add(Restrictions.Eq(property, Convert.ToInt32(value)))
.List<T>();
}
return centers;
}
the eq() searches a match for the (property,value) pair and return a List. It works like traditional WHERE clause with a SELECT statement.
Now we will create an method in the page class named “LoadCarInfo” this method will load data on form when the DropDownList of Name is being populated.
public void LoadCarInfo()
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString());
if (inv.Count > 0)
{
txtDesc.Text = inv[0].Description;
txtMan.Text = inv[0].ManuFacturedBy.Name;
}
}
Now , time to UpDate data. This very similar to “Add” in the ModelCode class.
We will add another method to “ModelCode”. It is very easy and understandable.
public static void Update<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
So now we can call this “Update” from our Page Class as before-
protected void btnSave_Click(object sender, EventArgs e)
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString())[0];
inv.Description = txtDesc.Text;
inv.ManuFacturedBy.Name = txtMan.Text;
ModelCode.Update<Manufaturer>(inv.ManuFacturedBy);
ModelCode.Update<Car>(inv);
}
Step 13:
Now we will Delete data. We will add another method in “ModelCode”.
public static void Remove<T>(T entity)
{
using (ISession session = OpenEngineSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
Conclusion:
Here I have tried to given some basic CRUD operation using NHibernate and FluentNHibernate. Many thing is left and overlooked intentionally because the limitation of my scope. Actually It takes time to be expert and skilled with these technology.
DownLoad FullCode.
How to Update Existing data by comparing lenth in C#
|
|
comments (0)
|
private void mprivUpdateStockItemCodeRelatedRecord()
{
string lstrNewStockItemCode;
if (clsDatabaseConnector.gmpubstasqlconnSQLConnection.State == ConnectionState.Open)
{
clsDatabaseConnector.gmpubstasqlconnSQLConnection.Close();
}
clsDatabaseConnector.gmpubstasqlconnSQLConnection.Open();
//OPEN TEMPORARY CONNECTION
if (clsDatabaseConnector.gmpubstasqlconnSQLConnectionTemp.State == ConnectionState.Open)
{
clsDatabaseConnector.gmpubstasqlconnSQLConnectionTemp.Close();
}
clsDatabaseConnector.gmpubstasqlconnSQLConnectionTemp.Open();
string lstrQuery = "SELECT STOCKITEM_CODE FROM INV_STOCKITEM WHERE STOCKITEM_CODE <> 'NULL' ORDER BY STOCKITEM_CODE";
SqlCommand thisCommand = new SqlCommand(lstrQuery, clsDatabaseConnector.gmpubstasqlconnSQLConnection);
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
lstrNewStockItemCode = null;
string lstrOldStockItemCode = Convert.ToString(thisReader["STOCKITEM_CODE"]);
if (lstrOldStockItemCode != "As Per Details")
{
string[] oldSplitedCode = lstrOldStockItemCode.Split('.');
foreach (string splitedCode in oldSplitedCode)
{
if (splitedCode.Length == 2)
{
lstrNewStockItemCode += "0" + splitedCode + ".";
}
else if (splitedCode.Length > 2)
{
lstrNewStockItemCode += "00" + splitedCode;
}
}
string lstrUpdateQuery = "UPDATE INV_STOCKITEM SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
lstrUpdateQuery += "; UPDATE ACC_SALES_PRICE_SETTING_CHILD SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
lstrUpdateQuery += "; UPDATE INV_TRAN_CHILD SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
lstrUpdateQuery += "; UPDATE INV_SL_NO_WISE_STOCK_DETAILS SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
lstrUpdateQuery += "; UPDATE INV_LC_OR_WORK_ORDER_CHILD SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
lstrUpdateQuery += "; UPDATE TAA_TARGET_SETTING_CHILD SET STOCKITEM_CODE = '" + lstrNewStockItemCode + "' WHERE STOCKITEM_CODE = '" + lstrOldStockItemCode + "'";
SqlCommand thisCommandTemp = new SqlCommand(lstrUpdateQuery, clsDatabaseConnector.gmpubstasqlconnSQLConnectionTemp);
thisCommandTemp.ExecuteNonQuery();
}
}
thisReader.Close();
clsDatabaseConnector.gmpubstasqlconnSQLConnectionTemp.Close();
clsDatabaseConnector.gmpubstasqlconnSQLConnection.Close();
}
mprivUpdateStockItemCodeRelatedRecord();
Upper Case First Character in a Text using C#
|
|
comments (0)
|
public static string UppercaseFirst(string text) //using ToCharArray; it is faster than traditional way
{
if (text.Length > 0)
{
char[] a = text.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
else
return "";
}
Website Validiting in C#
|
|
comments (0)
|
if (txtWebsite.Text != "")
{
if (!isWeb(txtWebsite.Text))
{
MessageBox.Show("Please Enter Valid Website Name");
txtWebsite.Focus();
txtWebsite.SelectAll();
}
else
{
txtEmail.Focus();
txtEmail.SelectAll();
}
}
else
{
txtEmail.Focus();
txtEmail.SelectAll();
}
public static bool isWeb(string inputWebsitel)
{
return Regex.IsMatch(inputWebsitel,@"^(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$");
}
Dtabase Restore And Backup in C#
|
|
comments (0)
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management;
using System.IO;
using net.ERP.AIMS.Constants;
using net.ERP.AIMS.Utility;
using net.ERP.AIMS.DatabaseSchema.DBExistanceChecking;
using System.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
namespace net.ERP.AIMS.Modules.Settings.GUI.Config
{
public partial class frmSettingsConfigDatabaseBackup : Form
{
public frmSettingsConfigDatabaseBackup()
{
InitializeComponent();
}
private static Server srvSql;
//private string mpristrFolderNameOne = "net.ERP.AIMS(Backup).bak";
//private string mpristrFolderNameTwo = "\net.ERP.AIMS(Backup).bak";
private void cmdLocation_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
txtBrowse.Text = folderDlg.SelectedPath;
//folderBrowserDialog.SelectedPath = txtBrowse.Text + @"\net.ERP.AIMS(Backup).bak";
}
}
private void cmdBackup_Click(object sender, EventArgs e)
{
string lstrToday = DateTime.Today.ToString("(MM-dd-yyyy)");
string lstrFileName = null;
if (txtBrowse.TextLength == 3)
{
lstrFileName = "DATABASE_BACKUP";
}
else
{
lstrFileName = @"\DATABASE_BACKUP";
}
string lstrExtension = ".bak";
string lstrFilePath = null;
string lstrTodayFile = lstrFileName + lstrToday + lstrExtension;
if (srvSql != null)
{
// Create a new backup operation
Backup bkpDatabase = new Backup();
// Set the backup type to a database backup
bkpDatabase.Action = BackupActionType.Database;
// Set the database that we want to perform a backup on
bkpDatabase.Database = clsCommonConstants.gmpubcstrDatabaseName;
// Set the backup device to a file
BackupDeviceItem bkpDevice = new BackupDeviceItem(txtBrowse.Text + lstrTodayFile, DeviceType.File);
bkpDatabase.Devices.Add(bkpDevice);
//Add the backup device to the backup
lstrFilePath = txtBrowse.Text + lstrTodayFile;
if (File.Exists(lstrFilePath))
{
File.Delete(lstrFilePath);
}
// Perform the backup
bkpDatabase.SqlBackup(srvSql);
MessageBox.Show("Backup Successfull");
}
else
{
// There was no connection established; probably the Connect button was not clicked
MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void DatabaseBackup_Load(object sender, EventArgs e)
{
ServerConnection srvConn = new ServerConnection(clsCommonConstants.gmpubstastrServerName.ToString());
srvSql = new Server(srvConn);
}
private void cmdRestore_Click(object sender, EventArgs e)
{
string lstrToday = DateTime.Today.ToString("(MM-dd-yyyy)");
string lstrFileName = null;
if (txtBrowse.TextLength == 3)
{
lstrFileName = "DATABASE_BACKUP";
}
else
{
lstrFileName = @"\DATABASE_BACKUP";
}
string lstrExtension = ".bak";
string lstrTodayFile = lstrFileName + lstrToday + lstrExtension;
if (srvSql != null)
{
Restore rstDatabase = new Restore();
BackupDeviceItem bkpDevice = new BackupDeviceItem(txtBrowse.Text + lstrTodayFile, DeviceType.File);
// Add the backup device to the restore type
rstDatabase.Devices.Add(bkpDevice);
// Set the database that we want to perform the restore on
rstDatabase.Database = clsCommonConstants.gmpubcstrDatabaseName;
// Set the restore type to a database restore
rstDatabase.Action = RestoreActionType.Database;
// If the database already exists, replace it
rstDatabase.ReplaceDatabase = true;
// Perform the restore
rstDatabase.SqlRestore(srvSql);
MessageBox.Show("Restore Successfull");
}
else
{
// There was no connection established; probably the Connect button was not clicked
MessageBox.Show("A connection to a SQL server was not established.", "Not Connected to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void txtBrowse_TextChanged(object sender, EventArgs e)
{
}
}
}
Drop Database Using C#
|
|
comments (0)
|
private void mprivDleteDB()
{
string mpristrSQL = string.Format("use master; drop database NET_ERP_REMS");
OperationGateway.mpubiExecuteSQLStmt(mpristrSQL);
}
Valid Email Address Checking
|
|
comments (0)
|
public static bool isEmail(string inputEmail)
{
inputEmail = NulltoString(inputEmail);
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Import Data from EXCEL TO SQL
|
|
comments (0)
|
using Excel = Microsoft.Office.Interop.Excel;
string Path = @"f:\ACC_LEDGER_TROYEE.xls";
Excel.Application app = new Excel.Application();
Excel.Workbook workBook = app.Workbooks.Open(Path, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
object rowIndex = 2;
object colIndex1 = 1;
object colIndex2 = 2;
object colIndex3 = 3;
try
{
while (((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value != null)
{
rowIndex = 2 + index;
//mpristrLedgerSerialNo = ((Excel.Range)workSheet.Cells[rowIndex, colIndex1]).Value.ToString();
mpristrLedgerName = ((Excel.Range)workSheet.Cells[rowIndex, colIndex2]).Value.ToString();
liLedgerPartyType = Convert .ToInt16 (((Excel.Range)workSheet.Cells[rowIndex, colIndex3]).Value);
mpristrLedgerCurrencySymbol = ((Excel.Range)workSheet.Cells[rowIndex, colIndex4]).Value.ToString();
clsOperationGateway.mpubstaiInsertIntoAccLedger(tbleAccLedger);
clsOperationGateway.mpubstaiUpdateAccLedgerForExcel(mpristrLedgerName, mpristrLedgerCodeTemp, mpristrLedgerCode, mpristrLedgerCurrencySymbol, mpristrLedgerGroupCode, mpridblOpeningBalance, mpridblFCOpeningBalance, mpridblClosingBalance, mpridblOnAccountValue, mpridblDebit, mpridblCredit, mpridblCreditLimit, mpridblCreditPeriod, mpristrAddress1, mpristrCountry, mpristrCity, mpristrPostal, mpristrFax, mpristrTelephone, mpristrMobile, mpristrEmailAddress, mpristrContactPer, mpriiCostCentreStatus, mpriiPayroll, mpriiEffectInventory, mpriiLedgerStatus, mpristrComments, mpristrLedgerInsertDate);
index++;
}
}
catch (Exception ex)
{
app.Quit();
Console.WriteLine(ex.Message);
}
MessageBox.Show("Successfully Imported...........");
}
How To Send Email Using C#
|
|
comments (0)
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Net;
namespace net.ERP.Modules.Marketing.GUI.Master
{
public partial class frmEmail : Form
{
public frmEmail()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("userid", "Password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
How To Send Email Using C#
|
|
comments (0)
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Net;
namespace net.ERP.Modules.Marketing.GUI.Master
{
public partial class frmEmail : Form
{
public frmEmail()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "20121986Mominul");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}