Example #1
0
        static void Main(string[] args)
        {
            DataContext dc = new DataContext(@"Data Source=.\sqlexpress;Initial Catalog=vs2010;Integrated Security=True");

            dc.Log = Console.Out;

            Table<Filho> filhosDoAdao = dc.GetTable<Filho>();

            ObjectDumper.Write(filhosDoAdao);
            Console.WriteLine();

            Filho ooops = new Filho() { NomeFilho = "TIANA", CodigoPessoa = 1 };

            filhosDoAdao.InsertOnSubmit(ooops);
            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Filho>());
            Console.WriteLine();

            filhosDoAdao.DeleteOnSubmit(ooops);
            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Filho>());

            Console.ReadKey();
        }
Example #2
0
        static void Main(string[] args)
        {
            // Use a standard connection string
            DataContext db = new DataContext(@"Data Source=REMAN-NOTEBOOK\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
            Table<Customer> Customers = db.GetTable<Customer>();

            // Logging
            db.Log = Console.Out;

            // CREATE
            Customer newCostumer = new Customer();
            newCostumer.City = "Dresden";
            newCostumer.Address = "Riesaer Str. 5";
            newCostumer.CustomerID = "DDMMS";
            newCostumer.CompanyName = "T-Systems MMS";

            Customers.InsertOnSubmit(newCostumer);
            db.SubmitChanges();
            
            // READ
            var custs =
                from c in Customers
                where c.City == "Dresden"
                select c;

            // Debugging - Console.WriteLine
            foreach (var cust in custs)
            {
                Console.WriteLine("ID={0}, City={1}, Address={2}", cust.CustomerID, cust.City, cust.Address);
            }
            
            // UPDATE
            var upObjects = from test in Customers
                             where test.CompanyName == "T-Systems MMS"
                             select test;

            upObjects.First().Address = "Straße";
            db.SubmitChanges();

            // Debugging - Console.WriteLine
            foreach (var cust in custs)
            {
                Console.WriteLine("ID={0}, City={1}, Address={2}", cust.CustomerID, cust.City, cust.Address);
            }

            // DEL
            var delObjects = from test in Customers 
                             where test.CompanyName == "T-Systems MMS"
                             select test;

            Customers.DeleteOnSubmit(delObjects.First());
            db.SubmitChanges();
            
            Console.ReadLine();
        }
 public void inserirConta(Conta c)
 {
     DataContext dc = new DataContext(@"Data Source=wv-toshiba\instancia1;Initial Catalog=ASI;User ID=sa;Password=123");
     Table<Conta> tc = dc.GetTable<Conta>();
     tc.InsertOnSubmit(c);
     dc.SubmitChanges();
 }
Example #4
0
        private void button12_Click(object sender, EventArgs e)
        {
            var dc = new DataContext(@"server=localhost\sqlexpress;database=loja;integrated security=true");
            var produtos = dc.GetTable<ProdutoInfo>();

            //Obter uma instancia
            var produto = (from p in produtos
                           where p.Codigo == 2
                           select p).FirstOrDefault();

            if (produto == null)
            {
                MessageBox.Show("Produto não encontrado");
                return;
            }

            //marcar para excluir
            produtos.DeleteOnSubmit(produto);

            //Confirmar
            dc.SubmitChanges();
            MessageBox.Show("Produto excluido com sucesso");



        }
Example #5
0
        static void Main(string[] args)
        {
            DataContext dc = new DataContext(@"Data Source=.\sqlexpress;Initial Catalog=vs2010;Integrated Security=True");

            dc.Log = Console.Out;

            var filhosDoAdao = from f in dc.GetTable<Filho>()
                                  where f.CodigoPessoa == 1
                                  select f;

            ObjectDumper.Write(filhosDoAdao);

            Console.WriteLine();

            foreach (Filho filho in filhosDoAdao)
            {
                filho.NomeFilho += "*";
            }

            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Filho>());

            Console.ReadKey();
        }
 public void inserirConta(Conta c)
 {
     DataContext dc = new DataContext(@"Data Source=MIRANDA-LAPTOP\SQL2012DEINST1;Initial Catalog=ASI;Integrated Security=true");//TODO: CONFIGURATION FILE!
     Table<Conta> tc = dc.GetTable<Conta>();
     tc.InsertOnSubmit(c);
     dc.SubmitChanges();
 }
        public void SendMessageToVP(string MessgeID, VPMsg msg)
        {
            DataContext writeMsgHere = new DataContext(DataConnectionString);

            writeMsgHere.Msgs.Add(msg);

            writeMsgHere.SubmitChanges();
        }
 public static CommitDBResult CommitChanges(DataContext _checkoutDataContext, int _userID)
 {
     _checkoutDataContext.SubmitChanges(ConflictMode.FailOnFirstConflict);
     if (_checkoutDataContext.ChangeConflicts == null)
         return CommitDBResult.Success;
     else
         return CommitDBResult.Fail;
 }
        private static void WriteUpdatesAndDeletes(DataContext _dataContext, DataContext _historyDataContext, int _userID)
        {
            //EntitiesToInsert = _dataContext.GetChangeSet().Inserts;

            ProcessUpdateItems(_dataContext, _historyDataContext, _userID);
            ProcessDeleteItems(_dataContext, _historyDataContext, _userID);
            _historyDataContext.SubmitChanges();
        }
		private static void Flush(DataContext context)
		{
			var changeSet = context.GetChangeSet();
			changeSet.Inserts.OfType<ISavingChangesEventHandler>().ToList().ForEach(x => x.OnInsert());
			changeSet.Updates.OfType<ISavingChangesEventHandler>().ToList().ForEach(x => x.OnUpdate());
			changeSet.Deletes.OfType<ISavingChangesEventHandler>().ToList().ForEach(x => x.OnDelete());

			context.SubmitChanges();
		}
        static void Main(string[] args)
        {
            string connString = "Server=(LocalDb)\\MSSQLLocalDb;Integrated Security=true;database=AdventureWorksDW2014";
            DataContext context = new DataContext(connString);

            var tableProd = context.GetTable<Product>();
            var products = from prod in tableProd
                           where prod.Color == "Black"
                           select prod;

            foreach (Product p in products)
            {
                Console.WriteLine(p.EnglishProductName);
            }

            Product product = products.First();
            product.Color = "Red";
            context.SubmitChanges();

            AdventureWorksDataContext awdc = new AdventureWorksDataContext(connString);
            var categories = awdc.DimProductCategories;

            foreach (DimProductCategory pc in categories)
            {
                Console.WriteLine(pc.EnglishProductCategoryName);
                foreach (var sub in pc.DimProductSubcategories)
                {
                    Console.WriteLine(sub.EnglishProductSubcategoryName);
                    foreach (var pd in sub.DimProducts)
                        Console.WriteLine("   {0}", pd.EnglishProductName);
                }
            }

            var query = from cat in categories
                        from sub in cat.DimProductSubcategories
                        from prod in sub.DimProducts
                        where cat.EnglishProductCategoryName.Contains("Bikes")
                        select prod;

            foreach (var p in query)
            {
                Console.WriteLine("{0}", p.EnglishProductName);
            }

            awdc.DimProducts.First().Color = "Dark Red";
            awdc.SubmitChanges();

            DimProductCategory newCat = new DimProductCategory();
            newCat.EnglishProductCategoryName = "New Category 1";
            newCat.SpanishProductCategoryName = "Nueva Categoria 1";
            newCat.FrenchProductCategoryName = "Nouvelle Categorie 1";
            awdc.DimProductCategories.InsertOnSubmit(newCat);
            awdc.SubmitChanges();
        }
