public int SaveContact(int?ID, string contact)
        {
            JObject jContact     = JObject.Parse(contact);
            string  Fname        = (string)jContact["Fname"];
            string  Lname        = (string)jContact["Lname"];
            Contact contactModel = new Contact();

            contactModel.Id    = (int)ID;
            contactModel.Fname = Fname;
            contactModel.Lname = Lname;
            using (ContactsEntities db = new ContactsEntities()) {
                if (ID == 0)
                {
                    db.Contacts.Add(contactModel);

                    db.SaveChanges();
                }
                else
                {
                    db.Entry(contactModel).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }


                return((int)ID);
            }
        }
        public IHttpActionResult PutContactsTable(int id, ContactsTable contactsTable)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != contactsTable.ContactsId)
            {
                return(BadRequest());
            }

            db.Entry(contactsTable).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ContactsTableExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #3
0
        public ActionResult Create([Bind(Include = "ID,Name,City,PostalCode")] Address address)
        {
            if (ModelState.IsValid)
            {
                db.Addresses.Add(address);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(address));
        }
예제 #4
0
        public ActionResult Create([Bind(Include = "ID,FirstName,LastName,DateOfBirth,Email,PhoneNumber,AddressID")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                db.Contacts.Add(contact);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.AddressID = new SelectList(db.Addresses, "ID", "Name", contact.AddressID);
            return(View(contact));
        }
 static void Main(string[] args)
 {
     using (ContactsEntities entities = new ContactsEntities())
     {
         Address doeaddress = new Address()
         {
             Street = "1 Broadway", ZipCode = "01234"
         };
         Address doeaddress2 = new Address()
         {
             Street = "2 Broadway", ZipCode = "01234"
         };
         entities.Addresses.Add(doeaddress);
         entities.Persons.Add(new Person()
         {
             FirstName = "Jane", LastName = "Doe", Address = doeaddress
         });
         entities.Persons.Add(new Person()
         {
             FirstName = "John", LastName = "Doe", Address = doeaddress
         });
         entities.Persons.Add(new Person()
         {
             FirstName = "Jim", LastName = "Doe", Address = doeaddress2
         });
         entities.SaveChanges();
     }
     Console.WriteLine("Press Enter to exit...");
     Console.ReadLine();
 }
예제 #6
0
        public IHttpActionResult PostContact(ContactViewModel contact)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Data"));
            }

            try
            {
                using (var ctx = new ContactsEntities())
                {
                    ctx.Contacts.Add(new Contact()
                    {
                        ContactId   = Guid.NewGuid(),
                        FirstName   = contact.FirstName,
                        LastName    = contact.LastName,
                        Email       = contact.Email,
                        PhoneNumber = contact.PhoneNumber,
                        Status      = contact.IsActive,
                        CreateDate  = DateTime.Now,
                    });

                    ctx.SaveChanges();
                }
            }
            catch (HttpResponseException ex)
            {
                BadRequest(ex.Message);
            }
            return(Ok());
        }
예제 #7
0
        public IHttpActionResult PutContact(ContactViewModel contact)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Not a valid model"));
            }
            try
            {
                using (var ctx = new ContactsEntities())
                {
                    var existingContact = ctx.Contacts.Where(s => s.ContactId == contact.ContactId).FirstOrDefault <Contact>();

                    if (existingContact != null)
                    {
                        existingContact.FirstName   = contact.FirstName;
                        existingContact.LastName    = contact.LastName;
                        existingContact.Email       = contact.Email;
                        existingContact.PhoneNumber = contact.PhoneNumber;
                        existingContact.Status      = contact.IsActive;
                        existingContact.CreateDate  = contact.CreateDate;

                        ctx.SaveChanges();
                    }
                    else
                    {
                        return(NotFound());
                    }
                }
            }
            catch (HttpResponseException ex) { BadRequest(ex.Message); }
            return(Ok());
        }
예제 #8
0
 private void btn_ChangePass_Click(object sender, EventArgs e)
 {
     if (tb_newpass.Text.Length < 5)
     {
         MessageBox.Show(@"رمز عبور باید حداقل 4 حرف باشد");
     }
     if (tb_newpass.Text != tb_newpass2.Text)
     {
         MessageBox.Show(@"رمز عبور جدید با تکرار آن مطابقت ندارد");
     }
     else
     {
         ContactsEntities db = new ContactsEntities();
         var pcon            = db.Configs.FirstOrDefault(p => p.ConfigKey == "Password");
         if (pcon != null)
         {
             pcon.ConfigValue = tb_newpass.Text;
         }
         else
         {
             db.Configs.Add(new Configs
             {
                 ConfigKey   = "Password",
                 ConfigValue = tb_newpass.Text
             });
         }
         db.SaveChanges();
     }
 }
