public int NumberOfFriends(Contact contact) { if (!FriendsCount.ContainsKey(contact.Id)) return 0; return FriendsCount[contact.Id]; }
public HomeModule() { Get["/"] = _ => { return View["index.html"]; }; Get["/contacts"] = _ => { List<Contact> allContacts = Contact.GetAll(); return View["contacts.cshtml", allContacts]; }; Get["/contacts/new"] = _ => { return View["add_new_contact"]; }; Post["/contacts/added"] = _ => { Contact newContact = new Contact ((Request.Form["name"]), (Request.Form["phoneNumber"]), (Request.Form["address"])); return View["contact_created.cshtml", newContact]; }; Get["/contacts/{id}"] = parameters => { Contact selectedContact = Contact.Find(parameters.id); return View["contact_details.cshtml", selectedContact]; }; Get["/contacts/cleared"] = _ => { Contact.ClearAll(); return View["contacts_deleted.cshtml"]; }; }
private void btnSubmit_Click(object sender, EventArgs e) { //string xml; Contact contact = new Contact(); contact.companyName = txtCompany.Text; contact.firstName = txtFName.Text; contact.middleName = txtMName.Text; contact.lastName = txtLName.Text; contact.liscence = txtLicense.Text; contact.phone = txtPhone.Text; contact.cell = txtCell.Text; contact.email = txtEmail.Text; contact.buildingLiscence = txtBuildingLicense.Text; contact.streetNumber = txtStreetNumber.Text; contact.streetName = txtStreetName.Text; contact.type = txtType.Text; contact.streetName2 = txtStreetName2.Text; contact.city = txtCity.Text; contact.state = txtState.Text; contact.zip = txtZip.Text; System.IO.StreamWriter file = new System.IO.StreamWriter(@"Contact.xml"); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(contact.GetType()); x.Serialize(file, contact); file.Close(); }
private void btnOk_Click(object sender, EventArgs e) { Hide(); if (ValidateInput() == false) { DialogResult = DialogResult.None; return; } Contact contact = AppController.Instance.Contacts[cbContactname.SelectedItem.ToString()]; JabberID Jid = new JabberID(contact.UserName.ToString(), contact.ServerName.ToString(), Settings.Default.Resource); Contact delContact = new Contact(Jid, contact.GroupName.ToString(), LoginState.Offline); Contact editContact = new Contact(Jid, tbnewGpName.Text.Trim(), LoginState.Offline); UnsubscribedResponse resp = new UnsubscribedResponse(Jid); AppController.Instance.SessionManager.Send(resp); AppController.Instance.SessionManager.BeginSend(new RosterRemove(Jid, contact.UserName.ToString())); AppController.Instance.Contacts.Remove(delContact); SubscribeRequest p = new SubscribeRequest(Jid); AppController.Instance.SessionManager.Send(p); AppController.Instance.SessionManager.BeginSend( new RosterAdd(Jid, contact.UserName.ToString(), tbnewGpName.Text.ToString())); AppController.Instance.Contacts.Add(editContact); AppController.Instance.MainWindow.UpdateContactList(); }
//метод: обновляет контакт в БД, если в БД контакт с таким ID отсутствует, то создается новая запись public void SaveContact(Contact contact) { Contact dbEntry = dataDBContext.Contacts.SingleOrDefault(c => c.Cont_ID == contact.Cont_ID); if (dbEntry == null) { //Контакт не найден в Системе: добавим TrimContactFields(contact);//обрежем лишние пробельчики dataDBContext.Contacts.InsertOnSubmit(contact); } else { dbEntry.Cont_email = contact.Cont_email; dbEntry.Cont_enterprise = contact.Cont_enterprise; dbEntry.Cont_middlename = contact.Cont_middlename; dbEntry.Cont_name = contact.Cont_name; dbEntry.Cont_phone1 = contact.Cont_phone1; dbEntry.Cont_phone2 = contact.Cont_phone2; dbEntry.Cont_phone3 = contact.Cont_phone3; dbEntry.Cont_position = contact.Cont_position; dbEntry.Cont_surname = contact.Cont_surname; TrimContactFields(dbEntry);//обрежем лишние пробельчики } dataDBContext.SubmitChanges(); }
public UiMessage(IMessage message, Contact contact) { Address = message.Address; Text = message.Text; TimeStamp = message.TimeStamp; Contact = contact; }
public frmEditContact(Contact contact, IDXMenuManager menuManager) { InitializeComponent(); this.contact = contact; this.bindingContact = contact.Clone(); InitEditors(); InitMenuManager(menuManager); pePhoto.Image = bindingContact.Photo; teFirstName.DataBindings.Add("Text", bindingContact.FullName, "FirstName"); teLastName.DataBindings.Add("Text", bindingContact.FullName, "LastName"); teMiddleName.DataBindings.Add("Text", bindingContact.FullName, "MiddleName"); icbTitle.DataBindings.Add("EditValue", bindingContact.FullName, "Title"); meLine.DataBindings.Add("Text", bindingContact.Address, "AddressLine"); cbeState.DataBindings.Add("Text", bindingContact.Address, "State"); cbeCity.DataBindings.Add("Text", bindingContact.Address, "City"); teZip.DataBindings.Add("Text", bindingContact.Address, "Zip"); teEmail.DataBindings.Add("Text", bindingContact, "Email"); tePhone.DataBindings.Add("Text", bindingContact, "Phone"); deBirthDate.DataBindings.Add("DateTime", bindingContact, "BindingBirthDate"); icbGender.DataBindings.Add("EditValue", bindingContact, "Gender"); richEditControl1.DataBindings.Add("HtmlText", bindingContact, "Note"); UpdateCaption(); InitValidationProvider(); }
public ActionResult EditProfile(Contact con) { using (var db = new ProjectDatabaseContext()) { try { if (ModelState.IsValid) { db.Contacts.Attach(con); db.ObjectStateManager.ChangeObjectState(con, EntityState.Modified); db.SaveChanges(); return RedirectToAction("Index"); } var username = Session["username"].ToString(); var q = (from p in db.Contacts where p.Username == username select p).FirstOrDefault(); return View(q); } catch (Exception e) { return View(); } } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the ContactService. ContactService contactService = (ContactService) user.GetService(DfpService.v201508.ContactService); // Set the IDs of the companies for the contacts. long advertiserCompanyId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE")); long agencyCompanyId = long.Parse(_T("INSERT_AGENCY_COMPANY_ID_HERE")); // Create an advertiser contact. Contact advertiserContact = new Contact(); advertiserContact.name = "Mr. Advertiser #" + GetTimeStamp(); advertiserContact.email = "*****@*****.**"; advertiserContact.companyId = advertiserCompanyId; // Create an agency contact. Contact agencyContact = new Contact(); agencyContact.name = "Ms. Agency #" + GetTimeStamp(); agencyContact.email = "*****@*****.**"; agencyContact.companyId = agencyCompanyId; try { // Create the contacts on the server. Contact[] contacts = contactService.createContacts(new Contact[] {advertiserContact, agencyContact}); foreach (Contact contact in contacts) { Console.WriteLine("A contact with ID \"{0}\" and name \"{1}\" was created.", contact.id, contact.name); } } catch (Exception e) { Console.WriteLine("Failed to create contacts. Exception says \"{0}\"", e.Message); } }
public static ContactDto ToDto(Contact contact) { var dto = new ContactDto { ID = contact.ID, FirstName = contact.FirstName, LastName = contact.LastName, Address = new AddressDto { Street1 = contact.Address.Street1, Street2 = contact.Address.Street2, City = contact.Address.City, State = contact.Address.State, Zip = contact.Address.Zip }, Numbers = new ObservableCollection<PhoneNumberDto>() }; foreach(var number in contact.Numbers) { dto.Numbers.Add(new PhoneNumberDto { Number = number.Number, Type = number.Type }); } return dto; }
public static Contact ToContact(ContactDto dto) { var contact = new Contact { ID = dto.ID, FirstName = dto.FirstName, LastName = dto.LastName, }; contact.Address.Street1 = dto.Address.Street1; contact.Address.Street2 = dto.Address.Street2; contact.Address.City = dto.Address.City; contact.Address.State = dto.Address.State; contact.Address.Zip = dto.Address.Zip; foreach(var number in dto.Numbers) { contact.AddPhoneNumber(new PhoneNumber { Number = number.Number, Type = number.Type }); } return contact; }
public ActionResult Contact(ContactViewModel contactVm) { try { if (!ModelState.IsValid) { return View(contactVm); } var contact = new Contact { From = contactVm.From, Message = contactVm.Message }; new Email().Send(contact); switch (Request.CurrentLang()) { case Lang.De: return RedirectToAction("Danke"); case Lang.Nl: return RedirectToAction("Bedankt"); case Lang.En: return RedirectToAction("Thanks"); default: return RedirectToAction("Tack"); } } catch (Exception) { return RedirectToAction("Error"); } }
static void Main(string[] args) { Uri baseAddress = new Uri("http://*****:*****@gmail.com", PhoneNo = "789" }; Console.WriteLine("\n添加联系人003"); httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); contact = new Contact { Id = "003", Name = "王五", EmailAddress = "*****@*****.**", PhoneNo = "987" }; Console.WriteLine("\n修改联系人003"); httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.WriteLine("\n删除联系人003"); httpClient.DeleteAsync("/api/contacts/003").Wait(); contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result; ListContacts(contacts); Console.Read(); }
public ComposeBubble(long time, BubbleDirection direction, Service service, VisualBubble bubbleToSend, Contact.ID[] ids) : base(time, direction, service) { Ids = ids; BubbleToSend = bubbleToSend; }
public Contact GetUserInfo() { WebInfo web = userCookie.Click("酷站</a> <a href=\"(?<key>.*?)\">更多</a><br/>", Encoding.UTF8); web = web.Click("主题</a>[\\w\\W]*?<a href=\"(?<key>.*?)\">空间</a>", Encoding.UTF8); web = web.Click("我的好友</a>\\|<a href=\"(?<key>.*?)\">我的档案</a>", Encoding.UTF8); string html = web.Html; Contact c = new Contact(); //头像 c.Photo = html.FindText("<div class=\"i\"><img src=\"", "\" alt=\"头像\"/>"); //姓名 c.Name = html.FindText("<strong>", "</strong>"); //昵称 c.NickName = this.UserName; //性别 string str_sex = html.FindText("</strong><br/><br/>", "  "); switch (str_sex) { case "男": c.Sex = e_Sex.男; break; case "女": c.Sex = e_Sex.女; break; default: c.Sex = e_Sex.保密; break; } //生日 c.BirthDay = html.FindText("  ", " ").ToDateTime(); //地址 Address a = new Address(); a.AddressType = e_AddressType.老家; a.address = html.FindText("出生地:", "<br/>"); a.Country = "中国"; string[] arr_add = a.address.Split('-'); a.Province = arr_add[0]; if (arr_add.Length>1) { a.City = arr_add[1]; } if (arr_add.Length>2) { a.District = arr_add[2]; } c.Address = a; c.Remark = html.FindText("个人简介:", "<br/>"); return c; }
///<summary>Inserts one Contact into the database. Provides option to use the existing priKey.</summary> internal static long Insert(Contact contact,bool useExistingPK) { if(!useExistingPK && PrefC.RandomKeys) { contact.ContactNum=ReplicationServers.GetKey("contact","ContactNum"); } string command="INSERT INTO contact ("; if(useExistingPK || PrefC.RandomKeys) { command+="ContactNum,"; } command+="LName,FName,WkPhone,Fax,Category,Notes) VALUES("; if(useExistingPK || PrefC.RandomKeys) { command+=POut.Long(contact.ContactNum)+","; } command+= "'"+POut.String(contact.LName)+"'," +"'"+POut.String(contact.FName)+"'," +"'"+POut.String(contact.WkPhone)+"'," +"'"+POut.String(contact.Fax)+"'," + POut.Long (contact.Category)+"," +"'"+POut.String(contact.Notes)+"')"; if(useExistingPK || PrefC.RandomKeys) { Db.NonQ(command); } else { contact.ContactNum=Db.NonQ(command,true); } return contact.ContactNum; }
public JsonResult AddContact(string firstName, string middleName, string lastName, string email, string phone, int contactGroupId) { var result = new ServiceResponse<Object>(); var contact = new Contact { FirstName = firstName, MiddleName = middleName, LastName = lastName, Email = email, Phone = phone, ContactGroupId = contactGroupId }; try { _contactService.AddContact(contact); } catch (Exception ex) { Trace.WriteLine("AddContact: " + ex.Message); result.Message = ex.Message; } result.Result = GetAllGroupsResponse(); return JsonResponse(result); }
public ContactViewModel(Contact contact) { FullName = contact.FirstName + " " + contact.LastName; Email = contact.Email; Phone = contact.PhoneNo; Age = CalculateAge(contact.BirthDate); }
///<summary>Inserts one Contact into the database. Returns the new priKey.</summary> internal static long Insert(Contact contact) { if(DataConnection.DBtype==DatabaseType.Oracle) { contact.ContactNum=DbHelper.GetNextOracleKey("contact","ContactNum"); int loopcount=0; while(loopcount<100){ try { return Insert(contact,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ contact.ContactNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(contact,false); } }
public void Save(Contact contact, List<Friend> friends) { friends = friends.Where(friend => friend.ContactID1 != friend.ContactId2 && friend.ContactId2 == contact.Id). ToList(); DAL.Save(contact, friends); }
public bool Update(Contact oldContact, Contact newContact) { if (!Contains(oldContact) || Contains(newContact) || !Delete(oldContact)) return false; if (Add(newContact)) return true; Add(oldContact); return false; }
// PUT api/Contacts/5 public HttpResponseMessage PutContact(int id, Contact contact) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != contact.Id) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(contact).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public static Contact GetUser(Uri requestUri, int Id) { ClientContext context; if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, null)) { using (context) { var web = context.Web; context.Load(web); var user = web.GetUserById(Id); context.Load(user, u => u.LoginName); context.ExecuteQuery(); var peopleManager = new PeopleManager(context); var userProfile = peopleManager.GetPropertiesFor(user.LoginName); context.Load(userProfile); context.ExecuteQuery(); var contact = new Contact() { ExternalId = user.Id.ToString(), FullName = user.Title, EmailAddress = user.Email }; if (userProfile.IsPropertyAvailable("Title")) contact.Position = userProfile.Title; if (userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone")) contact.PhoneNumber = userProfile.UserProfileProperties["WorkPhone"]; return contact; } } throw new InvalidOperationException(string.Format("Unable to find user '{0}' at '{1}'", Id, requestUri.AbsoluteUri)); }
public String EditBusinessCriticality(Contact contact) { db.Entry(contact).State = EntityState.Modified; db.SaveChanges(); return "Success"; }
public ResponseHolder CreateAccount(Account acc, Contact con) { acc.Status = "Draft"; ResponseHolder accResp = zs.Create(acc); if (accResp.Success) { con.AccountId = accResp.Id; ResponseHolder conResp = zs.Create(con); if (conResp.Success) { Account newAcc = new Account(); newAcc.Id = accResp.Id; newAcc.Status = "Active"; newAcc.SoldToId = conResp.Id; newAcc.BillToId = conResp.Id; return zs.Update(new List<zObject>{newAcc})[0]; } else { return conResp; } } else { return accResp; } }
public String CreateApplication(Contact contact) { db.Contacts.Add(contact); db.SaveChanges(); return "Success"; }
public String DeleteBusinessCriticality(Contact contact) { db.Contacts.Remove(contact); db.SaveChanges(); return "Success"; }
static public string CreateReportFile(Contact supplier, DateTime fromDate, DateTime toDate) { DataView view = BillingDS.GetBills(fromDate, toDate, "[BillType] IN('B','G') AND [BillStatus] <> 'X' AND " + "[CancelationTime] > '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); string fileContents = GetReportFileSection(view, "1", "I"); // Active bills view = BillingDS.GetBills(DateTime.Parse("31/12/2011"), fromDate.AddSeconds(-0.5), "[BillType] = 'B' AND [BillStatus] = 'C' AND [CancelationTime] >= '" + fromDate.ToString("yyyy-MM-dd") + "' AND " + "[CancelationTime] <= '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); fileContents += GetReportFileSection(view, "0", "I"); // Canceled bills view = BillingDS.GetBills(fromDate, toDate, "[BillType] IN ('C','L') AND [BillStatus] = 'A'"); fileContents += GetReportFileSection(view, "1", "E"); // Active credit notes view = BillingDS.GetBills(DateTime.Parse("31/12/2011"), fromDate.AddSeconds(-0.5), "[BillType] IN ('C','L') AND [BillStatus] = 'C' AND [CancelationTime] >= '" + fromDate.ToString("yyyy-MM-dd") + "' AND " + "[CancelationTime] <= '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "'"); fileContents += GetReportFileSection(view, "0", "E"); // Canceled credit notes fileContents = fileContents.TrimEnd(System.Environment.NewLine.ToCharArray()); string fileName = GetReportFileName(toDate); System.IO.File.WriteAllText(fileName, fileContents); return fileName; }
public void UpdateContact(int contactId, Contact entity) { var contactManager = new ContactManager(this); var originalContact = new Contact(); originalContact = contactManager.GetContact(contactId); contactManager.Update(originalContact, entity); }
public HomeModule() { Get["/"] = _ => { return View["index.cshtml"]; }; Get["/view"] = _ => { List<Contact> cList = Contact.GetAllContacts(); return View["view.cshtml",cList]; }; Get["/add"] = _ => { return View["add.cshtml"]; }; Post["/contact_created"] = _ => { Contact c = new Contact(Request.Form["new-name"],Request.Form["new-address"],Request.Form["new-number"]); return View["contact_created.cshtml", c]; }; Post["/contacts_deleted"] = _ => { Contact.DeleteAllContacts(); List<Contact> cList = Contact.GetAllContacts(); return View["view.cshtml", cList]; }; Get["/view/{name}"] = parameters => { Contact c = Contact.GetContactByName(parameters.name); return View["contact.cshtml", c]; }; }
// Compute contacts between child shapes of two <see cref="CompositeShape"/>s. // testXxx are initialized objects which are re-used to avoid a lot of GC garbage. private void AddChildChildContacts(ContactSet contactSet, int childIndexA, int childIndexB, CollisionQueryType type, ContactSet testContactSet, CollisionObject testCollisionObjectA, TestGeometricObject testGeometricObjectA, CollisionObject testCollisionObjectB, TestGeometricObject testGeometricObjectB) { CollisionObject collisionObjectA = contactSet.ObjectA; CollisionObject collisionObjectB = contactSet.ObjectB; IGeometricObject geometricObjectA = collisionObjectA.GeometricObject; IGeometricObject geometricObjectB = collisionObjectB.GeometricObject; CompositeShape shapeA = (CompositeShape)geometricObjectA.Shape; CompositeShape shapeB = (CompositeShape)geometricObjectB.Shape; Vector3F scaleA = geometricObjectA.Scale; Vector3F scaleB = geometricObjectB.Scale; IGeometricObject childA = shapeA.Children[childIndexA]; IGeometricObject childB = shapeB.Children[childIndexB]; // Find collision algorithm. CollisionAlgorithm collisionAlgorithm = CollisionDetection.AlgorithmMatrix[childA, childB]; // ----- Set the shape temporarily to the current children. // (Note: The scaling is either uniform or the child has no local rotation. Therefore, we only // need to apply the scale of the parent to the scale and translation of the child. We can // ignore the rotation.) Debug.Assert( (scaleA.X == scaleA.Y && scaleA.Y == scaleA.Z) || !childA.Pose.HasRotation, "CompositeShapeAlgorithm should have thrown an exception. Non-uniform scaling is not supported for rotated children."); Debug.Assert( (scaleB.X == scaleB.Y && scaleB.Y == scaleB.Z) || !childB.Pose.HasRotation, "CompositeShapeAlgorithm should have thrown an exception. Non-uniform scaling is not supported for rotated children."); var childAPose = childA.Pose; childAPose.Position *= scaleA; // Apply scaling to local translation. testGeometricObjectA.Pose = geometricObjectA.Pose * childAPose; testGeometricObjectA.Shape = childA.Shape; testGeometricObjectA.Scale = scaleA * childA.Scale; // Apply scaling to local scale. testCollisionObjectA.SetInternal(collisionObjectA, testGeometricObjectA); var childBPose = childB.Pose; childBPose.Position *= scaleB; // Apply scaling to local translation. testGeometricObjectB.Pose = geometricObjectB.Pose * childBPose; testGeometricObjectB.Shape = childB.Shape; testGeometricObjectB.Scale = scaleB * childB.Scale; // Apply scaling to local scale. testCollisionObjectB.SetInternal(collisionObjectB, testGeometricObjectB); Debug.Assert(testContactSet.Count == 0, "testContactSet needs to be cleared."); testContactSet.Reset(testCollisionObjectA, testCollisionObjectB); if (type == CollisionQueryType.Boolean) { // Boolean queries. collisionAlgorithm.ComputeCollision(testContactSet, CollisionQueryType.Boolean); contactSet.HaveContact = (contactSet.HaveContact || testContactSet.HaveContact); } else { // TODO: We could add existing contacts with the same child shape to childContactSet. // No perturbation test. Most composite shapes are either complex and automatically // have more contacts. Or they are complex and will not be used for stacking // where full contact sets would be needed. testContactSet.IsPerturbationTestAllowed = false; // Make collision check. As soon as we have found contact, we can make faster // contact queries instead of closest-point queries. CollisionQueryType queryType = (contactSet.HaveContact) ? CollisionQueryType.Contacts : type; collisionAlgorithm.ComputeCollision(testContactSet, queryType); contactSet.HaveContact = (contactSet.HaveContact || testContactSet.HaveContact); // Transform contacts into space of composite shape. // And set the shape feature of the contact. int numberOfContacts = testContactSet.Count; for (int i = 0; i < numberOfContacts; i++) { Contact contact = testContactSet[i]; contact.PositionALocal = childAPose.ToWorldPosition(contact.PositionALocal); //if (contact.Lifetime.Ticks == 0) // Currently, all contacts are new, so this check is not necessary. //{ contact.FeatureA = childIndexA; //} contact.PositionBLocal = childBPose.ToWorldPosition(contact.PositionBLocal); //if (contact.Lifetime.Ticks == 0) // Currently, all contacts are new, so this check is not necessary. //{ contact.FeatureB = childIndexB; //} } // Merge child contacts. ContactHelper.Merge(contactSet, testContactSet, type, CollisionDetection.ContactPositionTolerance); } }
public void ModelPrimaryContactsProperties() { Tracing.TraceMsg("Entering TestModelPrimaryContactsProperties"); Contact c = new Contact(); EMail e = new EMail(); e.Primary = true; e.Address = "*****@*****.**"; Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); c.Emails.Add(e); Assert.IsTrue(c.PrimaryEmail == e, "Contact should have one primary Email"); c.Emails.Remove(e); Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); c.Emails.Add(e); Assert.IsTrue(c.PrimaryEmail == e, "Contact should have one primary Email"); c.Emails.RemoveAt(0); Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); foreach (Object o in c.ContactEntry.ExtensionElements) { if (o is EMail) { Assert.IsTrue(o == null, "There should be no email in the collection"); } } StructuredPostalAddress p = CreatePostalAddress(); Assert.IsTrue(c.PrimaryPostalAddress == null, "Contact should have no primary Postal"); c.PostalAddresses.Add(p); Assert.IsTrue(c.PrimaryPostalAddress == p, "Contact should have one primary Postal"); c.PostalAddresses.Remove(p); Assert.IsTrue(c.PrimaryPostalAddress == null, "Contact should have no primary Postal"); PhoneNumber n = new PhoneNumber("123345"); n.Primary = true; Assert.IsTrue(c.PrimaryPhonenumber == null, "Contact should have no primary Phonenumber"); c.Phonenumbers.Add(n); Assert.IsTrue(c.PrimaryPhonenumber == n, "Contact should have one primary Phonenumber"); c.Phonenumbers.Remove(n); Assert.IsTrue(c.PrimaryPhonenumber == null, "Contact should have no primary Phonenumber"); IMAddress i = new IMAddress("*****@*****.**"); i.Primary = true; Assert.IsTrue(c.PrimaryIMAddress == null, "Contact should have no primary IM"); c.IMs.Add(new IMAddress()); c.IMs.Add(i); Assert.IsTrue(c.PrimaryIMAddress == i, "Contact should have one primary IMAddress"); c.IMs.Remove(i); Assert.IsTrue(c.PrimaryIMAddress == null, "Contact should have no primary IM"); }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelBatchContactsTest() { const int numberOfInserts = 5; Tracing.TraceMsg("Entering ModelInsertContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); List <Contact> list = new List <Contact>(); Feed <Contact> f = cr.GetContacts(); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; GDataBatchEntryData g = new GDataBatchEntryData(); g.Id = i.ToString(); g.Type = GDataBatchOperationType.insert; entry.BatchData = g; list.Add(entry); } Feed <Contact> r = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); list.Clear(); int iVerify = 0; foreach (Contact c in r.Entries) { // let's count and update them iVerify++; c.Name.FamilyName = "get a nother one"; c.BatchData.Type = GDataBatchOperationType.update; list.Add(c); } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 inserts"); Feed <Contact> u = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); list.Clear(); iVerify = 0; foreach (Contact c in u.Entries) { // let's count and update them iVerify++; c.BatchData.Type = GDataBatchOperationType.delete; list.Add(c); } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 updates"); Feed <Contact> d = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); iVerify = 0; foreach (Contact c in d.Entries) { if (c.BatchData.Status.Code == 200) { // let's count and update them iVerify++; } } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 deletes"); }
public IEnumerable <Note> GetNotes(Contact contact) { throw new System.NotImplementedException(); }
public IEnumerable <Task> GetTasks(Contact contact) { throw new System.NotImplementedException(); }
public IEnumerable <Contact> saveContact(Contact contact) { return((from c in database.Table <Contact>() select c).ToList()); }
public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities) { _step = step; _count = count; _positions = positions; _velocities = velocities; _contacts = contacts; // grow the array if (VelocityConstraints == null || VelocityConstraints.Length < count) { VelocityConstraints = new ContactVelocityConstraint[count * 2]; _positionConstraints = new ContactPositionConstraint[count * 2]; for (int i = 0; i < VelocityConstraints.Length; i++) { VelocityConstraints[i] = new ContactVelocityConstraint(); } for (int i = 0; i < _positionConstraints.Length; i++) { _positionConstraints[i] = new ContactPositionConstraint(); } } // Initialize position independent portions of the constraints. for (int i = 0; i < _count; ++i) { Contact contact = contacts[i]; Fixture fixtureA = contact.FixtureA; Fixture fixtureB = contact.FixtureB; Shape shapeA = fixtureA.Shape; Shape shapeB = fixtureB.Shape; float radiusA = shapeA.Radius; float radiusB = shapeB.Radius; Body bodyA = fixtureA.Body; Body bodyB = fixtureB.Body; Manifold manifold = contact.Manifold; int pointCount = manifold.PointCount; Debug.Assert(pointCount > 0); ContactVelocityConstraint vc = VelocityConstraints[i]; vc.Friction = contact.Friction; vc.Restitution = contact.Restitution; vc.TangentSpeed = contact.TangentSpeed; vc.IndexA = bodyA.IslandIndex; vc.IndexB = bodyB.IslandIndex; vc.InvMassA = bodyA._invMass; vc.InvMassB = bodyB._invMass; vc.InvIA = bodyA._invI; vc.InvIB = bodyB._invI; vc.ContactIndex = i; vc.PointCount = pointCount; vc.K.SetZero(); vc.NormalMass.SetZero(); ContactPositionConstraint pc = _positionConstraints[i]; pc.IndexA = bodyA.IslandIndex; pc.IndexB = bodyB.IslandIndex; pc.InvMassA = bodyA._invMass; pc.InvMassB = bodyB._invMass; pc.LocalCenterA = bodyA._sweep.LocalCenter; pc.LocalCenterB = bodyB._sweep.LocalCenter; pc.InvIA = bodyA._invI; pc.InvIB = bodyB._invI; pc.LocalNormal = manifold.LocalNormal; pc.LocalPoint = manifold.LocalPoint; pc.PointCount = pointCount; pc.RadiusA = radiusA; pc.RadiusB = radiusB; pc.Type = manifold.Type; for (int j = 0; j < pointCount; ++j) { ManifoldPoint cp = manifold.Points[j]; VelocityConstraintPoint vcp = vc.Points[j]; #pragma warning disable 162 // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (Settings.EnableWarmstarting) { vcp.NormalImpulse = _step.dtRatio * cp.NormalImpulse; vcp.TangentImpulse = _step.dtRatio * cp.TangentImpulse; } else { vcp.NormalImpulse = 0.0f; vcp.TangentImpulse = 0.0f; } #pragma warning restore 162 vcp.rA = Vector2.Zero; vcp.rB = Vector2.Zero; vcp.NormalMass = 0.0f; vcp.TangentMass = 0.0f; vcp.VelocityBias = 0.0f; pc.LocalPoints[j] = cp.LocalPoint; } } }
private void OnContactAdded(ContactDetailViewModel source, Contact contact) { Contacts.Add(new ContactViewModel(contact)); }
DetailsLazy(string genderC, Guid guid, List <Address> addresses, Login login, Contact contactDetails, string clientIdentifier, string id, string name, string surname, DateTime dateOfBirth, string gender) : base(guid, addresses, login, contactDetails, clientIdentifier, id, name, surname, dateOfBirth, gender) { this.genderC = genderC; }
// Compute contacts between a shape and the child shapes of a <see cref="CompositeShape"/>. // testXxx are initialized objects which are re-used to avoid a lot of GC garbage. private void AddChildContacts(ContactSet contactSet, bool swapped, int childIndex, CollisionQueryType type, ContactSet testContactSet, CollisionObject testCollisionObject, TestGeometricObject testGeometricObject) { // This method is also used in RayCompositeAlgorithm.cs. Keep changes in sync! // Object A should be the CompositeShape. CollisionObject collisionObjectA = (swapped) ? contactSet.ObjectB : contactSet.ObjectA; CollisionObject collisionObjectB = (swapped) ? contactSet.ObjectA : contactSet.ObjectB; IGeometricObject geometricObjectA = collisionObjectA.GeometricObject; IGeometricObject geometricObjectB = collisionObjectB.GeometricObject; Vector3F scaleA = geometricObjectA.Scale; IGeometricObject childA = ((CompositeShape)geometricObjectA.Shape).Children[childIndex]; // Find collision algorithm. CollisionAlgorithm collisionAlgorithm = CollisionDetection.AlgorithmMatrix[childA, geometricObjectB]; // ----- Set the shape temporarily to the current child. // (Note: The scaling is either uniform or the child has no local rotation. Therefore, we only // need to apply the scale of the parent to the scale and translation of the child. We can // ignore the rotation.) Debug.Assert( (scaleA.X == scaleA.Y && scaleA.Y == scaleA.Z) || !childA.Pose.HasRotation, "CompositeShapeAlgorithm should have thrown an exception. Non-uniform scaling is not supported for rotated children."); var childPose = childA.Pose; childPose.Position *= scaleA; // Apply scaling to local translation. testGeometricObject.Pose = geometricObjectA.Pose * childPose; testGeometricObject.Shape = childA.Shape; testGeometricObject.Scale = scaleA * childA.Scale; // Apply scaling to local scale. testCollisionObject.SetInternal(collisionObjectA, testGeometricObject); // Create a temporary contact set. // (ObjectA and ObjectB should have the same order as in contactSet; otherwise we couldn't // simply merge them.) Debug.Assert(testContactSet.Count == 0, "testContactSet needs to be cleared."); if (swapped) { testContactSet.Reset(collisionObjectB, testCollisionObject); } else { testContactSet.Reset(testCollisionObject, collisionObjectB); } if (type == CollisionQueryType.Boolean) { // Boolean queries. collisionAlgorithm.ComputeCollision(testContactSet, CollisionQueryType.Boolean); contactSet.HaveContact = (contactSet.HaveContact || testContactSet.HaveContact); } else { // No perturbation test. Most composite shapes are either complex and automatically // have more contacts. Or they are complex and will not be used for stacking // where full contact sets would be needed. testContactSet.IsPerturbationTestAllowed = false; // TODO: We could add existing contacts with the same child shape to childContactSet. // Collision algorithms could take advantage of existing contact information to speed up // calculations. However, at the moment the collision algorithms ignore existing contacts. // If we add the exiting contacts to childContactSet we need to uncomment the comment // code lines below. // Transform contacts into space of child shape. //foreach (Contact c in childContactSet) //{ // if (childContactSet.ObjectA == childCollisionObject) // c.PositionALocal = childPose.ToLocalPosition(c.PositionALocal); // else // c.PositionBLocal = childPose.ToLocalPosition(c.PositionBLocal); //} // Make collision check. As soon as we have found contact, we can make faster // contact queries instead of closest-point queries. CollisionQueryType queryType = (contactSet.HaveContact) ? CollisionQueryType.Contacts : type; collisionAlgorithm.ComputeCollision(testContactSet, queryType); contactSet.HaveContact = (contactSet.HaveContact || testContactSet.HaveContact); // Transform contacts into space of composite shape. // And set the shape feature of the contact. int numberOfContacts = testContactSet.Count; for (int i = 0; i < numberOfContacts; i++) { Contact contact = testContactSet[i]; if (swapped) { contact.PositionBLocal = childPose.ToWorldPosition(contact.PositionBLocal); //if (contact.Lifetime.Ticks == 0) // Currently, all contacts are new, so this check is not necessary. //{ contact.FeatureB = childIndex; //} } else { contact.PositionALocal = childPose.ToWorldPosition(contact.PositionALocal); //if (contact.Lifetime.Ticks == 0) // Currently, all contacts are new, so this check is not necessary. //{ contact.FeatureA = childIndex; //} } } // Merge child contacts. ContactHelper.Merge(contactSet, testContactSet, type, CollisionDetection.ContactPositionTolerance); } }
public AddContactPage(Contact contact = null) { InitializeComponent(); BindingContext = new AddContactViewModel(contact); }
public IActionResult Create(Contact contact) { DataAccess.Contacts.Add(contact); return(RedirectToAction("Index", "Home")); }
public ContactEventArgs(Contact contacto) { Contacto = contacto; }
public async Task AddAsync(Contact contact) { await this.context.AddAsync(contact); await this.context.SaveChangesAsync(); }
public void TearDownObjects() { _contact = null; _contactService = null; _mockContactRepository = null; }
//Set default sorting by last name public int CompareTo(Contact cont) { return(this.lastname.CompareTo(cont.lastname)); }
public static ContactDto AsDto(this Contact contact) { return(new ContactDto(contact.Id, contact.First, contact.Middle, contact.Last, contact.Addresses, contact.Phones, contact.Email)); }
public bool MyOnCollision(Fixture f1, Fixture f2, Contact contact) { return(f2.Body.BodyName == null); }
public List<DateTime> GetCoversationDateList(Contact contract, DateTime searchDate, SearchDirection direction = SearchDirection.None) { List<DateTime> list = new List<DateTime>(); if ((searchDate == DateTime.MaxValue || searchDate == DateTime.MinValue) && (direction == SearchDirection.Forward || direction == SearchDirection.Backward)) { return list; } bool insertAt0 = true; if (direction == SearchDirection.None || direction == SearchDirection.Last) { insertAt0 = true; } else if (direction == SearchDirection.First) { insertAt0 = false; } else if (direction == SearchDirection.Forward) { insertAt0 = false; } else if (direction == SearchDirection.Backward) { insertAt0 = true; } using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand("GetCoversationDateList", connection)) { connection.Open(); command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.AddWithValue("@ContratId", contract.Id); command.Parameters.AddWithValue("@SearchDate", searchDate.Date == DateTime.MinValue ? new DateTime(1753, 1, 1) : searchDate.Date); command.Parameters.AddWithValue("@Pagesize", pageSize); command.Parameters.AddWithValue("@Direction", (int)direction); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DateTime messageDate = DateTime.Parse(reader["MessageDate"].ToString()); if (insertAt0) { list.Insert(0, messageDate); } else { list.Add(messageDate); } } } } } return list; }
protected override async void OnInitialized() { InitializeComponent(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //MSSqlServer //string connectionString = MSSqlConnectionProvider.GetConnectionString("YOUR_SERVER_NAME", "sa", "", "XamarinDemo"); //SQLite var filePath = Path.Combine(documentsPath, "xpoXamarinDemo.db"); string connectionString = SQLiteConnectionProvider.GetConnectionString(filePath) + ";Cache=Shared;"; //In-memory data store with saving/loading from the xml file //var filePath = Path.Combine(documentsPath, "xpoXamarinDemo.xml"); //string connectionString = InMemoryDataStore.GetConnectionString(filePath); //DevExpress.Xpo.SimpleDataLayer.SuppressReentrancyAndThreadSafetyCheck = true; XPOWebApi.Register(); connectionString = XPOWebApi.GetConnectionString("http://192.168.122.101/BitServer", string.Empty, "db1"); XpoHelper.InitXpo(connectionString); using (var UoW = XpoHelper.CreateUnitOfWork()) { if (UoW.Query <Contact>().Count() == 0) { Contact Joche = new Contact(UoW) { Name = "Jose Manuel Ojeda Melgar", Phone = "+7897654321" }; Contact Javier = new Contact(UoW) { Name = "Jose Javier Columbie", Phone = "+1897654321" }; Contact Jaime = new Contact(UoW) { Name = "Jaime Macias", Phone = "+123423431" }; Contact Rafael = new Contact(UoW) { Name = "Rafael Gonzales", Phone = "+14305345345" }; } if (UoW.InTransaction) { UoW.CommitChanges(); } } await NavigationService.NavigateAsync("NavigationPage/ContactList"); }
public void SetUp() { var logger = new Mock <ILogger <Web.Services.OutcomeSectionReviewOrchestrator> >(); _applyApiClient = new Mock <IRoatpApplicationApiClient>(); _moderationApiClient = new Mock <IRoatpModerationApiClient>(); _clarificationApiClient = new Mock <IRoatpClarificationApiClient>(); var supplementaryInformationService = new Mock <ISupplementaryInformationService>(); _orchestrator = new Web.Services.OutcomeSectionReviewOrchestrator(logger.Object, _applyApiClient.Object, _moderationApiClient.Object, _clarificationApiClient.Object, supplementaryInformationService.Object); _userId = _user.UserId(); _userName = _user.UserDisplayName(); _application = new Apply { ApplicationId = _applicationId, ApplyData = new ApplyData { ApplyDetails = new ApplyDetails { } }, Assessor1UserId = _userId }; _contact = new Contact { Email = _userId, GivenNames = _user.GivenName(), FamilyName = _user.Surname() }; _blindAssessmentOutcome = new BlindAssessmentOutcome { ApplicationId = _applicationId, SequenceNumber = _sequenceNumber, SectionNumber = _sectionNumber, PageId = _pageId, Assessor1UserId = _userId, Assessor1Name = _userName, Assessor1ReviewStatus = AssessorPageReviewStatus.Pass, Assessor1ReviewComment = null, Assessor2UserId = $"{_userId}-2", Assessor2Name = $"{_userName}-2", Assessor2ReviewStatus = AssessorPageReviewStatus.Fail, Assessor2ReviewComment = "Failed" }; _clarificationPage = new ClarificationPage { ApplicationId = _applicationId, SequenceNumber = _sequenceNumber, SectionNumber = _sectionNumber, PageId = _pageId, Questions = new List <Question> { new Question { QuestionId = "Q1" } }, Answers = new List <Answer> { new Answer { QuestionId = "Q1", Value = "value" } } }; _pageReviewOutcome = new ClarificationPageReviewOutcome { ApplicationId = _applicationId, SequenceNumber = _sequenceNumber, SectionNumber = _sectionNumber, PageId = _pageId, UserId = _userId, UserName = _userName, Status = ClarificationPageReviewStatus.Pass, ModeratorUserId = _userId, ModeratorUserName = _userName, ModeratorReviewStatus = ApplyTypes.Moderator.ModeratorPageReviewStatus.Fail, ModeratorReviewComment = "Not Good", ClarificationResponse = "Response", ClarificationFile = null }; _applyApiClient.Setup(x => x.GetApplication(_applicationId)).ReturnsAsync(_application); _applyApiClient.Setup(x => x.GetContactForApplication(_applicationId)).ReturnsAsync(_contact); _moderationApiClient.Setup(x => x.GetBlindAssessmentOutcome(_applicationId, _sequenceNumber, _sectionNumber, _pageId)) .ReturnsAsync(_blindAssessmentOutcome); _clarificationApiClient.Setup(x => x.GetClarificationPage(_applicationId, _sequenceNumber, _sectionNumber, _pageId)) .ReturnsAsync(_clarificationPage); _clarificationApiClient.Setup(x => x.GetClarificationPageReviewOutcomesForSection(_applicationId, _sequenceNumber, _sectionNumber, _userId)) .ReturnsAsync(new List <ClarificationPageReviewOutcome> { _pageReviewOutcome }); _clarificationApiClient.Setup(x => x.GetClarificationPageReviewOutcome(_applicationId, _sequenceNumber, _sectionNumber, _pageId, _userId)) .ReturnsAsync(_pageReviewOutcome); }
private void processContacts(Node node, NodeAttributes attributes, IEnumerable <FieldViewModel> customFields, int jobId, IEnumerable <DropdownValueViewModel> dropdownFields, string fileName) { #region Declarations StringBuilder hash = new StringBuilder(); IList <Email> emails = new List <Email>(); var guid = Guid.NewGuid(); RawContact contact = new RawContact(); IList <ImportCustomData> contactCustomData = new List <ImportCustomData>(); IList <ImportPhoneData> contactPhoneData = new List <ImportPhoneData>(); StringBuilder customFieldData = new StringBuilder(); bool isDuplicateFromFile = false; LeadAdapterRecordStatus status = LeadAdapterRecordStatus.Undefined; SearchResult <Contact> duplicateResult = new SearchResult <Contact>(); Dictionary <string, dynamic> oldNewValues = new Dictionary <string, dynamic> { }; #endregion #region BuilderNumber Validation string builderNumber = attributes[_fieldMappings.GetOrDefault("BuilderNumber")].Value; bool builderNumberPass = leadAdapterAndAccountMap.BuilderNumber.ToLower().Split(',').Contains(builderNumber.ToLower()); #endregion #region Community Number Validation string communityNumber = attributes[_fieldMappings.GetOrDefault("CommunityNumber")].Value; bool communityNumberPass = true; #endregion #region ContactsProcessing string firstName = attributes[_fieldMappings.GetOrDefault("FirstName")].Value; string lastName = attributes[_fieldMappings.GetOrDefault("LastName")].Value; string primaryEmail = attributes[_fieldMappings.GetOrDefault("Email")].Value; string companyName = string.Empty; #region HashPreparation Action <string> HashAppend = (n) => { if (string.IsNullOrEmpty(n)) { hash.Append("-").Append(string.Empty); } else { hash.Append("-").Append(n); } }; if (!string.IsNullOrEmpty(primaryEmail)) { Email _primaryemail = new Email() { EmailId = primaryEmail, AccountID = leadAdapterAndAccountMap.AccountID, IsPrimary = true }; emails.Add(_primaryemail); hash.Append("-").Append(primaryEmail); } else { hash.Append("-").Append("*****@*****.**"); } HashAppend(firstName); HashAppend(lastName); HashAppend(companyName); #endregion Person person = new Person() { FirstName = firstName, LastName = lastName, CompanyName = companyName, Emails = emails, AccountID = AccountID }; if (builderNumberPass && communityNumberPass) { bool duplicatEemailCount = hashes.Any(h => !string.IsNullOrEmpty(primaryEmail) && h.Contains(primaryEmail)); if (duplicatEemailCount || (string.IsNullOrEmpty(primaryEmail) && hashes.Where(h => h.Contains(hash.ToString())).Any())) { isDuplicateFromFile = true; } else if (!duplicatEemailCount) { isDuplicateFromFile = false; } } hashes.Add(hash.ToString()); if (builderNumberPass && communityNumberPass) { SearchParameters parameters = new SearchParameters() { AccountId = AccountID }; IEnumerable <Contact> duplicateContacts = contactService.CheckIfDuplicate(new CheckContactDuplicateRequest() { Person = person }).Contacts; duplicateResult = new SearchResult <Contact>() { Results = duplicateContacts, TotalHits = duplicateContacts != null?duplicateContacts.Count() : 0 }; } if (!builderNumberPass) { status = LeadAdapterRecordStatus.BuilderNumberFailed; } else if (!communityNumberPass) { status = LeadAdapterRecordStatus.CommunityNumberFailed; } else if (isDuplicateFromFile) { status = LeadAdapterRecordStatus.DuplicateFromFile; } else if (duplicateResult.TotalHits > 0) { status = LeadAdapterRecordStatus.Updated; guid = duplicateResult.Results.FirstOrDefault().ReferenceId; } else { status = LeadAdapterRecordStatus.Added; } Contact duplicatePerson = default(Person); if (status == LeadAdapterRecordStatus.Updated) { duplicatePerson = duplicateResult.Results.FirstOrDefault(); } else { duplicatePerson = new Person(); } Func <NodeAttribute, string, bool> checkIfStandardField = (name, field) => { return(name.Name.ToLower() == _fieldMappings.GetOrDefault(field).NullSafeToLower()); }; try { foreach (var attribute in attributes) { var name = attribute.Name.ToLower(); var value = attribute.Value; ImportCustomData customData = new ImportCustomData(); try { var elementValue = string.Empty; if (checkIfStandardField(attribute, "FirstName")) { elementValue = ((Person)duplicatePerson).FirstName == null ? string.Empty : ((Person)duplicatePerson).FirstName; contact.FirstName = value; } else if (checkIfStandardField(attribute, "LastName")) { elementValue = ((Person)duplicatePerson).LastName; contact.LastName = value; } else if (checkIfStandardField(attribute, "Email")) { Email primaryemail = duplicatePerson.Emails.IsAny() ? duplicatePerson.Emails.Where(i => i.IsPrimary == true).FirstOrDefault() : null; if (primaryemail != null) { elementValue = primaryemail.EmailId; } contact.PrimaryEmail = value; } else if (checkIfStandardField(attribute, "Company")) { // get company dynamic elementValue = duplicatePerson.CompanyName; contact.CompanyName = value; } else if (checkIfStandardField(attribute, "PhoneNumber") || checkIfStandardField(attribute, "Phone")) { DropdownValueViewModel dropdownValue = dropdownFields.Where(i => i.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault(); var mobilephone = default(Phone); ImportPhoneData phoneData = new ImportPhoneData(); phoneData.ReferenceID = guid; if (dropdownValue != null) { if (!string.IsNullOrEmpty(value)) { string phoneNumber = GetNonNumericData(value); if (IsValidPhoneNumberLength(phoneNumber)) { contact.PhoneData = dropdownValue.DropdownValueID.ToString() + "|" + phoneNumber; phoneData.PhoneType = (int?)dropdownValue.DropdownValueID; phoneData.PhoneNumber = phoneNumber; contactPhoneData.Add(phoneData); } } mobilephone = duplicatePerson.Phones.IsAny() ? duplicatePerson.Phones.Where(i => i.PhoneType == dropdownValue.DropdownValueID).FirstOrDefault() : null; } if (mobilephone != null) { elementValue = mobilephone.Number; } } else if (checkIfStandardField(attribute, "Country")) { var countryvalue = value.Replace(" ", string.Empty).ToLower(); if (countryvalue == "usa" || countryvalue == "us" || countryvalue == "unitedstates" || countryvalue == "unitedstatesofamerica") { contact.Country = "US"; } else if (countryvalue == "ca" || countryvalue == "canada") { contact.Country = "CA"; } else { contact.Country = value; } } else if (checkIfStandardField(attribute, "StreetAddress")) { contact.AddressLine1 = value; } else if (checkIfStandardField(attribute, "City")) { contact.City = value; } else if (checkIfStandardField(attribute, "State")) { contact.State = value; } else if (checkIfStandardField(attribute, "PostalCode")) { contact.ZipCode = value; } else { var customField = customFields.Where(i => i.Title.Replace(" ", string.Empty).ToLower() == (name + "(" + leadAdapterType.ToString().ToLower() + ")")).FirstOrDefault(); if (customField != null) { var customfielddata = duplicatePerson.CustomFields == null ? null : duplicatePerson.CustomFields.Where(i => i.CustomFieldId == customField.FieldId).FirstOrDefault(); if (customfielddata != null) { elementValue = customfielddata.Value; } customData.FieldID = customField.FieldId; customData.FieldTypeID = (int?)customField.FieldInputTypeId; customData.ReferenceID = guid; if (customField.FieldInputTypeId == FieldType.date || customField.FieldInputTypeId == FieldType.datetime || customField.FieldInputTypeId == FieldType.time) { DateTime converteddate; if (DateTime.TryParse(value, out converteddate)) { customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + converteddate.ToString("MM/dd/yyyy hh:mm tt")); customData.FieldValue = converteddate.ToString("MM/dd/yyyy hh:mm tt"); } } else if (customField.FieldInputTypeId == FieldType.number) { double number; if (double.TryParse(value, out number)) { customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + number.ToString()); customData.FieldValue = number.ToString(); } } else if (customField.FieldInputTypeId == FieldType.url) { if (IsValidURL(value.Trim())) { customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim()); customData.FieldValue = value.Trim(); } } else { customFieldData.Append("~" + customField.FieldId + "##$##" + (byte)customField.FieldInputTypeId + "|" + value.Trim()); customData.FieldValue = value.Trim(); } contactCustomData.Add(customData); } } if (!oldNewValues.ContainsKey(attribute.Name)) { oldNewValues.Add(attribute.Name, new { OldValue = string.IsNullOrEmpty(elementValue) ? string.Empty : elementValue, NewValue = value }); } } catch (Exception ex) { Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : " + attribute.Name, ex); } } } catch (Exception ex) { Logger.Current.Error("An exception occured in Genereating old new values element in Trulia : ", ex); } #endregion if (customFieldData.Length > 0) { customFieldData.Remove(0, 1); } contact.CustomFieldsData = customFieldData.ToString(); contact.ReferenceId = guid; contact.AccountID = AccountID; contact.IsBuilderNumberPass = builderNumberPass; contact.IsCommunityNumberPass = communityNumberPass; contact.LeadAdapterRecordStatusId = (byte)status; contact.JobID = jobId; contact.ContactStatusID = 1; contact.ContactTypeID = 1; JavaScriptSerializer js = new JavaScriptSerializer(); contact.LeadAdapterSubmittedData = js.Serialize(oldNewValues); contact.LeadAdapterRowData = node.Current != null?node.Current.ToString() : string.Empty; personCustomFieldData.AddRange(contactCustomData); personPhoneData.AddRange(contactPhoneData); contact.ValidEmail = ValidateEmail(contact); RawContact duplicate_data = null; if (!string.IsNullOrEmpty(contact.PrimaryEmail)) { duplicate_data = persons.Where(p => string.Compare(p.PrimaryEmail, contact.PrimaryEmail, true) == 0).FirstOrDefault(); } else { duplicate_data = persons.Where(p => string.Compare(p.FirstName, contact.FirstName, true) == 0 && string.Compare(p.LastName, contact.LastName, true) == 0).FirstOrDefault(); } if (duplicate_data != null) { contact.IsDuplicate = true; //RawContact updatedperson = MergeDuplicateData(duplicate_data, contact, guid); //duplicate_data = updatedperson; } persons.Add(contact); }
/// <summary> /// Call this to draw shapes and other debug draw data. /// </summary> private void DrawDebugData() { if ((Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape) { foreach (Body b in World.BodyList) { Transform xf; b.GetTransform(out xf); foreach (Fixture f in b.FixtureList) { if (b.Enabled == false) { DrawShape(f, xf, InactiveShapeColor); } else if (b.BodyType == BodyType.Static) { DrawShape(f, xf, StaticShapeColor); } else if (b.BodyType == BodyType.Kinematic) { DrawShape(f, xf, KinematicShapeColor); } else if (b.Awake == false) { DrawShape(f, xf, SleepingShapeColor); } else { DrawShape(f, xf, DefaultShapeColor); } } } } if ((Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints) { const float axisScale = 0.3f; for (int i = 0; i < _pointCount; ++i) { ContactPoint point = _points[i]; if (point.State == PointState.Add) { // Add DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.95f, 0.3f)); } else if (point.State == PointState.Persist) { // Persist DrawPoint(point.Position, 0.1f, new Color(0.3f, 0.3f, 0.95f)); } if ((Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals) { Vector2 p1 = point.Position; Vector2 p2 = p1 + axisScale * point.Normal; DrawSegment(p1, p2, new Color(0.4f, 0.9f, 0.4f)); } } _pointCount = 0; } if ((Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints) { foreach (Body body in World.BodyList) { foreach (Fixture f in body.FixtureList) { PolygonShape polygon = f.Shape as PolygonShape; if (polygon != null) { Transform xf; body.GetTransform(out xf); for (int i = 0; i < polygon.Vertices.Count; i++) { Vector2 tmp = MathUtils.Multiply(ref xf, polygon.Vertices[i]); DrawPoint(tmp, 0.1f, Color.Red); } } } } } if ((Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint) { foreach (Joint j in World.JointList) { DrawJoint(j); } } if ((Flags & DebugViewFlags.Pair) == DebugViewFlags.Pair) { Color color = new Color(0.3f, 0.9f, 0.9f); for (int i = 0; i < World.ContactManager.ContactList.Count; i++) { Contact c = World.ContactManager.ContactList[i]; Fixture fixtureA = c.FixtureA; Fixture fixtureB = c.FixtureB; AABB aabbA; fixtureA.GetAABB(out aabbA, 0); AABB aabbB; fixtureB.GetAABB(out aabbB, 0); Vector2 cA = aabbA.Center; Vector2 cB = aabbB.Center; DrawSegment(cA, cB, color); } } if ((Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB) { Color color = new Color(0.9f, 0.3f, 0.9f); IBroadPhase bp = World.ContactManager.BroadPhase; foreach (Body b in World.BodyList) { if (b.Enabled == false) { continue; } foreach (Fixture f in b.FixtureList) { for (int t = 0; t < f.ProxyCount; ++t) { FixtureProxy proxy = f.Proxies[t]; AABB aabb; bp.GetFatAABB(proxy.ProxyId, out aabb); DrawAABB(ref aabb, color); } } } } if ((Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass) { foreach (Body b in World.BodyList) { Transform xf; b.GetTransform(out xf); xf.Position = b.WorldCenter; DrawTransform(ref xf); } } if ((Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers) { for (int i = 0; i < World.ControllerList.Count; i++) { Controller controller = World.ControllerList[i]; BuoyancyController buoyancy = controller as BuoyancyController; if (buoyancy != null) { AABB container = buoyancy.Container; DrawAABB(ref container, Color.LightBlue); } } } if ((Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel) { DrawDebugPanel(); } }
public async Task DeleteContact(Contact contact) { Contacts.Remove(contact); await SaveChangesAsync(); }
public TaskWrapper UpdateTask( int taskid, string title, string description, ApiDateTime deadline, Guid responsibleid, int categoryid, int contactid, string entityType, int entityid, bool isNotify, int alertValue) { if (!string.IsNullOrEmpty(entityType) && !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0 ) || categoryid <= 0) { throw new ArgumentException(); } var listItem = DaoFactory.GetListItemDao().GetByID(categoryid); if (listItem == null) { throw new ItemNotFoundException(CRMErrorsResource.TaskCategoryNotFound); } var task = new Task { ID = taskid, Title = title, Description = description, DeadLine = deadline, AlertValue = alertValue, ResponsibleID = responsibleid, CategoryID = categoryid, ContactID = contactid, EntityID = entityid, EntityType = ToEntityType(entityType) }; task = DaoFactory.GetTaskDao().SaveOrUpdateTask(task); if (isNotify) { Contact taskContact = null; Cases taskCase = null; Deal taskDeal = null; if (task.ContactID > 0) { taskContact = DaoFactory.GetContactDao().GetByID(task.ContactID); } if (task.EntityID > 0) { switch (task.EntityType) { case EntityType.Case: taskCase = DaoFactory.GetCasesDao().GetByID(task.EntityID); break; case EntityType.Opportunity: taskDeal = DaoFactory.GetDealDao().GetByID(task.EntityID); break; } } NotifyClient.Instance.SendAboutResponsibleByTask(task, listItem.Title, taskContact, taskCase, taskDeal, null); } MessageService.Send(Request, MessageAction.CrmTaskUpdated, task.Title); return(ToTaskWrapper(task)); }
public ActionResult Add(Contact c, HttpPostedFileBase file) { try { #region // Fetch Country & State List <Country> allCountry = new List <Country>(); List <State> states = new List <State>(); using (MYCONTACTBOOKEntities dc = new MYCONTACTBOOKEntities()) { allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList(); if (c.CountryID > 0) { states = dc.States.Where(a => a.CountryID.Equals(c.CountryID)).OrderBy(a => a.StateName).ToList(); } } ViewBag.Country = new SelectList(allCountry, "CountryID", "CountryName", c.CountryID); ViewBag.State = new SelectList(states, "StateID", "StateName", c.StateID); #endregion #region// Validate file if selected if (file != null) { if (file.ContentLength > (512 * 1000)) // 512 KB { ModelState.AddModelError("FileErrorMessage", "File size must be within 512 KB"); } string[] allowedType = new string[] { "image/png", "image/gif", "image/jpeg", "image/jpg" }; bool isFileTypeValid = false; foreach (var i in allowedType) { if (file.ContentType == i.ToString()) { isFileTypeValid = true; break; } } if (!isFileTypeValid) { ModelState.AddModelError("FileErrorMessage", "Only .png, .gif and .jpg file type allowed"); } } #endregion #region// Validate Model & Save to Database if (ModelState.IsValid) { //Save here if (file != null) { string savePath = Server.MapPath("~/Image"); string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); file.SaveAs(Path.Combine(savePath, fileName)); c.ImagePath = fileName; } ServiceRepository serviceObj = new ServiceRepository(); HttpResponseMessage response = serviceObj.PostResponse("api/Values/", c); if (response.IsSuccessStatusCode) { response.EnsureSuccessStatusCode(); return(RedirectToAction("GetContactlist")); } return(View(c)); } else { ModelState.AddModelError(string.Empty, "Please capture all the required fileds."); return(View(c)); } } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.ToString()); return(View(c)); } #endregion }
public void Edit(Contact contact) { _context.Contacts.Update(contact); _context.SaveChanges(); }
public ContactViewModel() { _contact = new Contact { Birthday = new DateTime(1990, 11, 1), FirstName = "Aaberg", LastName = "Jesper", NumberOfComputers = 2 }; }
public void Delete(Contact contact) { _context.Contacts.Remove(contact); _context.SaveChanges(); }
public IEnumerable <TaskWrapper> CreateTaskGroup( string title, string description, ApiDateTime deadline, Guid responsibleId, int categoryId, int[] contactId, string entityType, int entityId, bool isNotify, int alertValue) { var tasks = new List <Task>(); if ( !string.IsNullOrEmpty(entityType) && !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) ) { throw new ArgumentException(); } foreach (var cid in contactId) { tasks.Add(new Task { Title = title, Description = description, ResponsibleID = responsibleId, CategoryID = categoryId, DeadLine = deadline, ContactID = cid, EntityType = ToEntityType(entityType), EntityID = entityId, IsClosed = false, AlertValue = alertValue }); } tasks = DaoFactory.GetTaskDao().SaveOrUpdateTaskList(tasks).ToList(); string taskCategory = null; if (isNotify) { if (categoryId > 0) { var listItem = DaoFactory.GetListItemDao().GetByID(categoryId); if (listItem == null) { throw new ItemNotFoundException(); } taskCategory = listItem.Title; } } for (var i = 0; i < tasks.Count; i++) { if (!isNotify) { continue; } Contact taskContact = null; Cases taskCase = null; Deal taskDeal = null; if (tasks[i].ContactID > 0) { taskContact = DaoFactory.GetContactDao().GetByID(tasks[i].ContactID); } if (tasks[i].EntityID > 0) { switch (tasks[i].EntityType) { case EntityType.Case: taskCase = DaoFactory.GetCasesDao().GetByID(tasks[i].EntityID); break; case EntityType.Opportunity: taskDeal = DaoFactory.GetDealDao().GetByID(tasks[i].EntityID); break; } } NotifyClient.Instance.SendAboutResponsibleByTask(tasks[i], taskCategory, taskContact, taskCase, taskDeal, null); } if (tasks.Any()) { var contacts = DaoFactory.GetContactDao().GetContacts(contactId); var task = tasks.First(); MessageService.Send(Request, MessageAction.ContactsCreatedCrmTasks, contacts.Select(x => x.GetTitle()), task.Title); } return(ToTaskListWrapper(tasks)); }