Example #12
0
        //Metodo para la comunicacion con la BD y llamar al SP
        public static void Agregar(int idvuelo, string origen, string destino, int millas, string fecha, int idavion, Decimal precioDolar)
        {
            DataContext dc = new DataContext(myConnection.getConnection());
            var Customers = dc.GetTable<tablaVuelo>();

            var insert = dc.GetTable<tablaVuelo>();

            tablaVuelo newInsert = new tablaVuelo { ID_VUELO = idvuelo, ORIGEN = origen, DESTINO = destino, MILLAS = millas, FECHA = fecha, ID_AVION = idavion, PRECIO_DOLARES = precioDolar,ID_TICKET=0 };
            insert.InsertOnSubmit(newInsert);
            dc.SubmitChanges();
        }
 private static void SaveChanges(DataContext db)
 {
     try
     {
         db.SubmitChanges();
         Console.WriteLine("Success");
     }
     catch (ChangeConflictException)
     {
         db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
         Console.WriteLine("Failure");
     }
 }
Example #14
0
        static void Main(string[] args)
        {
            DataContext dc = new DataContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True");

            //dc.Log = Console.Out;

            Pessoa pessoa = new Pessoa() { CodigoPessoa = 5, NomePessoa = "Cobra", SexoPessoa = 'F' };

            dc.GetTable<Pessoa>().InsertOnSubmit(pessoa);
            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Pessoa>());

            Console.WriteLine();

            dc.GetTable<Pessoa>().DeleteOnSubmit(pessoa);
            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Pessoa>());

            Console.ReadKey();
        }
        //private static IList<object> EntitiesToInsert;

        public static CommitDBResult CommitChanges(DataContext _dataContext, DataContext _historyDataContext, int _userID)
        {
            CommitDBResult commitDBResult = CommitDBResult.Success;
            CheckForInvalidVersions(_dataContext);
            SetAuditInfo(_dataContext, _userID);
            WriteUpdatesAndDeletes(_dataContext, _historyDataContext, _userID);

            _dataContext.SubmitChanges(ConflictMode.FailOnFirstConflict);

            // History de current item union ile gerçek tabloya bağlanılarak çekiliyor. Dolayısıyla insert changeset ini history ye atmaya gerek kalmıyor.
            //ProcessInsertItems(_dataContext, _historyDataContext, _userID);

            return commitDBResult;
        }
        public void UserClassTest()
        {
            // Arrange
            // Create the user.
            User user = new User();
            user.UserName = "******";
            user.Password = "******";
            user.FirstName = "Ke";
            user.LastName = "Sun";
            user.Email = "*****@*****.**";
            user.PrivilegeType = User.Privilege.Admin;
            user.RegistrationDate = DateTime.Now;
            user.LoginDate = DateTime.Now;

            // Act
            // Submit the user.
            try
            {
                using (DataContext userDataContext = new DataContext(Constants.DatabaseConnectionString))
                {
                    Table<User> userTable = userDataContext.GetTable<User>();

                    userTable.InsertOnSubmit(user);
                    userDataContext.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
            }

            user = null;

            // Retrieve the user.
            try
            {
                using (DataContext userDataContext = new DataContext(Constants.DatabaseConnectionString))
                {
                    Table<User> userTable = userDataContext.GetTable<User>();

                    user = (from userEntity in userTable where userEntity.UserName == "ksun" select userEntity).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
            }

            // Assert
            Assert.IsNotNull(user);
        }
Example #17
0
        public void TransferirSessionFull(int c1, int c2, float montante)
        {

            Console.WriteLine("Transferir session full" + montante + " euros de " + c1 + " para " + c2);

            DataContext dc = new DataContext(@"Data Source=wv-toshiba\instancia1;Initial Catalog=ASI;User ID=sa;Password=123");
            Table<Conta> tc = dc.GetTable<Conta>();
            var conta1 = (from c in dc.GetTable<Conta>()
                          where c.Numero == c1
                          select c).SingleOrDefault();
            var conta2 = (from c in dc.GetTable<Conta>()
                          where c.Numero == c2
                          select c).SingleOrDefault();

            conta1.Saldo -= montante;
            dc.SubmitChanges();
            conta2.Saldo += montante;
            dc.SubmitChanges();


            Console.WriteLine("Fim de transferir session full");


        }
Example #18
0
 public void alterarConta(Conta c)
 {
     DataContext dc = new DataContext(@"Data Source=wv-toshiba\instancia1;Initial Catalog=ASI;User ID=sa;Password=123");
     Table<Conta> tc = dc.GetTable<Conta>();
     tc.Attach(c, true);
     try
     {
         dc.SubmitChanges(ConflictMode.ContinueOnConflict);
     }
     catch (ChangeConflictException e)
     {
         dc.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues); // last -in - wins
         dc.SubmitChanges();
     }
 }
Example #19
0
        //nuevo
        public void asignarVueloEnAsientos(int idAvion, int idVuelo)
        {
            DataContext dc = new DataContext(myConnection.getConnection());
            var tabla = dc.GetTable<TablaAsientos>();
            var asientos = from a in tabla
                           where a.ID_AVION.Equals(idAvion)
                           select a;

            foreach (var asiento in asientos)
            {
                asiento.ID_VUELO = idVuelo;
            }

            dc.SubmitChanges();
        }
Example #20
0
        private void button10_Click(object sender, EventArgs e)
        {
            var dc = new DataContext(@"server=localhost\sqlexpress;database=loja;integrated security=true");
            var produtos = dc.GetTable<ProdutoInfo>();

            var p = new ProdutoInfo();
            p.Nome = "Novo Produto";
            p.Preco = 100;
            p.Estoque = 2;
            

            produtos.InsertOnSubmit(p);

            dc.SubmitChanges();
            MessageBox.Show("Produto incluido com sucesso");
        }
Example #21
0
        private void button11_Click(object sender, EventArgs e)
        {
            var dc = new DataContext(@"server=localhost\sqlexpress;database=loja;integrated security=true");
            var produtos = dc.GetTable<ProdutoInfo>();
            
            //Obter uma instancia
            var produto = (from p in produtos
                           where p.Codigo == 1
                           select p).FirstOrDefault();

            //Alterar os dados
            produto.Nome = "Alterado";
            produto.Estoque += 1;

            //Gravar
            dc.SubmitChanges();
        }
		private static void ClearTpDB(DataContext tpDatabaseDataContext)
		{
            if (!tpDatabaseDataContext.DatabaseExists())
            {
                tpDatabaseDataContext.CreateDatabase();
                tpDatabaseDataContext.SubmitChanges();
            }
            else
            {
                tpDatabaseDataContext.ExecuteCommand("delete from Project");
                tpDatabaseDataContext.ExecuteCommand("delete from TpUser");
                tpDatabaseDataContext.ExecuteCommand("delete from General");
                tpDatabaseDataContext.ExecuteCommand("delete from MessageUid");
                tpDatabaseDataContext.ExecuteCommand("delete from PluginProfile");
                tpDatabaseDataContext.ExecuteCommand("delete from Revision");  
            }
		}
Example #23
0
        public void alterarConta(Conta c)
        {
            MessageBox.Show("AlterarConta");
            Console.WriteLine("AlterarConta");

            DataContext dc = new DataContext(@"Data Source=wv-toshiba\instancia1;Initial Catalog=ASI;User ID=sa;Password=123");
            Table<Conta> tc = dc.GetTable<Conta>();
            tc.Attach(c, true);
            try
            {
                dc.SubmitChanges(ConflictMode.ContinueOnConflict);
                MessageBox.Show("Conta alterada");

            }
            catch (ChangeConflictException e)
            {
                MessageBox.Show("Erro ao alterar a conta");
                throw;
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            DataContext dc = new DataContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True");

            dc.Log = Console.Out;

            var pessoas = from p in dc.GetTable<Pessoa>()
                          select p;

            ObjectDumper.Write(pessoas);

            Console.WriteLine();

            foreach (Pessoa p in pessoas)
            {
                p.Nome += "*";
            }

            dc.SubmitChanges();

            ObjectDumper.Write(dc.GetTable<Pessoa>());

            Console.ReadKey();
        }
Example #25
0
        public static string SerializeForLog(this ChangeConflictException e, DataContext context)
        {
            StringBuilder builder = new StringBuilder();

            using (StringWriter sw = new StringWriter(builder))
            {
                sw.WriteLine("Optimistic concurrency error:");
                sw.WriteLine(e.Message);

                foreach (ObjectChangeConflict occ in context.ChangeConflicts)
                {
                    Type      objType          = occ.Object.GetType();
                    MetaTable metatable        = context.Mapping.GetTable(objType);
                    object    entityInConflict = occ.Object;

                    sw.WriteLine("Table name: {0}", metatable.TableName);

                    var noConflicts =
                        from property in objType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        where property.CanRead &&
                        property.CanWrite &&
                        property.GetIndexParameters().Length == 0 &&
                        !occ.MemberConflicts.Any(c => c.Member.Name != property.Name)
                        orderby property.Name
                        select property;

                    foreach (var property in noConflicts)
                    {
                        sw.WriteLine("\tMember: {0}", property.Name);
                        sw.WriteLine("\t\tCurrent value: {0}",
                                     property.GetGetMethod().Invoke(occ.Object, new object[0]));
                    }

                    sw.WriteLine("\t-- Conflicts Start Here --");

                    foreach (MemberChangeConflict mcc in occ.MemberConflicts)
                    {
                        sw.WriteLine("\tMember: {0}", mcc.Member.Name);
                        sw.WriteLine("\t\tCurrent value: {0}", mcc.CurrentValue);
                        sw.WriteLine("\t\tOriginal value: {0}", mcc.OriginalValue);
                        sw.WriteLine("\t\tDatabase value: {0}", mcc.DatabaseValue);
                    }

                    sw.WriteLine("\t-- Conflicts End --");
                }

                sw.WriteLine();
                sw.WriteLine("Attempted SQL: ");

                TextWriter tw = context.Log;

                try
                {
                    context.Log = sw;
                    context.SubmitChanges();
                }
                catch (ChangeConflictException)
                {
                }
                catch
                {
                    sw.WriteLine("Unable to recreate SQL!");
                }
                finally
                {
                    context.Log = tw;
                }

                sw.WriteLine();
            }

            return(builder.ToString());
        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (CurrentUser.type != 0)
            {
                if (Login.Text != "")
                {
                    if (Password.Password != "" && Password.Password.Length >= 5)
                    {
                        CurrentUser.name     = Login.Text;
                        CurrentUser.password = Password.Password;
                        reg = new REG();

                        if (CurrentUser.type == 2)
                        {
                            var r = from o in org where o.orgname == Login.Text select o.Idorg;
                            if (r.Max() == null)
                            {
                                reg.Login    = Login.Text;
                                reg.Password = Password.Password;
                                Treg.InsertOnSubmit(reg);
                                NewOrg       = new org();
                                NewOrg.Idorg = (from o in org select o.Idorg).Max() + 1;
                                if (NewOrg.Idorg == null)
                                {
                                    NewOrg.Idorg = 1;
                                }
                                NewOrg.orgname = Login.Text;
                                org.InsertOnSubmit(NewOrg);
                                try
                                {
                                    db.SubmitChanges();
                                    MessageBox.Show("Компания зарегистрирована!\nВаш логин: " + reg.Login + "\nВаш пароль: " + reg.Password);
                                    CurrentUser.flag = false;
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Ошибка регистрации!");
                                }
                                finally
                                {
                                    ch?.Invoke(this, new EventArgs());
                                    if (CurrentUser.flag == false)
                                    {
                                        this.Close();
                                    }
                                    this.Close();
                                }
                            }
                            else
                            {
                                MessageBox.Show("Компания уже зарегистрирована.");
                            }
                        }
                        if (CurrentUser.type == 1)
                        {
                            var r = from a in Treg where a.Login == Login.Text select a.Login;
                            if (r.Max() == null)
                            {
                                reg.Login    = Login.Text;
                                reg.Password = Password.Password;
                                Treg.InsertOnSubmit(reg);
                                try
                                {
                                    db.SubmitChanges();
                                    MessageBox.Show("Вы успешно зарегистрированы!\nВаш логин: " + reg.Login + "\nВаш пароль: " + reg.Password);
                                    CurrentUser.flag = false;
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Ошибка регистрации!");
                                }
                                finally
                                {
                                    ch?.Invoke(this, new EventArgs());
                                    if (CurrentUser.flag == false)
                                    {
                                        this.Close();
                                    }
                                    this.Close();
                                }
                            }
                            else
                            {
                                MessageBox.Show("Пользователь с таким именем уже есть.");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Введите корректный пароль (не менее 5 символов)");
                    }
                }
                else
                {
                    MessageBox.Show("Введите логин");
                }
            }
            else
            {
                MessageBox.Show("Кто же вы?");
            }
        }
Example #27
0
        //inactiva cliente con criterios
        public static void inactivarCliente(int id,string estado)
        {
            DataContext dataContext = new DataContext(myConnection.getConnection());
            var tabla = dataContext.GetTable<tablaCliente>();

            var cliente = from c in tabla
                          where c.ID_CLIENTE.Equals(id)
                          select c;

            foreach (var c in cliente)
            {
                c.CONDICION = estado;
            }

            dataContext.SubmitChanges();
        }
        public void PostClassTest()
        {
            Post post = new Post();
            post.Title = "A Test Post";
            post.Date = DateTime.Now;
            post.MediaType = Post.Media.Article;
            post.Content = "Yeppy Tai Yai Yay!";
            post.Flagged = false;

            // Submit a post.
            try
            {
                using (DataContext postDataContext = new DataContext(Constants.DatabaseConnectionString))
                {
                    Table<Post> postTable = postDataContext.GetTable<Post>();

                    postTable.InsertOnSubmit(post);
                    postDataContext.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
            }

            post = null;

            // Retrieve the post.
            try
            {
                using (DataContext postDataContext = new DataContext(Constants.DatabaseConnectionString))
                {
                    Table<Post> postTable = postDataContext.GetTable<Post>();

                    post = (from postEntity in postTable where postEntity.Title.Contains("Test") select postEntity).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
            }

            Assert.IsNotNull(post);
        }
        public void VoteClassTest()
        {
            Vote vote1 = new Vote { ParentID = 1, ParentType = Vote.Parent.Comment, Value = 1 };
            Vote vote2 = new Vote { ParentID = 1, ParentType = Vote.Parent.Comment, Value = -1 };
            Vote vote3 = new Vote { ParentID = 1, ParentType = Vote.Parent.Comment, Value = -1 };
            Vote vote4 = new Vote { ParentID = 1, ParentType = Vote.Parent.Comment, Value = -1 };
            Vote vote5 = new Vote { ParentID = 1, ParentType = Vote.Parent.Comment, Value = 1 };

            // Submit a bunch of votes for a comment.
            using (DataContext voteDataContext = new DataContext(Constants.DatabaseConnectionString))
            {
                Table<Vote> voteTable = voteDataContext.GetTable<Vote>();

                voteTable.InsertOnSubmit(vote1);
                voteTable.InsertOnSubmit(vote2);
                voteTable.InsertOnSubmit(vote3);
                voteTable.InsertOnSubmit(vote4);
                voteTable.InsertOnSubmit(vote5);

                voteDataContext.SubmitChanges();
            }

            // Count the total number of votes.
            using (DataContext voteDataContext = new DataContext(Constants.DatabaseConnectionString))
            {
                Table<Vote> voteTable = voteDataContext.GetTable<Vote>();

                var voteCount = (from voteEntity in voteTable 
                                 where voteEntity.ParentID == 1 && voteEntity.ParentType == Vote.Parent.Comment 
                                 select voteEntity.Value).Sum();
            }
        }
Example #30
0
 /// <summary>
 /// 插入
 /// </summary>
 /// <param name="database"></param>
 public void Insert(DataContext database)
 {
     InsertWhenSubmit(database);
     database.SubmitChanges();
 }
Example #31
0
        internal void DeleteListItem(int summeryId, int sourceId, SRL_Ingredient ingredient)
        {
            using (DataContext)
            {
                try
                {
                    SummerySource summerySource = (from p in DataContext.SummerySources
                                                   where
                                                   p.SUMMERY_ID == summeryId && p.SOURCE_ID == sourceId &&
                                                   p.FOOD_ID == ingredient.FoodId
                                                   select p).SingleOrDefault();
                    if (summerySource != null)
                    {
                        summerySource.QUANTITY -= ingredient.Quantity;
                        if (summerySource.QUANTITY <= 0)
                        {
                            DataContext.SummerySources.DeleteOnSubmit(summerySource);
                        }
                    }

                    // ReCalculate summery list
                    IQueryable <decimal?> summerySources = from p in DataContext.SummerySources where p.SUMMERY_ID == summeryId && p.FOOD_ID == ingredient.FoodId select p.QUANTITY;
                    decimal?sum = summerySources.Sum() - ingredient.Quantity;

                    SummeryListDetail summeryListDetail = (from p in DataContext.SummeryListDetails
                                                           where p.LIST_ID == summeryId && p.FOOD_ID == ingredient.FoodId
                                                           select p).SingleOrDefault();

                    if (summeryListDetail == null)
                    {
                        if (sum > 0)
                        {
                            summeryListDetail = new SummeryListDetail
                            {
                                FOOD_ID             = ingredient.FoodId,
                                FOOD_NAME           = ingredient.FoodName,
                                LIST_ID             = summeryId,
                                QUANTITY            = sum.HasValue ? sum.Value : 0,
                                MEASUREMENT_UNIT_ID = ingredient.MeasurementUnitId,
                                MEASUREMENT_UNIT    = ingredient.MeasurementUnitName
                            };
                            DataContext.SummeryListDetails.InsertOnSubmit(summeryListDetail);
                        }
                    }
                    else
                    {
                        if (sum == 0)
                        {
                            DataContext.SummeryListDetails.DeleteOnSubmit(summeryListDetail);
                        }
                        else
                        {
                            summeryListDetail.QUANTITY = sum.HasValue ? sum.Value : 0;
                        }
                    }

                    DataContext.SubmitChanges();
                }
                catch (Exception)
                {
                }
            }
        }
Example #32
0
 protected void UpdateAndSubmitChangesCore(DbFileSystemItem dbitem, Action <DbFileSystemItem> update)
 {
     update(dbitem);
     DataContext.SubmitChanges();
     RefreshFolderCache();
 }
Example #33
0
        /// <summary>
        /// Constructor to wrap the "using" of SqlConnection, SqlTransaction, and DataContext
        /// </summary>
        /// <param name="tones"></param>
        /// <param name="actionToAnalyze"></param>
        public WatsonResultsTransaction(Utterance utterance, ActionToAnalyze actionToAnalyze, Action <WatsonTransactionCallback> callback)
        {
            List <Tones> tones = utterance.tones;

            if (tones == null)
            {
                return; // ?
            }
            // open the connection
            try
            {
                _singleThreadedTransactions.WaitOne();
                string connectionString = ConfigurationManager.AppSettings.Get("ConnectionString");
                _connection = new SqlConnection(connectionString); // using
                _connection.Open();                                // connection must be open to begin transaction

                // start the transaction
                _transaction = _connection.BeginTransaction();  // using

                // create a data context
                _db             = new DataContext(_connection); // using
                _db.Transaction = _transaction;

                // insert ActionSentiment
                ActionSentiment sentiment = InsertActionSentiment(_db, actionToAnalyze);
                _db.SubmitChanges();    // get the DB generated ID
                int actionSentimentID = sentiment.ActionSentimentID;

                // insert child records - ActionSentimentScore(s)
                List <ActionSentimentScore> scores = InsertSentimentScores(tones, _db, actionSentimentID);

                // Delete ActionToAnalyze
                actionToAnalyze.DeleteOnSubmit(_db);
                _db.SubmitChanges();

                if (callback != null)
                {
                    WatsonTransactionCallback transaction = new WatsonTransactionCallback()
                    {
                        _db        = _db,
                        _sentiment = sentiment,
                        _scores    = scores
                    };
                    callback(transaction);
                }

                // Success!
                _transaction.Commit();
            }
            catch (Exception e)
            {
                if (_transaction != null)
                {
                    _transaction.Rollback();
                }

                EventLog.WriteEntry(EVENT_SOURCE, "********************PublishToTable SubmitTransaction: Exception " + e.Message + " ### " + e.Source + " ### " + e.StackTrace.ToString());
                Console.WriteLine("Exception at insert into Action Sentiment:" + e.Message + "###" + e.Source + " ----- STACK: " + e.StackTrace.ToString());
            }
            finally
            {
                _singleThreadedTransactions.ReleaseMutex();
            }
        }
Example #34
0
        private void addPhasenForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!addPhaseForm.editMode && addPhaseForm.DialogResult == DialogResult.OK)
            {
                if (addPhaseForm.BezeichnungTextBox.Text.Length > 1 && !addPhaseForm.BezeichnungTextBox.Text.Equals("") &&
                    addPhaseForm.PhasenFortschrittTextBox.Text.Length >= 1 && !addPhaseForm.PhasenFortschrittTextBox.Text.Equals("") &&
                    addPhaseForm.StatusTextBox.Text.Length > 1 && !addPhaseForm.StatusTextBox.Text.Equals("") &&
                    addPhaseForm.StartdatumGeplantDatePicker.Text.Length > 2 && !addPhaseForm.StartdatumGeplantDatePicker.Text.Equals("") &&
                    addPhaseForm.EnddatumGeplantDatePicker.Text.Length > 2 && !addPhaseForm.EnddatumGeplantDatePicker.Text.Equals("") &&
                    addPhaseForm.ReviewdatumGeplantDatePicker.Text.Length > 2 && !addPhaseForm.ReviewdatumGeplantDatePicker.Text.Equals(""))
                {
                    //Connect auf Tabelle inkl. dem Mapping
                    Table <Phase> phaseTableDefinition = dbContext.GetTable <Phase>();

                    //neuer Eintrag erstellen
                    string   bezeichnung        = addPhaseForm.BezeichnungTextBox.Text;
                    int      fortschritt        = Int32.Parse(addPhaseForm.PhasenFortschrittTextBox.Text);
                    string   status             = addPhaseForm.StatusTextBox.Text;
                    DateTime startdatumGeplant  = addPhaseForm.StartdatumGeplantDatePicker.Value;
                    DateTime enddatumGeplant    = addPhaseForm.EnddatumGeplantDatePicker.Value;
                    DateTime reviewdatumGeplant = addPhaseForm.ReviewdatumGeplantDatePicker.Value;

                    DateTime?freigabedatum = null;
                    if (addPhaseForm.FreigabedatumDatePicker.Enabled)
                    {
                        freigabedatum = addPhaseForm.FreigabedatumDatePicker.Value;
                    }

                    DateTime?startdatumEffeftiv = null;
                    if (addPhaseForm.StartdatumEffektivDatePicker.Enabled)
                    {
                        startdatumEffeftiv = addPhaseForm.StartdatumEffektivDatePicker.Value;
                    }
                    DateTime?enddatumEffektiv = null;
                    if (addPhaseForm.EnddatumEffektivDatePicker.Enabled)
                    {
                        enddatumEffektiv = addPhaseForm.EnddatumEffektivDatePicker.Value;
                    }
                    DateTime?reviewdatumEffektiv = null;
                    if (addPhaseForm.ReviewdatumEffektivDatePicker.Enabled)
                    {
                        enddatumEffektiv = addPhaseForm.ReviewdatumEffektivDatePicker.Value;
                    }

                    Phase phase = new Phase();
                    phase.bezeichnung         = bezeichnung;
                    phase.phasenfortschritt   = fortschritt;
                    phase.phasenstatus        = status;
                    phase.startdatumGeplant   = startdatumGeplant;
                    phase.startdatumEffektiv  = startdatumEffeftiv ?? null;
                    phase.enddatumGeplant     = enddatumGeplant;
                    phase.enddatumEffektiv    = enddatumEffektiv ?? null;
                    phase.reviewdatumGeplant  = reviewdatumGeplant;
                    phase.reviewdatumEffektiv = reviewdatumEffektiv ?? null;
                    phase.freigabedatum       = freigabedatum ?? null;

                    phaseTableDefinition.InsertOnSubmit(phase);

                    //Aenderung auf DB auslösen
                    dbContext.SubmitChanges();

                    updateVorgehensmodelPhaseReference(phase.phaseId);
                    addDefaultMeilensteinForPhase(phase.phaseId);

                    // datagrid neu befüllen
                    loadPhasenDataGrid();
                }
                else
                {
                    MessageBox.Show("Es wurden nicht alle Pflichtfelder ausgefüllt! (Diese sind mit * versehen)");
                }
            }
        }
        /// <summary>
        /// フォルダ参照ボタンクリックイベント.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fld_button_Click(object sender, RoutedEventArgs e)
        {
            // ダイアログ生成
            CommonOpenFileDialog dlg = new CommonOpenFileDialog();

            // パラメタ設定

            // タイトル
            dlg.Title = "フォルダ選択";
            // フォルダ選択かどうか
            dlg.IsFolderPicker = true;
            // 初期ディレクトリ
            dlg.InitialDirectory = @"c:\";
            // ファイルが存在するか確認する
            //dlg.EnsureFileExists = false;
            // パスが存在するか確認する
            //dlg.EnsurePathExists = false;
            // 読み取り専用フォルダは指定させない
            //dlg.EnsureReadOnly = false;
            // コンパネは指定させない
            //dlg.AllowNonFileSystemItems = false;

            //ダイアログ表示
            var Path = dlg.ShowDialog();

            if (Path == CommonFileDialogResult.Ok)
            {
                // 選択されたフォルダ名を取得、格納されているCSVを読み込む
                List <Cat> list = readFiles(dlg.FileName);

                // 接続
                int count = 0;
                using (var conn = new SQLiteConnection("Data Source=SampleDb.sqlite"))
                {
                    conn.Open();

                    // データを追加する
                    using (DataContext context = new DataContext(conn))
                    {
                        foreach (Cat cat in list)
                        {
                            // 対象のテーブルオブジェクトを取得
                            var table = context.GetTable <Cat>();
                            // データが存在するかどうか判定
                            if (table.SingleOrDefault(x => x.No == cat.No) == null)
                            {
                                // データ追加
                                table.InsertOnSubmit(cat);
                                // DBの変更を確定
                                context.SubmitChanges();
                                count++;
                            }
                        }
                    }
                    conn.Close();
                }

                MessageBox.Show(count + " / " + list.Count + " 件 のデータを取り込みました。");

                // データ再検索
                searchData();
            }
        }
Example #36
0
        public Message Add(IoT_Pricing info, List <IoT_PricingMeter> meterList)
        {
            // 定义执行结果
            Message m;
            string  configName = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            //Linq to SQL 上下文对象
            DataContext dd = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString);

            try
            {
                //获取价格信息
                IoT_PricePar priceInfo = dd.GetTable <IoT_PricePar>().Where(p =>
                                                                            p.CompanyID == info.CompanyID && p.ID == int.Parse(info.PriceType)).SingleOrDefault();

                info.Price1 = priceInfo.Price1 == null ? 0 : priceInfo.Price1;
                info.Gas1   = priceInfo.Gas1 == null ? 0 : priceInfo.Gas1;
                info.Price2 = priceInfo.Price2 == null ? 0 : priceInfo.Price2;
                info.Gas2   = priceInfo.Gas2 == null ? 0 : priceInfo.Gas2;
                info.Price3 = priceInfo.Price3 == null ? 0 : priceInfo.Price3;
                info.Gas3   = priceInfo.Gas3 == null ? 0 : priceInfo.Gas3;
                info.Price4 = priceInfo.Price4 == null ? 0 : priceInfo.Price4;
                info.Gas4   = priceInfo.Gas4 == null ? 0 : priceInfo.Gas4;
                info.Price5 = priceInfo.Price5 == null ? 0 : priceInfo.Price5;

                info.IsUsed         = priceInfo.IsUsed == null ? false : priceInfo.IsUsed;
                info.Ladder         = priceInfo.Ladder == null ? 3 : priceInfo.Ladder;
                info.SettlementType = priceInfo.SettlementType;
                info.MeterType      = "01";

                //设置调价计划参数和条件任务
                string result = new SetMeterParameter().SetPricingPlan(info, meterList);
                if (result != "")
                {
                    throw new Exception(result);
                }


                Table <IoT_Pricing> tbl = dd.GetTable <IoT_Pricing>();
                // 调用新增方法
                tbl.InsertOnSubmit(info);
                // 更新操作
                dd.SubmitChanges();

                Table <IoT_PricingMeter> tbl_meter = dd.GetTable <IoT_PricingMeter>();
                foreach (IoT_PricingMeter meter in meterList)
                {
                    IoT_Meter tempMeter = MeterManageService.QueryMeter(meter.MeterNo);
                    meter.MeterID = tempMeter.ID;
                    meter.ID      = info.ID;
                    meter.Context = info.Context;
                    meter.State   = '0';//申请
                    tbl_meter.InsertOnSubmit(meter);
                }
                // 更新操作
                dd.SubmitChanges();

                m = new Message()
                {
                    Result     = true,
                    TxtMessage = JSon.TToJson <IoT_Pricing>(info)
                };
            }
            catch (Exception e)
            {
                m = new Message()
                {
                    Result     = false,
                    TxtMessage = "新增调价计划失败!" + e.Message
                };
            }
            return(m);
        }
Example #37
0
 public void SaveReparation(Reparation reparation)
 {
     DataContext.Reparations.InsertOnSubmit(reparation);
     DataContext.SubmitChanges();
 }
Example #38
0
        internal bool AddListItem(SRL_Ingredient ingredient, int listId, int sourceId)
        {
            using (DataContext)
            {
                SummeryListDetail summeryListDetail;
                try
                {
                    // Get the food id
                    Food food = (from p in DataContext.Foods where p.FoodName == ingredient.FoodName select p).SingleOrDefault();
                    if (food != null)
                    {
                        ingredient.FoodId = food.FoodId;
                    }

                    // Add to Summery Sources
                    if (food != null)
                    {
                        SummerySource summerySource = (from p in DataContext.SummerySources
                                                       where
                                                       p.SUMMERY_ID == listId && p.SOURCE_ID == sourceId &&
                                                       p.FOOD_ID == food.FoodId
                                                       select p).SingleOrDefault();
                        if (summerySource == null)
                        {
                            summerySource = new SummerySource
                            {
                                SUMMERY_ID = listId,
                                SOURCE_ID  = sourceId,
                                FOOD_ID    = food.FoodId,
                                QUANTITY   = ingredient.Quantity
                            };
                            DataContext.SummerySources.InsertOnSubmit(summerySource);
                        }
                        else
                        {
                            summerySource.QUANTITY = ingredient.Quantity;
                        }

                        DataContext.SubmitChanges();
                    }

                    // ReCalculate summery list
                    IQueryable <decimal?> summerySources = from p in DataContext.SummerySources where p.SUMMERY_ID == listId && p.FOOD_ID == ingredient.FoodId select p.QUANTITY;
                    decimal?sum = summerySources.Sum();

                    summeryListDetail = (from p in DataContext.SummeryListDetails
                                         where p.LIST_ID == listId && p.FOOD_ID == ingredient.FoodId
                                         select p).SingleOrDefault();

                    if (summeryListDetail == null)
                    {
                        summeryListDetail = new SummeryListDetail
                        {
                            FOOD_ID             = ingredient.FoodId,
                            FOOD_NAME           = ingredient.FoodName,
                            LIST_ID             = listId,
                            QUANTITY            = sum.HasValue ? sum.Value : 0,
                            MEASUREMENT_UNIT_ID = ingredient.MeasurementUnitId,
                            MEASUREMENT_UNIT    = ingredient.MeasurementUnitName
                        };
                        DataContext.SummeryListDetails.InsertOnSubmit(summeryListDetail);
                    }
                    else
                    {
                        summeryListDetail.QUANTITY = sum.HasValue ? sum.Value : 0;
                    }
                    DataContext.SubmitChanges();

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
        protected virtual void DoWork(WorkQueue <WarningInfo> .EnqueueEventArgs e)
        {
            if (e == null)
            {
                return;
            }
            //临时解决重复数据
            if (_old != null && _old.Item.meterNo == e.Item.meterNo && _old.Item.readDate == e.Item.readDate)
            {
                _old = e;
                return;
            }
            _old = e;

            Log.getInstance().Write(MsgType.Information, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}数据中心处理报警数据,表号:{e.Item.meterNo} 数据采集时间:{e.Item.readDate} ST1:{e.Item.st1} ST2:{e.Item.st2}");

            string configName = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            //Linq to SQL 上下文对象
            DataContext dd = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString);

            try
            {
                Table <IoT_AlarmInfo> tbl       = dd.GetTable <IoT_AlarmInfo>();
                IoT_AlarmInfo         alarminfo = new IoT_AlarmInfo();
                alarminfo.MeterID    = e.Item.MeterID;
                alarminfo.MeterNo    = e.Item.meterNo;
                alarminfo.ReportDate = e.Item.readDate;
                if (e.Item.st1.Substring(0, 2) == "11")
                {
                    alarminfo.Item       = "阀门异常";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                string str = "";

                if (e.Item.st1.Substring(2, 1) == "1" || e.Item.st1.Substring(3, 1) == "1")
                {
                    str += e.Item.st1.Substring(2, 1) == "1" ? "电池1级欠压" : "电池2级欠压";
                }

                if (e.Item.st1.Substring(4, 1) == "1")
                {
                    str += "锂电池欠压";
                }


                if (e.Item.st1.Substring(5, 1) == "1")
                {
                    str += " 外电源异常";
                }

                if (e.Item.st1.Substring(6, 1) == "1")
                {
                    str += " 干电池异常";
                }
                if (e.Item.st1.Substring(7, 1) == "1")
                {
                    str += " 锂电池异常";
                }

                if (str != "")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;
                    alarminfo.Item       = str;
                    alarminfo.AlarmValue = "电源状态";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }

                if (e.Item.st1.Substring(9, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "无外电(外电和干电池)";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                if (e.Item.st1.Substring(10, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "欠压(干电池)";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                if (e.Item.st1.Substring(11, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "操作错误/磁干扰";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }

                if (e.Item.st1.Substring(12, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "余额不足/气量用尽";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                if (e.Item.st1.Substring(13, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "人工控制关阀";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                if (e.Item.st1.Substring(14, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "燃气表故障";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                if (e.Item.st1.Substring(15, 1) == "1")
                {
                    alarminfo            = new IoT_AlarmInfo();
                    alarminfo.MeterID    = e.Item.MeterID;
                    alarminfo.MeterNo    = e.Item.meterNo;
                    alarminfo.ReportDate = e.Item.readDate;

                    alarminfo.Item       = "长期未与服务器通讯报警";
                    alarminfo.AlarmValue = "报警";
                    // 调用新增方法
                    tbl.InsertOnSubmit(alarminfo);
                }
                string[] items = { "移动报警 / 地震震感器动作切断报警", "长期未使用切断报警", "LCD屏故障报警", "持续流量超时切断报警", "异常微小流量切断报警", "异常大流量切断报警", "流量过载切断报警", "燃气漏气切断报警" };
                for (int i = 0; i < 8; i++)
                {
                    if (e.Item.st2.Substring(i, 1) == "1")
                    {
                        alarminfo            = new IoT_AlarmInfo();
                        alarminfo.MeterID    = e.Item.MeterID;
                        alarminfo.MeterNo    = e.Item.meterNo;
                        alarminfo.ReportDate = e.Item.readDate;

                        alarminfo.Item       = items[i];
                        alarminfo.AlarmValue = "报警";
                        // 调用新增方法
                        tbl.InsertOnSubmit(alarminfo);
                    }
                }
                // 更新操作
                dd.SubmitChanges();
            }
            catch (Exception er)
            {
                Log.getInstance().Write(er, MsgType.Error);
            }
        }
Example #40
0
        public void save(Book book)
        {
            using (SqlConnection conn = DBAccess.getConnection())
            {
                DataContext db = new DataContext(conn);
                db.Transaction = db.Connection.BeginTransaction();

                try
                {
                    dbBook ub = (from b in db.GetTable <dbBook>() where b.id == book.id select b).First();
                    ub.name     = book.name;
                    ub.count    = book.count;
                    ub.price    = book.price;
                    ub.genre_id = book.genre.id;
                    ub.genre    = m_Genres.getForID(ub.genre_id);

                    Table <dbAuthorBookLink> link_table = db.GetTable <dbAuthorBookLink>();
                    var del_links = from l in link_table where l.book_id == book.id select l;
                    foreach (var del_item in del_links)
                    {
                        link_table.DeleteOnSubmit(del_item);
                    }

                    List <int> aIDs = new List <int>();
                    Func <int, int, dbAuthorBookLink> link_builder =
                        delegate(int author_id, int book_id)
                    {
                        dbAuthorBookLink newLink = new dbAuthorBookLink();
                        newLink.book_id   = book_id;
                        newLink.author_id = author_id;
                        return(newLink);
                    };
                    foreach (Author a in book.authors)
                    {
                        aIDs.Add(a.id);
                        link_table.InsertOnSubmit(link_builder(a.id, ub.id));
                    }
                    ub.authors = m_Authors.getForIDs(aIDs);

                    db.SubmitChanges();

                    int indx = m_EBook.FindIndex(x => x.id == book.id);
                    if (indx == -1)
                    {
                        m_EBook.Add(ub);
                    }
                    else
                    {
                        m_EBook[indx] = ub;
                    }

                    if (m_LinkToAuthor.ContainsKey(ub.id))
                    {
                        m_LinkToAuthor[ub.id] = aIDs;
                    }
                    else
                    {
                        m_LinkToAuthor.Add(ub.id, aIDs);
                    }

                    db.Transaction.Commit();
                }
                catch (Exception)
                {
                    db.Transaction.Rollback();
                }
            }
        }
Example #41
0
        public void InsertUser(string user, string pass, bool isAdmin = false)
        {
            Table <Man> man = db.GetTable <Man>();

            ////Insert
            Man newMan = new Man();

            newMan.PersonName = user;
            newMan.Pass       = pass;
            newMan.IsAdmin    = isAdmin;
            man.InsertOnSubmit(newMan);

            db.SubmitChanges();
        }
Example #42
0
        public Technologi AddNewTechnologi(Technologi data)
        {
            _db.GetTable <Technologi>().InsertOnSubmit(data);
            _db.SubmitChanges();

            return(data);
        }
Example #43
0
        public Message DianHuo(List <String> meterNoList, string meterType, Int64 priceId, string companyId, DateTime enableDate, List <String> lstUserID, string EnableMeterOper)
        {
            // 定义执行结果
            Message m;
            string  configName = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            //Linq to SQL 上下文对象
            DataContext dd = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString);

            try
            {
                List <IoT_Meter> dianHuoMeter = new List <IoT_Meter>();

                //获取价格信息
                IoT_PricePar priceInfo = dd.GetTable <IoT_PricePar>().Where(p =>
                                                                            p.CompanyID == companyId && p.ID == priceId).SingleOrDefault();
                //if (priceInfo==null)
                //{
                //     return new Message()
                //    {
                //        Result = false,
                //        TxtMessage = "该表具选择的价格不存在,请加载页面重新选择!"
                //    };
                //}
                foreach (string UserID in lstUserID)
                {
                    IoT_User dbinfo = dd.GetTable <IoT_User>().Where(p => p.UserID == UserID).SingleOrDefault();
                    if (dbinfo != null && dbinfo.State == '2')
                    {
                        return(new Message()
                        {
                            Result = false,
                            TxtMessage = "用户" + dbinfo.UserName + "已发送点火申请,请勿重复发送!"
                        });
                    }
                }
                foreach (string meterNo in meterNoList)
                {
                    IoT_Meter dbinfo = dd.GetTable <IoT_Meter>().Where(p => p.MeterNo == meterNo).SingleOrDefault();
                    if (priceInfo != null)
                    {
                        dbinfo.Price1          = priceInfo.Price1 == null ? 0 : priceInfo.Price1;
                        dbinfo.Gas1            = priceInfo.Gas1 == null ? 0 : priceInfo.Gas1;
                        dbinfo.Price2          = priceInfo.Price2 == null ? 0 : priceInfo.Price2;
                        dbinfo.Gas2            = priceInfo.Gas2 == null ? 0 : priceInfo.Gas2;
                        dbinfo.Price3          = priceInfo.Price3 == null ? 0 : priceInfo.Price3;
                        dbinfo.Gas3            = priceInfo.Gas3 == null ? 0 : priceInfo.Gas3;
                        dbinfo.Price4          = priceInfo.Price4 == null ? 0 : priceInfo.Price4;
                        dbinfo.Gas4            = priceInfo.Gas4 == null ? 0 : priceInfo.Gas4;
                        dbinfo.Price5          = priceInfo.Price5 == null ? 0 : priceInfo.Price5;
                        dbinfo.IsUsed          = priceInfo.IsUsed == null ? false : priceInfo.IsUsed;
                        dbinfo.Ladder          = priceInfo.Ladder == null ? 3 : priceInfo.Ladder;
                        dbinfo.SettlementDay   = priceInfo.SettlementDay;
                        dbinfo.SettlementMonth = priceInfo.SettlementMonth;
                        dbinfo.SettlementType  = priceInfo.SettlementType;
                    }
                    dbinfo.EnableMeterOper = EnableMeterOper;

                    dbinfo.PriceID         = (int)priceId;
                    dbinfo.MeterType       = meterType;
                    dbinfo.EnableMeterDate = enableDate;
                    dbinfo.MeterState      = '5';
                    dianHuoMeter.Add(dbinfo);
                }

                // 更新操作
                dd.SubmitChanges();

                string result = Do(dianHuoMeter);
                if (result == "")
                {
                    m = new Message()
                    {
                        Result     = true,
                        TxtMessage = "点火成功"
                    };
                }
                else
                {
                    m = new Message()
                    {
                        Result     = false,
                        TxtMessage = result
                    };
                }
            }
            catch (Exception e)
            {
                m = new Message()
                {
                    Result     = false,
                    TxtMessage = "" + e.Message
                };
            }
            return(m);
        }
Example #44
0
        ///// <summary>
        ///// 验证
        ///// </summary>
        ///// <param name="database">数据库</param>
        ///// <returns>验证结果</returns>
        //public ValidateResult Validate(DataContext database)
        //{
        //    if (database == null)
        //        throw new ArgumentNullException("database");
        //    var validater = new Validater();
        //    ValidateAction(validater, database);
        //    return validater.Validate();
        //}
        /// <summary>
        /// 验证动作
        /// </summary>
        /// <param name="validater">验证器</param>
        /// <param name="database">数据库</param>
        //protected virtual void ValidateAction(Validater validater, DataContext database) { }
        /// <summary>
        /// 保存 
        /// </summary>
        /// <param name="database">数据库</param>
        public void Save(DataContext database)
        {
            SaveWhenSubmit(database);

            database.SubmitChanges();
        }
Example #45
0
        public void CreateAdditionPlan(AdditionPlanEntity ape
                                       , List <AdditionEntity> weeklyAdditions
                                       , List <WeeklyMaxMinValues> minMaxValues
                                       , int countryId)
        {
            var loggedOnEmployee = ApplicationAuthentication.GetEmployeeId();
            var marsUserId       = GetMarsUserId(loggedOnEmployee);
            var entityToCreate   = new AdditionPlan
            {
                Name = ape.Name,
                MinComSegScenarioName         = ape.MinComSegScenarioName,
                MinComSegSccenarioDescription = ape.GetMinComSegScenarioDescription(),
                MaxFleetScenarioName          = ape.MaxFleetScenarioName,
                MaxFleetScenarioDescription   = ape.GetMaxFleetScenarioDescription(),
                StartRevenueDate = ape.GetStartRevenue(),
                EndRevenueDate   = ape.GetEndRevenue(),
                CurrentDate      = ape.GetCurrentDate(),
                DateCreated      = DateTime.Now,
                WeeksCalculated  = ape.GetWeeksCalculated(),
                CountryId        = countryId,
                //AdditionPlanEntries = additionPlanEntries,
                //AdditionPlanMinMaxValues = minMaxValueEntities,
                //CreatedBy = createdBy,
                MarsUserId = marsUserId
            };

            DataContext.AdditionPlans.InsertOnSubmit(entityToCreate);

            DataContext.SubmitChanges();

            var additionPlanId = entityToCreate.AdditionPlanId;

            var maxMinValues = from mmv in minMaxValues
                               select new AdditionPlanMinMaxValue
            {
                AdditionPlanId        = additionPlanId,
                Year                  = (short)mmv.Year,
                Week                  = (byte)mmv.WeekNumber,
                CarGroupId            = mmv.GetCarGroupId(),
                LocationId            = mmv.GetLocationId(),
                Rank                  = mmv.RankFromRevenue,
                TotalFleet            = mmv.TotalFleet,
                AdditionsAndDeletions = mmv.AdditionDeletionSum,
                MinFleet              = mmv.MinFleet,
                MaxFleet              = mmv.MaxFleet,
                Contribution          = mmv.Contribution,
            };

            var minMaxEntriesToBeInserted = maxMinValues.ToList();

            minMaxEntriesToBeInserted.BulkCopyToDatabase("AdditionPlanMinMaxValue", DataContext, "fao");


            var additionPlanEntryEntities = from wa in weeklyAdditions
                                            select new AdditionPlanEntry
            {
                Week                = (byte)wa.IsoWeek,
                Year                = (short)wa.Year,
                CarGroupId          = wa.GetCarGroupId(),
                LocationId          = wa.GetLocationId(),
                Additions           = wa.Amount,
                AdditionPlanId      = additionPlanId,
                ContributionPerUnit = (decimal)wa.Contribution,
            };


            var additionPlanEntriesToBeInserted = additionPlanEntryEntities.ToList();

            additionPlanEntriesToBeInserted.BulkCopyToDatabase("AdditionPlanEntry", DataContext, "fao");
        }
Example #46
0
 public static void Inserir(Model.Pessoa p)
 {
     using (var dc = new DataContext("Data Source=.\\sqlexpress;Initial Catalog=DB;Integrated Security=true"))
     {
         dc.GetTable<Model.Pessoa>().InsertOnSubmit(p);
         dc.SubmitChanges();
     }
 }
Example #47
0
 /// <summary>
 /// Обновление изменений БД
 /// </summary>
 public void UpdateDB()
 {
     db.SubmitChanges();
 }
Example #48
0
 /// <summary>
 /// 删除
 /// </summary>
 /// <param name="database">数据库</param>
 public void Delete(DataContext database)
 {
     DeleteWhenSubmit(database);
     database.SubmitChanges();
 }
 public virtual void Save()
 {
     dbContext.SubmitChanges();
 }
 //*unittest
 public void eliminarVueloPrueba()
 {
     DataContext datacontext = new DataContext(myConnection.SQLConnection);
     var table = datacontext.GetTable<Vuelo>();
     var result = from vuelo in table
                  where vuelo.HoraPartida == "Prueba unitaria"
                       select vuelo;
     foreach (Vuelo delete in result)
     {
         table.DeleteOnSubmit(delete);
         datacontext.SubmitChanges();
     }
 }
Example #51
0
 public void ModifyLiuchengzhuangtaiByFileId(FaArchiveTranfer faArchiveTranfer, LiuchengZhuangtaiEnum liuchengZhuangtai)
 {
     faArchiveTranfer.LiuchengZhuangtai = (int)liuchengZhuangtai;
     DataContext.SubmitChanges();
 }
Example #52
0
        //le suma millas al usuario
        public static void agregarMillas(int millas,int idCliente)
        {
            DataContext dataContext = new DataContext(myConnection.getConnection());
            var tabla = dataContext.GetTable<tablaCliente>();

            var cliente = from c in tabla
                          where c.ID_CLIENTE.Equals(idCliente)
                          select c;

            foreach (var c in cliente)
            {
                c.MILLAS += millas;
            }

            dataContext.SubmitChanges();
        }
Example #53
0
        protected void specTreeControl_OnUpItem(object sender, GenericEventArgs <Guid> e)
        {
            var entity = DataContext.LP_Specs.FirstOrDefault(n => n.ID == e.Value);

            if (entity == null)
            {
                return;
            }

            var query = from n in DataContext.LP_Specs
                        where n.DateDeleted == null
                        select n;

            if (entity.ParentID == null)
            {
                query = from n in query
                        where n.ParentID == null
                        select n;
            }
            else
            {
                query = from n in query
                        where n.ParentID == entity.ParentID
                        select n;
            }

            query = from n in query
                    orderby n.OrderIndex, n.DateCreated
            select n;

            var list = query.ToList();

            for (int i = 0; i < list.Count; i++)
            {
                list[i].OrderIndex = i;
            }

            var currentItem = list.FirstOrDefault(n => n.ID == e.Value);

            if (currentItem == null)
            {
                return;
            }

            var index = list.IndexOf(currentItem);

            if (index < 0 || index == 0)
            {
                return;
            }

            list[index]     = list[index - 1];
            list[index - 1] = currentItem;

            for (int i = 0; i < list.Count; i++)
            {
                list[i].OrderIndex = i;
            }

            DataContext.SubmitChanges();

            FillDataGrid();
        }
Example #54
0
        /// <summary>
        /// 更新调价任务状态
        /// </summary>
        /// <param name="taskID"></param>
        /// <param name="state">状态:0 申请 1 完成 2 撤销  3 失败</param>
        /// <returns></returns>
        public string UpdatePricingTaskState(string taskID, TaskState state)
        {
            if (state == TaskState.Waitting)
            {
                return("状态不能为申请");
            }

            string result     = "";
            string configName = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            //Linq to SQL 上下文对象
            DataContext dd = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString);

            try
            {
                IoT_PricingMeter dbinfo = dd.GetTable <IoT_PricingMeter>().Where(p =>
                                                                                 p.TaskID == taskID).SingleOrDefault();

                dbinfo.State        = Convert.ToChar(((byte)state).ToString());
                dbinfo.FinishedDate = DateTime.Now;
                // 更新操作
                dd.SubmitChanges();

                IoT_Pricing uploadCycle = null;
                int         iCount      = dd.GetTable <IoT_PricingMeter>().Where(p => p.TaskID == taskID && p.State.ToString() == "0").Count();
                if (iCount == 0)//表具任务都执行完成后 更新调价任务状态
                {
                    uploadCycle       = dd.GetTable <IoT_Pricing>().Where(p => p.ID == dbinfo.ID).SingleOrDefault();
                    uploadCycle.State = Convert.ToChar(((byte)state).ToString());
                }
                dd.SubmitChanges();
                IoT_PricePar pricePar = dd.GetTable <IoT_PricePar>().Where(p => p.ID.ToString() == uploadCycle.PriceType).SingleOrDefault();


                if (state == TaskState.Undo)
                {
                    new M_SetParameterService().UnSetParameter(taskID);
                }
                if (state == TaskState.Finished)
                {
                    IoT_Meter meterInfo = dd.GetTable <IoT_Meter>().Where(p => p.MeterNo == dbinfo.MeterNo).SingleOrDefault();

                    meterInfo.Price1 = uploadCycle.Price1 == null ? 0 : uploadCycle.Price1;
                    meterInfo.Gas1   = uploadCycle.Gas1 == null ? 0 : uploadCycle.Gas1;
                    meterInfo.Price2 = uploadCycle.Price2 == null ? 0 : uploadCycle.Price2;
                    meterInfo.Gas2   = uploadCycle.Gas2 == null ? 0 : uploadCycle.Gas2;
                    meterInfo.Price3 = uploadCycle.Price3 == null ? 0 : uploadCycle.Price3;
                    meterInfo.Gas3   = uploadCycle.Gas3 == null ? 0 : uploadCycle.Gas3;
                    meterInfo.Price4 = uploadCycle.Price4 == null ? 0 : uploadCycle.Price4;
                    meterInfo.Gas4   = uploadCycle.Gas4 == null ? 0 : uploadCycle.Gas4;
                    meterInfo.Price5 = uploadCycle.Price5 == null ? 0 : uploadCycle.Price5;

                    meterInfo.IsUsed = uploadCycle.IsUsed == null ? false : uploadCycle.IsUsed;
                    meterInfo.Ladder = uploadCycle.Ladder == null ? 3 : uploadCycle.Ladder;

                    meterInfo.SettlementType  = uploadCycle.SettlementType;
                    meterInfo.SettlementDay   = pricePar.SettlementDay;
                    meterInfo.SettlementMonth = pricePar.SettlementMonth;

                    // 更新操作
                    dd.SubmitChanges();
                }
            }
            catch (Exception e)
            {
                result = e.Message;
            }
            return(result);
        }
Example #55
0
 private void DoAndSubmitChanges(Action action)
 {
     action();
     _context.SubmitChanges();
 }