예제 #9
0
 public int SaveContact(Person contact)
 {
     using (ContactsEntities context = new ContactsEntities())
     {
         if (contact.Id > 0)
         {
             context.Persons.Attach(contact);
             context.Entry(contact).State = EntityState.Modified;
             context.SaveChanges();
         }
         else
         {
             context.Persons.Add(contact);
             context.SaveChanges();
         }
     }
     return(contact.Id);
 }
        public int DeleteContact(int?ID, string contact)
        {
            Contact contactModel = new Contact();

            using (ContactsEntities db = new ContactsEntities())
            {
                contactModel = db.Contacts.Where(x => x.Id == ID).FirstOrDefault <Contact>();
                db.Contacts.Remove(contactModel);
                db.SaveChanges();
                return((int)ID);
            }
        }
예제 #11
0
 private void btn_addGroup_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(tb_groupName.Text))
     {
         ContactsEntities db = new ContactsEntities();
         db.ContactGroupDef.Add(new ContactGroupDef()
         {
             GroupName = tb_groupName.Text
         });
         db.SaveChanges();
         LoadGroup();
         MessageBox.Show("با موفقیت اضافه شد");
     }
 }
예제 #12
0
 public bool DeleteContact(Person contact)
 {
     if (contact.Id > 0)
     {
         using (ContactsEntities context = new ContactsEntities())
         {
             context.Persons.Attach(contact);
             context.Entry(contact).State = EntityState.Deleted;
             context.SaveChanges();
         }
         return(true);
     }
     return(false);
 }
예제 #13
0
 private void btn_removeGroup_Click(object sender, EventArgs e)
 {
     foreach (DataGridViewRow selectedRow in dataGV_group.SelectedRows)
     {
         int groupid;
         if (int.TryParse(selectedRow.Cells[0].Value.ToString(), out groupid))
         {
             ContactsEntities db = new ContactsEntities();
             db.Database.ExecuteSqlCommand("DELETE FROM ContactGroupDef WHERE Id=" + groupid);
             db.Database.ExecuteSqlCommand("DELETE FROM ContactGroup WHERE GroupId=" + groupid);
             db.SaveChanges();
             LoadGroup();
             MessageBox.Show("با موفقیت حذف شد");
         }
     }
 }
예제 #14
0
        public IHttpActionResult DeleteContact(Guid id)
        {
            if (id == null)
            {
                return(BadRequest("Not a valid contact id"));
            }

            try
            {
                using (var ctx = new ContactsEntities())
                {
                    var contact = ctx.Contacts.Where(s => s.ContactId == id).FirstOrDefault();
                    ctx.Contacts.Remove(contact);
                    ctx.SaveChanges();
                }
            }
            catch (HttpResponseException ex)
            { BadRequest(ex.Message); }
            return(Ok());
        }
예제 #15
0
        private void btn_delete_Click(object sender, EventArgs e)
        {
            ContactsEntities db = new ContactsEntities();

            if (_contactid > 0)
            {
                var con = db.ContactPerson.FirstOrDefault(p => p.Id == _contactid);
                if (con != null)
                {
                    db.ContactPerson.Remove(con);
                    db.SaveChanges();
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactPhone WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactAddress WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactEmail WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactGroup WHERE ContactPersonID=" + _contactid);
                }
            }
            MessageBox.Show("تغییرات خواسته شده اعمال شد");
            this.Close();
        }
        protected override void ProcessRecord()
        {
            if (String.IsNullOrWhiteSpace(LastName))
            {
                throw new ArgumentNullException(nameof(LastName));
            }

            // Auswertung der Parameter
            var contact = new Contact
            {
                FirstName = this.FirstName,
                LastName  = this.LastName
            };



            try
            {
                WriteDebug("Datenbankverbindung wird geöffnet");

                using (ContactsEntities model = new ContactsEntities())
                {
                    WriteDebug("Datenbankverbindung geöffnet");

                    model.Contacts.Add(contact);

                    model.SaveChanges();

                    WriteDebug("Schließe Datenbankverbindung");
                }

                WriteObject(contact);
            }
            catch (Exception e)
            {
                // Auswertung des Fehlers...
                WriteError(new ErrorRecord(e, "1", ErrorCategory.WriteError, null));
            }
        }
