using System; using System.Reflection; using System.Data; using MySql.Data.MySqlClient; using System.Collections; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Expression; using NHibernate.Tool.hbm2ddl; using TrainingProject.Entity;namespace TrainingProject.DataAccess { public class BaseDataAccess { private static BaseDataAccess entity; public static NHibernate.Cfg.Configuration myCfg; public static NHibernate.Dialect.Dialect dialect; public static ISessionFactory sessions;
public static BaseDataAccess CreateControl(string[] hbm) { //if (entity == null) //{ BuildSessionFactory(hbm); entity = new BaseDataAccess(); //}
using System.Reflection;
using System.Data;
using MySql.Data.MySqlClient;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Expression;
using NHibernate.Tool.hbm2ddl;
using TrainingProject.Entity;namespace TrainingProject.DataAccess
{
public class BaseDataAccess
{
private static BaseDataAccess entity;
public static NHibernate.Cfg.Configuration myCfg;
public static NHibernate.Dialect.Dialect dialect;
public static ISessionFactory sessions;
public static BaseDataAccess CreateControl(string[] hbm)
{
//if (entity == null)
//{
BuildSessionFactory(hbm);
entity = new BaseDataAccess();
//}
return entity;
}
private static void BuildSessionFactory(string[] hbm)
{
ExportSchema(hbm, false);
}
public void AddEntity(object entity)
{
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
try
{
s.Save(entity);
t.Commit();
}
catch(Exception e)
{
t.Rollback();
throw e;
}
finally
{
s.Close();
}
}
public void UpdateEntity(object entity)
{
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
try
{
s.Update(entity);
t.Commit();
}
catch(Exception e)
{
t.Rollback();
throw e;
}
finally
{
s.Close();
}
}
public void UpdateEntity(object entity, object key)
{
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
try
{
s.Update(entity, key);
t.Commit();
}
catch(Exception e)
{
t.Rollback();
throw e;
}
finally
{
s.Close();
}
}
public void DeleteEntity(object entity)
{
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
try
{
s.Delete(entity);
t.Commit();
}
catch (Exception e)
{
t.Rollback();
throw e;
}
finally
{
s.Close();
}
}
public IList GetEntities(string query)
{
IList lst;
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
lst = s.Find(query);
t.Commit();
s.Close();
return lst;
}
public IList GetAll(Type type, params string[] sortProperties)
{
ISession s = sessions.OpenSession();
ICriteria crit = s.CreateCriteria(type);
if (sortProperties != null)
{
foreach (string sortProperty in sortProperties)
{
crit.AddOrder(Order.Asc(sortProperty));
}
}
return crit.List();
}
public object GetEntity(System.Type theType, object id)
{
object obj;
ISession s = sessions.OpenSession();
ITransaction t = s.BeginTransaction();
obj = s.Load(theType, id);
t.Commit();
s.Close();
return obj; }
private static void ExportSchema(string[] files)
{
ExportSchema(files, true);
}
private static void ExportSchema(string[] files, bool exportSchema)
{
myCfg = new NHibernate.Cfg.Configuration();
for (int i = 0; i <= files.Length - 1; i++)
{
myCfg.AddResource(files[i], Assembly.Load("Entity"));
}
if (exportSchema)
{
SchemaExport se = new SchemaExport(myCfg);
se.Create(true, true);
}
sessions = myCfg.BuildSessionFactory();
dialect = NHibernate.Dialect.Dialect.GetDialect(myCfg.Properties);
}
private static void DropSchema()
{
SchemaExport se = new SchemaExport(myCfg);
se.Drop(true, true);
}
private static void ExecuteStatement(string sql)
{
ExecuteStatement(sql, true);
}
private static void ExecuteStatement(string sql, bool error)
{
IDbConnection conn = null;
IDbTransaction tran = null;
try
{
if (myCfg == null)
{
myCfg = new NHibernate.Cfg.Configuration();
}
NHibernate.Connection.IConnectionProvider prov = NHibernate.Connection.ConnectionProviderFactory.NewConnectionProvider(myCfg.Properties);
conn = prov.GetConnection();
tran = conn.BeginTransaction();
IDbCommand comm = conn.CreateCommand();
comm.CommandText = sql;
comm.Transaction = tran;
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
tran.Commit();
}
catch(Exception ex)
{
if(!(tran == null))
{
tran.Rollback();
}
if(error)
{
throw ex;
}
}
finally
{
if(!(conn == null))
{
conn.Close();
}
}
}
}}
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler,System,Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<nhibernate>
<add key="hibernate.dialect"
value="NHibernate.Dialect.MySQLDialect"/>
<add key="hibernate.connection.provider"
value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.driver_class"
value="NHibernate.Driver.MySqlDataDriver"/>
<add key="hibernate.connection.connection_string"
value="server=localhost;database=Garrison;User Id=root"/>
</nhibernate>
<log4net>
<!--<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender> <root>
<level value="WARN" />
<appender-ref ref="ConsoleAppender" />
</root>-->
<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="D:\TrainingProject\DataAccessTest\log.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="log-data\\LQSS-SS-log.txt" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="10" />
<param name="MaximumFileSize" value="5MB" />
<param name="RollingStyle" value="Size" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="HttpTraceAppender" />
<!-- <appender-ref ref="RollingLogFileAppender" /> -->
</root>
</log4net>
<appSettings>
<add key="Test" value="Test"/>
</appSettings></configuration>
* Created by SharpDevelop.
* User: Garrison.Lv
* Date: 2005-8-26
* Time: 18:32
*
* Last Modify By: Garrison.Lv
* Last Modify Date: 2005-8-26
* Last Modify Time: 18:32
*
* Copyright @ Augmentum
**************************************/using System;
using System.Collections;
using TrainingProject.Entity;namespace TrainingProject.DataAccess
{
public class ProductDataAccess
{
private BaseDataAccess baseDAL = null; public ProductDataAccess()
{
baseDAL = BaseDataAccess.CreateControl(new string[]{"Product.hbm.xml"});
}
public void AddProduct(Product product)
{
baseDAL.AddEntity(product);
}
public void ModifyProduct(Product product)
{
baseDAL.UpdateEntity(product, product.ID);
}
public void DeleteProduct(Product product)
{
baseDAL.DeleteEntity(product);
}
public Product GetProductByID(int productID)
{
return (Product)baseDAL.GetEntity(typeof(Product), productID);
}
public IList GetProductByName(string name)
{
string handleName = name.Replace("'", "''");
string query = "FROM Product where Name like '%" + handleName + "%'";
return baseDAL.GetEntities(query);
}
public IList ListProduct()
{
IList list = baseDAL.GetEntities("FROM Product"); return list;
}
public IList ListProduct(string[] sortField)
{
IList list = baseDAL.GetAll(typeof(Product), sortField);
return list;
}
}}
=-============================================
/**************************************
* Created by SharpDevelop.
* User: Garrison.Lv
* Date: 2005-8-26
* Time: 18:32
*
* Last Modify By: Garrison.Lv
* Last Modify Date: 2005-8-26
* Last Modify Time: 18:32
*
* Copyright @ Augmentum
**************************************/using System;
using System.Collections;
using TrainingProject.Entity;
using log4net;
using log4net.Config;
using System.Configuration;[assembly: log4net.Config.XmlConfigurator(Watch=true)]
namespace TrainingProject.DataAccess
{
public class UserDataAccess
{
private BaseDataAccess baseDAL = null;
public log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public UserDataAccess()
{
baseDAL = BaseDataAccess.CreateControl(new string[]{"UserInfo.hbm.xml"});
}
public UserInfo GetUserByName(string userName)
{
string query = "FROM UserInfo WHERE Name='" + userName + "'";
log.Info(query);
IList list = baseDAL.GetEntities(query);
if(list.Count > 0)
return (UserInfo)list[0];
else
return new UserInfo();
}
public bool CheckValidUser(string userName, string password)
{
bool result = false;
IList list;
string query = "FROM UserInfo where Name='" + userName + "' and Password='" + password + "'";
try
{
list = baseDAL.GetEntities(query);
if(list.Count <= 0)
result = false;
else
result = true;
}
catch(Exception e)
{
result = false;
//log.Error(e.Message);
throw e;
}
return result;
}
public void AddUser(UserInfo user)
{
baseDAL.AddEntity(user);
}
public void ModifyUser(UserInfo user)
{
baseDAL.UpdateEntity(user, user.ID);
}
public void DeleteUser(UserInfo user)
{
baseDAL.DeleteEntity(user);
}
public UserInfo GetUserByID(int userID)
{
UserInfo returnUser = (UserInfo)baseDAL.GetEntity(typeof(UserInfo), userID);
return returnUser;
}
public IList ListUser()
{
IList list = baseDAL.GetEntities("FROM UserInfo"); return list;
}
public void AddToCart(int productID, int userID)
{
CartDataAccess cartDAL = new CartDataAccess();
User_Cart cart = new User_Cart();
cart.UserID = userID;
cart.ProductID = productID;
string query = "FROM UserInfo WHERE UserID=" + userID + "and ProductID=" + productID;
IList list = cartDAL.GetEntities(query);
if(list.Count >= 1)
{
cart.Count = ((User_Cart)list[0]).Count + 1;
cartDAL.ModifyCart(cart);
}
else
{
cart.Count = 1;
}
cartDAL.AddCart(cart);
}
public void RemoveFormCart(int productID, int userID)
{
CartDataAccess cartDAL = new CartDataAccess();
User_Cart cart = new User_Cart();
cart.UserID = userID;
cart.ProductID = productID;
string query = "FROM UserInfo WHERE serID=" + userID + "and ProductID=" + productID;
IList list = cartDAL.GetEntities(query);
if(list.Count > 1)
{
cart.Count = ((User_Cart)list[0]).Count - 1;
cartDAL.ModifyCart(cart);
}
else
{
cart.Count = 1;
}
cartDAL.RomoveFromCart(cart);
}
public int ListCount(int userID)
{
CartDataAccess cartDAL = new CartDataAccess();
return cartDAL.ListCount(userID);
}
public IList ListCart(int userID)
{
CartDataAccess cartDAL = new CartDataAccess();
return cartDAL.ListCart(userID);
}
}
}