protected override List <ProductInventory> GetingItems(System.Data.Linq.DataContext dc, SearchCondition search) { IQueryable <ProductInventory> ret = dc.GetTable <ProductInventory>(); if (search is ProductInventorySearchCondition) { ProductInventorySearchCondition con = search as ProductInventorySearchCondition; if (!string.IsNullOrEmpty(con.WareHouseID)) { ret = ret.Where(item => item.WareHouseID.Contains(con.WareHouseID)); } if (!string.IsNullOrEmpty(con.ProductID)) { ret = ret.Where(item => item.ProductID.Contains(con.ProductID)); } } List <ProductInventory> items = ret.ToList(); if (items != null && items.Count > 0) { List <Product> ps = (new ProductProvider(ConnectStr, _MappingResource)).GetItems(null).QueryObjects; List <WareHouse> ws = (new WareHouseProvider(ConnectStr, _MappingResource)).GetItems(null).QueryObjects; foreach (ProductInventory pi in items) { pi.Product = ps.SingleOrDefault(p => p.ID == pi.ProductID); pi.WareHouse = ws.SingleOrDefault(w => w.ID == pi.WareHouseID); } } return(items); }
private void DeleteExsistingOrder() { using (var ctx = new System.Data.Linq.DataContext(Central.SpecialConnStr)) { ctx.ExecuteCommand("delete from objects where id={0}", _bar.Id); } }
private void btnFind_Click(object sender, RoutedEventArgs e) { if (tbSearchString.Text == "") { btnRefresh_Click(sender, e); return; } else { string SqlCommand; if (TableType.Name[TableType.Name.Length - 1] == 'y') { SqlCommand = "select * from " + TableType.Name.Substring(0, TableType.Name.Length - 1) + "ies where "; } else { SqlCommand = "select * from " + TableType.Name + "s where "; } string[] SearchValues = tbSearchString.Text.Split(); foreach (string Str in SearchValues) { try { int I = Convert.ToInt32(Str); foreach (var F in Fields) { if (F.Value.PropertyType == typeof(int)) { SqlCommand += F.Value.Name + " = " + I.ToString() + " or "; } } } catch { } try { double I = Convert.ToDouble(Str); foreach (var F in Fields) { if (F.Value.PropertyType == typeof(double)) { SqlCommand += F.Value.Name + " = " + I.ToString() + " or "; } } } catch { } foreach (var F in Fields) { if (F.Value.PropertyType == typeof(string)) { SqlCommand += F.Value.Name + " like '%" + Str + "%' or "; } } } SqlCommand = SqlCommand.Substring(0, SqlCommand.Length - 4); DatabaseContext = new System.Data.Linq.DataContext(ConnectionString); DataGrid.DataContext = DatabaseContext.ExecuteQuery(TableType, SqlCommand); } }
protected override List <ExpenditureRecord> GetingItems(System.Data.Linq.DataContext dc, SearchCondition search) { IQueryable <ExpenditureRecord> ret = dc.GetTable <ExpenditureRecord>(); if (search is SheetSearchCondition) { SheetSearchCondition con = search as SheetSearchCondition; if (con.SheetDate != null) { ret = ret.Where(item => item.SheetDate >= con.SheetDate.Begin && item.SheetDate <= con.SheetDate.End); } if (con.LastActiveDate != null) { ret = ret.Where(item => item.LastActiveDate >= con.LastActiveDate.Begin && item.LastActiveDate <= con.LastActiveDate.End); } if (con.SheetNo != null && con.SheetNo.Count > 0) { ret = ret.Where(item => con.SheetNo.Contains(item.ID)); } if (con.States != null && con.States.Count > 0) { ret = ret.Where(item => con.States.Contains(item.State)); } } if (search is ExpenditureRecordSearchCondition) { ExpenditureRecordSearchCondition con = search as ExpenditureRecordSearchCondition; if (!string.IsNullOrEmpty(con.Category)) { ret = ret.Where(item => item.Category.Contains(con.Category)); } } return(ret.ToList()); }
public DatabaseInterface(System.Data.Linq.DataContext DatabaseContext, Type TableType, Dictionary <string, PropertyInfo> Fields, DataGrid DataGrid) { this.DatabaseContext = DatabaseContext; this.TableType = TableType; this.Fields = Fields; this.DataGrid = DataGrid; }
public static System.Data.DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query) { if (query == null) { throw new System.ArgumentNullException("query"); } System.Data.IDbCommand cmd = ctx.GetCommand(query as System.Linq.IQueryable); var adapter = new System.Data.SqlClient.SqlDataAdapter(); adapter.SelectCommand = (System.Data.SqlClient.SqlCommand)cmd; var dt = new System.Data.DataTable(); try { cmd.Connection.Open(); adapter.FillSchema(dt, System.Data.SchemaType.Source); adapter.Fill(dt); } catch { throw; } finally { cmd.Connection.Close(); } return(dt); }
protected override List <DeviceReadLog> GetingItems(System.Data.Linq.DataContext dc, SearchCondition search) { IQueryable <DeviceReadLog> ret = dc.GetTable <DeviceReadLog>(); if (search is DeviceReadLogSearchCondition) { var con = search as DeviceReadLogSearchCondition; if (con.ReadDateRange != null) { ret = ret.Where(it => it.ReadDate >= con.ReadDateRange.Begin && it.ReadDate <= con.ReadDateRange.End); } if (!string.IsNullOrEmpty(con.DeviceID)) { ret = ret.Where(it => it.DeviceID == con.DeviceID); } if (con.Devices != null && con.Devices.Count > 0) { ret = ret.Where(it => con.Devices.Contains(it.DeviceID)); } if (con.DeviceType.HasValue) { ret = ret.Where(it => it.DeviceType == con.DeviceType.Value); } } return(ret.ToList()); }
public DataSet ToDataTable(System.Data.Linq.DataContext ctx, object query) { if (query == null) { throw new ArgumentNullException("query"); } IDbCommand cmd = ctx.GetCommand(query as IQueryable); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataSet ds = new DataSet("sd"); ds.EnforceConstraints = false; try { cmd.Connection.Open(); adapter.FillSchema(ds, SchemaType.Source); adapter.Fill(ds); } finally { cmd.Connection.Close(); } return(ds); }
private string objQueryToXML(System.Data.Linq.DataContext ctx, object query, int rowCount, decimal ID_USUARIO) { DataTable dt = ApoioXML.ToDataTable(ctx, query); dt.Columns["CONTATOS"].MaxLength = 50000; foreach (DataRow dr in dt.Rows) { dr["CONTATOS"] = ContatosDoCliente(Convert.ToDecimal(dr["ID_CLIENTE"]), ID_USUARIO); } DataSet ds = new DataSet("Query"); ds.Tables.Add(dt); DataTable totalCount = new DataTable("Totais"); totalCount.Columns.Add("totalCount"); DataRow nova = totalCount.NewRow(); nova[0] = rowCount; totalCount.Rows.Add(nova); ds.Tables.Add(totalCount); System.IO.StringWriter tr = new System.IO.StringWriter(); ds.WriteXml(tr); return(tr.ToString()); }
protected ServiceResult HandleException(Exception ex, User user) { ServerError error = new ServerError() { ErrorMessage = ex.Message, DateCreated = DateTime.Now, }; if (user != null) { error.UserId = user.UserId; error.UserName = user.UserName; } //HACK The saving of errors needs to be refactored. The reason for the below code is because we need to //create a new context, as the DB one has thrown an exception, therefore we are not able to use it any longer to save. //That's why the error is being saved in the first place i.e. because an exception has been thrown. using (System.Data.Linq.DataContext ctx = new System.Data.Linq.DataContext(LINQOptions.Instance.Settings.ConnectionString)) { ctx.GetTable <ServerError>().InsertOnSubmit(error); ctx.SubmitChanges(); } ServiceException serviceException = ex as ServiceException; if (serviceException == null) { return(new ServiceResult { Code = ServiceResultCode.FatalError, Message = ex.Message }); //Not a user thrown exception. } else { return(serviceException.Result); } }
/// <summary> /// Caches Linq query´s that is created for LinqToSql. /// Limitations are the same as SqlCacheDependency /// </summary> /// <typeparam name="T"></typeparam> /// <param name="q">The linq query</param> /// <param name="dc">Your LinqToSql DataContext</param> /// <param name="CacheId">The unique Id for the cache</param> /// <returns></returns> public static List <T> LinqCache <T>(this System.Linq.IQueryable <T> q, System.Data.Linq.DataContext dc, string CacheId) { try { List <T> objCache = (List <T>)System.Web.HttpRuntime.Cache.Get(CacheId); if (objCache == null) { /////////No cache... implement new SqlCacheDependeny////////// //1. Get connstring from DataContext string connStr = dc.Connection.ConnectionString; //2. Get SqlCommand from DataContext and the LinqQuery string sqlCmd = dc.GetCommand(q).CommandText; //3. Create Conn to use in SqlCacheDependency using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr)) { conn.Open(); //4. Create Command to use in SqlCacheDependency using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlCmd, conn)) { //5.0 Add all parameters provided by the Linq Query foreach (System.Data.Common.DbParameter dbp in dc.GetCommand(q).Parameters) { cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter(dbp.ParameterName, dbp.Value)); } //5.1 Enable DB for Notifications... Only needed once per DB... System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connStr); //5.2 Get ElementType for the query string NotificationTable = "ReviseResourceValue";// q.ElementType.Name; //string NotificationTable = q.ElementType.Name; //5.3 Enable the elementtype for notification (if not done!) if (!System.Web.Caching.SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connStr).Contains(NotificationTable)) { System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, NotificationTable); } //6. Create SqlCacheDependency System.Web.Caching.SqlCacheDependency sqldep = new System.Web.Caching.SqlCacheDependency(cmd); // - removed 090506 - 7. Refresh the LinqQuery from DB so that we will not use the current Linq cache // - removed 090506 - dc.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, q); //8. Execute SqlCacheDepency query... cmd.ExecuteNonQuery(); //9. Execute LINQ-query to have something to cache... objCache = q.ToList(); //10. Cache the result but use the already created objectCache. Or else the Linq-query will be executed once more... System.Web.HttpRuntime.Cache.Insert(CacheId, objCache, sqldep); //System.Web.HttpRuntime.Cache.Insert("test", objCache); //System.Web.HttpRuntime.Cache.Add(CacheId,objCache,sqldep,System.DateTime.Now.AddDays(2),System.TimeSpan.MaxValue,System.Web.Caching.CacheItemPriority.Default) } } } //Return the created (or cached) List //dc.Dispose(); return(objCache); } catch (Exception ex) { throw ex; } }
private void SortAuthorClick(object sender, EventArgs e) { System.Data.Linq.DataContext db = new System.Data.Linq.DataContext(connectionString); var query = from u in db.GetTable <Book>() orderby u.AuthorFIO select u; }
private void Search_Click(object sender, EventArgs e) { System.Data.Linq.DataContext db = new System.Data.Linq. DataContext(Properties.Resources.ConnectionString); Resultatas.DataSource = db.GetTable <Lektuva>(). Where(x => x.AtvykimoVieta == KryptisText.Text && x.Isvykimas.Date > dateTimePicker1.Value); }
public static DataSet LINQToDataSet(System.Data.Linq.DataContext dataContext, IQueryable linQ) { DataSet ds = new DataSet(); SqlCommand cmd = dataContext.GetCommand(linQ) as SqlCommand; SqlDataAdapter adp = new SqlDataAdapter(cmd); adp.Fill(ds); return(ds); }
private static string GetTableName(System.Data.Linq.DataContext DB, Type entityType) { Type tableType = typeof(System.Data.Linq.Table <>).MakeGenericType(entityType); var propertyInfo = DB.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType == tableType).FirstOrDefault(); if (propertyInfo == null) { return(string.Empty); } return(propertyInfo.Name); }
protected override ProductInventory GetingItemByID(Guid id, System.Data.Linq.DataContext dc) { //ProductInventory pi = dc.GetTable<ProductInventory>().SingleOrDefault(item => item.ID == id); //if (pi != null) //{ // pi.Product = dc.GetTable<Product>().SingleOrDefault(p => p.ID == pi.ProductID); // pi.WareHouse = dc.GetTable<WareHouse>().SingleOrDefault(w => w.ID == pi.WareHouseID); //} //return pi; throw new Exception("未实现此方法"); }
public CreateEditWindow(System.Data.Linq.DataContext DatabaseContext, Type Type, Dictionary <string, PropertyInfo> Fields) { InitializeComponent(); TableType = Type; windowMain.Title = "Добавление"; this.DatabaseContext = DatabaseContext; Creating = true; this.Fields = Fields; RemakeWindow(Fields); }
private void button1_Click(object sender, EventArgs e) { Dates = dtpFrom.Value; Motivo = textBox1.Text; using (var ctx = new System.Data.Linq.DataContext(Central.ConnStr)) { ctx.ExecuteCommand("update comenzi set DateControlled={0}, Motivo={1} where Id={2}", Dates, Motivo, Id); } DialogResult = DialogResult.OK; Close(); }
private void CloseAllOpenConnections(LinqDataContext ctx) { ctx.Log = new StringWriter(); if (ctx.DatabaseExists()) { //drop all connections by disabling multi-user (and immediatly abort all current transactions) ctx.ExecuteCommand("ALTER DATABASE " + _databaseName + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE"); //re-enable multi-user ctx.ExecuteCommand("ALTER DATABASE " + _databaseName + " SET MULTI_USER"); } }
public void DeleteAll() { System.Configuration.ConnectionStringSettingsCollection connectionStrings = WebConfigurationManager.ConnectionStrings as ConnectionStringSettingsCollection; if (connectionStrings.Count > 0) { System.Data.Linq.DataContext db = new System.Data.Linq.DataContext(connectionStrings["ConnectionString"].ConnectionString); db.ExecuteCommand("TRUNCATE TABLE Employees"); } }
public CreateEditWindow(System.Data.Linq.DataContext DatabaseContext, Object O, Dictionary <string, PropertyInfo> Fields) { InitializeComponent(); TableType = O.GetType(); windowMain.Title = "Редактирование"; this.DatabaseContext = DatabaseContext; Creating = false; this.Fields = Fields; RemakeWindow(Fields); SetValues(O); Result = O; }
/// <summary> /// Execute an SQL command directly to the database. /// </summary> /// <param name="dataContext">The data context to the database.</param> /// <param name="sqlCommand">The sql command to execute to the database.</param> /// <param name="values">The parameter values for the command, can be null.</param> /// <returns>A value indicating the result of the command.</returns> /// <exception cref="System.ArgumentNullException"></exception> public static Int32 ExecuteCommand(System.Data.Linq.DataContext dataContext, string sqlCommand, params object[] values) { // Check to see if the critical parameters // have been set, throw exception on each. if (sqlCommand == null) { throw new ArgumentNullException("sqlCommand"); } // Execute the command and return // the result from the command. return(dataContext.ExecuteCommand(sqlCommand, values)); }
public void DeleteAll() { using (PersonsDBEntities pb = conn.GetContext()) { System.Configuration.ConnectionStringSettingsCollection connectionStrings = WebConfigurationManager.ConnectionStrings as ConnectionStringSettingsCollection; if (connectionStrings.Count > 0) { System.Data.Linq.DataContext db = new System.Data.Linq.DataContext(connectionStrings["ConnectionString"].ConnectionString); db.ExecuteCommand("TRUNCATE TABLE Department"); } } }
public static IEnumerable <T> GetMatchingObjects <T>(System.Data.Linq.DataContext dataContext, IEnumerable <WhereCondition> elements, string tableName, string[] columnNames) #if Mono where T : class, new() #endif { string sql = string.Format("SELECT {0} FROM {1} WHERE {2}", string.Join(",", columnNames), tableName, elements.ToWhereString() ); var parameterValues = elements.AsQueryable().SelectMany(elem => elem.Values).ToArray(); return(dataContext.ExecuteQuery <T>(sql, parameterValues)); }
public static string CreateMethods(MetadataResult metadata, System.Data.Linq.DataContext DB) { var sb = new StringBuilder(4096); metadata.dbSets.ForEach((dbSetInfo) => { string tableName = GetTableName(DB, dbSetInfo.EntityType); if (tableName == string.Empty) { return; } sb.AppendLine(createDbSetMethods(dbSetInfo, tableName)); }); return(sb.ToString()); }
protected override List <Contact> GetingItems(System.Data.Linq.DataContext dc, SearchCondition search) { IQueryable <Contact> ret = dc.GetTable <Contact>(); if (search is ContactSearchCondition) { ContactSearchCondition con = search as ContactSearchCondition; if (!string.IsNullOrEmpty(con.CompanyID)) { ret = ret.Where(item => item.Company == con.CompanyID); } } List <Contact> cs = ret.ToList(); return(cs); }
private void RegistruotisMygtukas_Click(object sender, EventArgs e) { User user = new User() { Vardas = NameText.Text, Pavarde = SurnameText.Text, UserName = UserNameText.Text, Password = PassWordName.Text }; string connection = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\GitHub\C--kursas-20190923\Rezervacijo\Rezervacijo\RezervacijosDB.mdf;Integrated Security=True"; System.Data.Linq.DataContext db = new System.Data.Linq.DataContext(connection); db.GetTable <User>().InsertOnSubmit(user); db.SubmitChanges(); Close(); }
static CreateTable() { var context = new System.Data.Linq.DataContext(Conexion.Connection); // Crear Tabla Por la Aplicacion. // CREATE TABLE[TAcciones] context.ExecuteCommand("CREATE TABLE[TAcciones] ([idAcciones] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[fkCliente] INTEGER NOT NULL,[fkTipoAccion] INTEGER NOT NULL,[FechaAccion] DATE DEFAULT CURRENT_DATE NULL,[FechaRecordar] DATE DEFAULT CURRENT_DATE NULL,[Comentario] TEXT NULL);"); // CREATE TABLE[TCliente] context.ExecuteCommand("CREATE TABLE [TCliente] ([idCliente] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[Nombre] varCHAR(30) NOT NULL,[Apellido] VARCHAR(30) NOT NULL,[Cedula] VARCHAR(30) UNIQUE NULL,[fkDireccion] INTEGER NULL,[Telefono] varchar(30) NULL,[Email] varCHAR(30) NULL,[Estatu] INTEGER NULL);"); // CREATE TABLE[TDireccion] context.ExecuteCommand("CREATE TABLE[TDireccion] ([idDireccion] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[pais] varCHAR(30) NOT NULL,[Ciudad] VARCHAR(30) NOT NULL,[Municipio] vaRCHAR(30) NULL,[Barrio] vaRCHAR(30) NULL,[Calle] varCHAR(15) NULL,[numCasa] INTEGER(4) NULL,[Detalles] varchar(9) NULL); "); // CREATE TABLE[TTipoAccion] context.ExecuteCommand("CREATE TABLE[TTipoAccion] ([idTipoAccion] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[Descripcion] VARCHAR(60) NOT NULL); "); // CREATE TABLE[TUsuario] context.ExecuteCommand("CREATE TABLE[TUsuario] ([idUsuario] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,[Usuario] VARCHAR(30) UNIQUE NOT NULL,[Clave] VARCHAR(30) NOT NULL,[fkUsuario] INTEGER Null); "); }
private void btnDelete_Click(object sender, RoutedEventArgs e) { if (DataGrid != null) { if (DataGrid.SelectedItem != null) { if (MessageBox.Show(@"Вы действительно хотите удалить эту запись", "Удаление", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { var Table = DatabaseContext.GetTable(TableType); Table.DeleteOnSubmit(DataGrid.SelectedItem); DatabaseContext.SubmitChanges(); DatabaseContext = new System.Data.Linq.DataContext(ConnectionString); DataGrid.DataContext = DatabaseContext.GetTable(TableType); } } } }
private void Connect_Click(object sender, EventArgs e) { System.Data.Linq.DataContext db = new System.Data.Linq.DataContext(connection); var user = db.GetTable <User>(). Where(x => x.UserName == UserNameText.Text && x.Password == PassWordText.Text); if (user.Count() == 0) { MessageBox.Show("Nerastas toks vartotojas"); } else { RezervacijosForma form = new RezervacijosForma(connection, user.First().Id); form.Show(); WindowState = FormWindowState.Minimized; } }
public DataRepository() { //Load Connectionstring try { string filedb = string.Format(@"{0}\personalThingsdb.sqlite", Environment.CurrentDirectory); //System.IO.File.Delete(filedb); connection = new SQLiteConnection(@"Data Source=" + filedb + ";version=3"); checkorcreate(); context = new System.Data.Linq.DataContext(connection); }catch (Exception ex) { Estado = "Error Datos: " + ex.Message; MostrarEstado = true; } }
/* public override IDbDataParameter CreateSqlParameter(IDbCommand cmd, string dbTypeName, string paramName) { //System.Data.SqlDbType dbType = DbLinq.util.SqlTypeConversions.ParseType(dbTypeName); //SqlParameter param = new SqlParameter(paramName, dbType); NpgsqlTypes.NpgsqlDbType dbType = PgsqlTypeConversions.ParseType(dbTypeName); NpgsqlParameter param = new NpgsqlParameter(paramName, dbType); return param; } */ /// <summary> /// call mysql stored proc or stored function, /// optionally return DataSet, and collect return params. /// </summary> public override System.Data.Linq.IExecuteResult ExecuteMethodCall(DataContext context, MethodInfo method , params object[] inputValues) { if (method == null) throw new ArgumentNullException("L56 Null 'method' parameter"); //check to make sure there is exactly one [FunctionEx]? that's below. //FunctionAttribute functionAttrib = GetFunctionAttribute(method); var functionAttrib = context.Mapping.GetFunction(method); ParameterInfo[] paramInfos = method.GetParameters(); //int numRequiredParams = paramInfos.Count(p => p.IsIn || p.IsRetval); //if (numRequiredParams != inputValues.Length) // throw new ArgumentException("L161 Argument count mismatch"); string sp_name = functionAttrib.MappedName; using (IDbCommand command = context.Connection.CreateCommand()) { command.CommandText = sp_name; //MySqlCommand command = new MySqlCommand("select hello0()"); int currInputIndex = 0; List<string> paramNames = new List<string>(); for (int i = 0; i < paramInfos.Length; i++) { ParameterInfo paramInfo = paramInfos[i]; //TODO: check to make sure there is exactly one [Parameter]? ParameterAttribute paramAttrib = paramInfo.GetCustomAttributes(false).OfType<ParameterAttribute>().Single(); //string paramName = "?" + paramAttrib.Name; //eg. '?param1' MYSQL string paramName = ":" + paramAttrib.Name; //eg. '?param1' PostgreSQL paramNames.Add(paramName); System.Data.ParameterDirection direction = GetDirection(paramInfo, paramAttrib); //MySqlDbType dbType = MySqlTypeConversions.ParseType(paramAttrib.DbType); IDbDataParameter cmdParam = command.CreateParameter(); cmdParam.ParameterName = paramName; //cmdParam.Direction = System.Data.ParameterDirection.Input; if (direction == ParameterDirection.Input || direction == ParameterDirection.InputOutput) { object inputValue = inputValues[currInputIndex++]; cmdParam.Value = inputValue; } else { cmdParam.Value = null; } cmdParam.Direction = direction; command.Parameters.Add(cmdParam); } if (!functionAttrib.IsComposable) { //procedures: under the hood, this seems to prepend 'CALL ' command.CommandType = System.Data.CommandType.StoredProcedure; } else { //functions: 'SELECT myFunction()' or 'SELECT hello(?s)' string cmdText = "SELECT " + command.CommandText + "($args)"; cmdText = cmdText.Replace("$args", string.Join(",", paramNames.ToArray())); command.CommandText = cmdText; } if (method.ReturnType == typeof(DataSet)) { //unknown shape of resultset: System.Data.DataSet dataSet = new DataSet(); IDbDataAdapter adapter = CreateDataAdapter(context); adapter.SelectCommand = command; adapter.Fill(dataSet); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(dataSet, outParamValues.ToArray()); } else { object obj = command.ExecuteScalar(); List<object> outParamValues = CopyOutParams(paramInfos, command.Parameters); return new ProcedureResult(obj, outParamValues.ToArray()); } } }
private void CloseAllOpenConnections(LinqDataContext ctx) { ctx.Log = new StringWriter(); if (ctx.DatabaseExists()) { //drop all connections by disabling multi-user (and immediatly abort all current transactions) ctx.ExecuteCommand("ALTER DATABASE " + _databaseName + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE"); //re-enable multi-user ctx.ExecuteCommand("ALTER DATABASE " + _databaseName + " SET MULTI_USER"); } }
/// <summary> /// Initializes the repository. /// </summary> public void InitializeRepository() { IEnumerable<Type> dataTypes = CoreIntelligence.PluginIntelligence.LoadedPluginTypes.Where(x => x.IsSubclassOf(typeof(BaseDataPlugin))); BaseDataPlugin plugin = null; if (dataTypes.Count() > 0) { plugin = (BaseDataPlugin)CoreIntelligence.PluginIntelligence.TryCreatingInstance(dataTypes.FirstOrDefault()); } if (plugin != null) { _plugin = plugin; _context = new System.Data.Linq.DataContext(_plugin.Database); _dbLogBridge = new TextWriterEasySocialLogBridge(CoreIntelligence); _context.Log = _dbLogBridge; installSocialIntelligence(); } else { //throw new Exception("There was no repository found."); } }