예제 #17
0
        /// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                var outputLines = new List <string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

                throw e;
            }
        }
        public void GetContactByIdAndPipeline()
        {
            // Testvorbereitung
            var contactone = new Contact()
            {
                FirstName = "Hans", LastName = "Mustermann"
            };
            var contacttwo = new Contact()
            {
                FirstName = "Franz", LastName = "Heinrich"
            };

            using (ContactsEntities model = new ContactsEntities())
            {
                model.Contacts.Add(contactone);
                model.Contacts.Add(contacttwo);

                model.SaveChanges();
            }


            var script = $@"Import-Module '{_assemblyname}'

                        {contactone.Id}, {contacttwo.Id} | Get-Contact | Export-Csv -Path 'D:\personen.txt'

                        ";

            var result = RunScript(script);

            Write(result);

            var contactresult = result.Output.OfType <Contact>();

            //Assert.NotNull(contactresult);
            //Assert.True(contactresult.Count() == 2);
            //Assert.Contains(contactresult, c => c.Id == contactone.Id);
            //Assert.Contains(contactresult, c => c.Id == contacttwo.Id);
        }
        public void GetContactById()
        {
            // Testvorbereitung
            var contact = new Contact()
            {
                FirstName = "Hans", LastName = "Mustermann"
            };

            using (ContactsEntities model = new ContactsEntities())
            {
                model.Contacts.Add(contact);

                model.SaveChanges();
            }

            int id = contact.Id;

            // Durchführung

            var script = $@"Import-Module '{_assemblyname}'

                        Get-Contact {id}

                        ";

            var result = RunScript(script);

            Write(result);

            var contactresult = result.Output.OfType <Contact>().FirstOrDefault();

            Assert.NotNull(contactresult);
            Assert.True(contactresult.Id > 0);
            Assert.Equal("Hans", contactresult.FirstName);
            Assert.Equal("Mustermann", contactresult.LastName);
        }
        public void GetContactWithoutRestriction()
        {
            // Testvorbereitung
            var contact = new Contact()
            {
                FirstName = "Dieter", LastName = "Müller"
            };

            using (ContactsEntities model = new ContactsEntities())
            {
                model.Contacts.Add(contact);

                model.SaveChanges();
            }

            int id = contact.Id;

            // Durchführung

            var script = $@"Import-Module '{_assemblyname}'

                        Get-Contact

                        ";

            var result = RunScript(script);

            Write(result);

            var contacts = result.Output.OfType <Contact>();

            Assert.NotNull(contacts);
            Assert.True(contacts.Any());
            Assert.DoesNotContain(contacts, c => c.Id == 0);
            Assert.Contains(contacts, c => c.LastName.Equals("Müller"));
        }
예제 #21
0
        private void ImportData()
        {
            ContactsEntities db = new ContactsEntities();
            int cnt             = 0;

            var now          = DateTime.Now;
            var existingFile = new FileInfo(_filepathString);

            using (var package = new ExcelPackage(existingFile))
            {
                ExcelWorkbook workBook = package.Workbook;

                if (workBook != null)
                {
                    if (workBook.Worksheets.Count > 0)
                    {
                        ExcelWorksheet currentWorksheet = workBook.Worksheets.First();

                        SetControlPropertyValue(l_allcnt, "Text", currentWorksheet.Dimension.End.Row.ToString());
                        for (int i = 2; i <= currentWorksheet.Dimension.End.Row; i++)
                        {
                            int col = 0;
                            SetControlPropertyValue(L_per, "Text",
                                                    "%" + ((float)cnt * 100 / currentWorksheet.Dimension.End.Row).ToString("00.00"));
                            SetControlPropertyValue(L_cnt, "Text", cnt.ToString());
                            cnt++;

                            ContactPerson         person           = new ContactPerson();
                            List <ContactPhone>   contactPhones    = new List <ContactPhone>();
                            List <ContactEmail>   contactEmails    = new List <ContactEmail>();
                            List <ContactAddress> contactAddresses = new List <ContactAddress>();
                            foreach (
                                var rowCell in currentWorksheet.Cells[i, 1, i, currentWorksheet.Dimension.End.Column])
                            {
                                string value = rowCell.Text;
                                if (!string.IsNullOrEmpty(value) && col < _dataModels.Count)
                                {
                                    switch (_dataModels[col])
                                    {
                                    case DataModelKey.FirstName:
                                        person.FirstName = value;
                                        break;

                                    case DataModelKey.LastName:
                                        person.LastName = value;
                                        break;

                                    case DataModelKey.PostName:
                                        person.PostName = value;
                                        break;

                                    case DataModelKey.BirthDate:
                                        long birthdate;
                                        long.TryParse(value, out birthdate);
                                        person.DateOfBirth = birthdate;
                                        break;

                                    case DataModelKey.MobilePhone:
                                        contactPhones.Add(new ContactPhone()
                                        {
                                            PhoneType = 0, PhoneNumber = value
                                        });
                                        break;

                                    case DataModelKey.HomePhone:
                                        contactPhones.Add(new ContactPhone()
                                        {
                                            PhoneType = 1, PhoneNumber = value
                                        });
                                        break;

                                    case DataModelKey.WorkPhone:
                                        contactPhones.Add(new ContactPhone()
                                        {
                                            PhoneType = 2, PhoneNumber = value
                                        });
                                        break;

                                    case DataModelKey.PersonalEmail:
                                        contactEmails.Add(new ContactEmail()
                                        {
                                            EmailType = 0, Email = value
                                        });
                                        break;

                                    case DataModelKey.WorkEmail:
                                        contactEmails.Add(new ContactEmail()
                                        {
                                            EmailType = 1, Email = value
                                        });
                                        break;

                                    case DataModelKey.HomeAddress:
                                        contactAddresses.Add(new ContactAddress()
                                        {
                                            AddressType = 0, Address = value
                                        });
                                        break;

                                    case DataModelKey.WorkAddress:
                                        contactAddresses.Add(new ContactAddress()
                                        {
                                            AddressType = 1, Address = value
                                        });
                                        break;
                                    }
                                }
                                col++;
                            }
                            if (person.FirstName != "" || person.LastName != "")
                            {
                                //db.ContactPerson.Add(person);
                                //db.SaveChanges();
                                ContactPerson oldperson = null;
                                foreach (ContactPhone contactPhone in contactPhones)
                                {
                                    var oldphone = db.ContactPhone.FirstOrDefault(p => p.PhoneNumber == contactPhone.PhoneNumber);
                                    if (oldphone != null)
                                    {
                                        oldperson = oldphone.ContactPerson;
                                    }
                                }
                                if (oldperson != null)
                                {
                                    if (!string.IsNullOrEmpty(person.PostName))
                                    {
                                        oldperson.PostName = person.PostName;
                                    }
                                    if (!string.IsNullOrEmpty(person.FirstName))
                                    {
                                        oldperson.FirstName = person.FirstName;
                                    }
                                    if (!string.IsNullOrEmpty(person.LastName))
                                    {
                                        oldperson.PostName = person.LastName;
                                    }
                                    if (person.DateOfBirth != null)
                                    {
                                        oldperson.DateOfBirth = person.DateOfBirth;
                                    }
                                    person = oldperson;
                                    db.SaveChanges();
                                }

                                foreach (ContactPhone contactPhone in contactPhones)
                                {
                                    if (person.ContactPhone.All(p => p.PhoneNumber != contactPhone.PhoneNumber))
                                    {
                                        person.ContactPhone.Add(contactPhone);
                                    }
                                    else
                                    {
                                        var fphone = person.ContactPhone.FirstOrDefault(
                                            p => p.PhoneNumber == contactPhone.PhoneNumber);
                                        if (fphone != null)
                                        {
                                            fphone.PhoneType = contactPhone.PhoneType;
                                        }
                                    }
                                    //contactPhone.ContactPersonID = person.Id;
                                    // db.ContactPhone.Add(contactPhone);
                                }
                                foreach (ContactAddress contactAddress in contactAddresses)
                                {
                                    if (person.ContactAddress.All(p => p.Address != contactAddress.Address))
                                    {
                                        person.ContactAddress.Add(contactAddress);
                                    }
                                    else
                                    {
                                        var fphone = person.ContactAddress.FirstOrDefault(
                                            p => p.Address == contactAddress.Address);
                                        if (fphone != null)
                                        {
                                            fphone.AddressType = contactAddress.AddressType;
                                        }
                                    }

                                    //contactAddress.ContactPersonID = person.Id;
                                    //db.ContactAddress.Add(contactAddress);
                                }
                                foreach (ContactEmail contactEmail in contactEmails)
                                {
                                    if (person.ContactEmail.All(p => p.Email != contactEmail.Email))
                                    {
                                        person.ContactEmail.Add(contactEmail);
                                    }
                                    else
                                    {
                                        var fphone = person.ContactEmail.FirstOrDefault(
                                            p => p.Email == contactEmail.Email);
                                        if (fphone != null)
                                        {
                                            fphone.EmailType = contactEmail.EmailType;
                                        }
                                    }

                                    //contactEmail.ContactPersonID = person.Id;
                                    //db.ContactEmail.Add(contactEmail);
                                }
                                foreach (ContactGroup contactGroup in _contactGroups)
                                {
                                    if (person.ContactGroup.All(p => p.GroupId != contactGroup.GroupId))
                                    {
                                        person.ContactGroup.Add(contactGroup);
                                    }
                                    //contactGroup.ContactPersonID = person.Id;
                                    //db.ContactGroup.Add(contactGroup);
                                }
                                if (oldperson == null)
                                {
                                    db.ContactPerson.Add(person);
                                }
                                try
                                {
                                    db.SaveChanges();
                                }
                                catch (DbEntityValidationException e)
                                {
                                    foreach (var eve in e.EntityValidationErrors)
                                    {
                                        MessageBox.Show("Entity of type " + eve.Entry.Entity.GetType().Name +
                                                        " in state " + eve.Entry.State +
                                                        " has the following validation errors:");
                                        foreach (var ve in eve.ValidationErrors)
                                        {
                                            MessageBox.Show("- Property: " + ve.PropertyName + ", Error: " + ve.ErrorMessage);
                                        }
                                    }
                                    throw;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            MessageBox.Show(cnt + " Added in " + DateTime.Now.Subtract(now).TotalSeconds + " Secs");
            SetControlPropertyValue(btn_import, "Enabled", true);
        }
예제 #22
0
        private void btn_add_Click(object sender, EventArgs e)
        {
            ContactsEntities db = new ContactsEntities();

            if (_contactid > 0)
            {
                var con = db.ContactPerson.FirstOrDefault(p => p.Id == _contactid);
                if (con != null)
                {
                    db.ContactPerson.Remove(con);

                    db.SaveChanges();
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactPhone WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactAddress WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactEmail WHERE ContactPersonID=" + _contactid);
                    db.Database.ExecuteSqlCommand("DELETE FROM ContactGroup WHERE ContactPersonID=" + _contactid);
                }
            }

            int b;

            int.TryParse(tb_Birthdate.Text, out b);
            ContactPerson per = new ContactPerson()
            {
                FirstName   = tb_firstname.Text,
                LastName    = tb_LastName.Text,
                PostName    = tb_postname.Text,
                DateOfBirth = b
            };

            db.ContactPerson.Add(per);
            db.SaveChanges();

            for (int i = 0; i < _callnum; i++)
            {
                if (panelCall.Controls.Find("tb_call" + i, false).Any())
                {
                    var tb = (TextBox)(panelCall.Controls.Find("tb_call" + i, false))[0];
                    var cb = (ComboBox)(panelCall.Controls.Find("cb_Calltype" + i, false))[0];
                    if (!string.IsNullOrEmpty(tb.Text))
                    {
                        db.ContactPhone.Add(new ContactPhone()
                        {
                            ContactPersonID = per.Id,
                            PhoneNumber     = tb.Text,
                            PhoneType       = cb.SelectedIndex
                        });
                    }
                }
            }
            for (int i = 0; i < _emailnum; i++)
            {
                if (panelEmail.Controls.Find("tb_email" + i, false).Any())
                {
                    var tb = (TextBox)(panelEmail.Controls.Find("tb_email" + i, false))[0];
                    var cb = (ComboBox)(panelEmail.Controls.Find("cb_emailtype" + i, false))[0];
                    if (!string.IsNullOrEmpty(tb.Text))
                    {
                        db.ContactEmail.Add(new ContactEmail()
                        {
                            ContactPersonID = per.Id,
                            Email           = tb.Text,
                            EmailType       = cb.SelectedIndex
                        });
                    }
                }
            }
            for (int i = 0; i < _addressnum; i++)
            {
                if (panelAddress.Controls.Find("tb_address" + i, false).Any())
                {
                    var tb = (TextBox)(panelAddress.Controls.Find("tb_address" + i, false))[0];
                    var cb = (ComboBox)(panelAddress.Controls.Find("cb_addresstype" + i, false))[0];
                    if (!string.IsNullOrEmpty(tb.Text))
                    {
                        db.ContactAddress.Add(new ContactAddress()
                        {
                            ContactPersonID = per.Id,
                            Address         = tb.Text,
                            AddressType     = cb.SelectedIndex
                        });
                    }
                }
            }
            foreach (var selectedItem in clb_Groups.SelectedItems)
            {
                var g = (ContactGroupDef)selectedItem;
                db.ContactGroup.Add(new ContactGroup()
                {
                    ContactPersonID = per.Id,
                    GroupId         = g.Id
                });
            }
            db.SaveChanges();

            MessageBox.Show("تغییرات خواسته شده اعمال شد");
            this.Close();
        }