public void SetUp() { _httpClient = Substitute.For<HttpClient>(); _sut = new RdStationApiClient(_httpClient); _lead = new Lead("FakeToken", "FakeIdentificador", "FakeEmail"); _leadStatus = new LeadStatusRoot("FakeAuthToken", new LeadStatus(LifeCycleLeadStage.LeadQualificado, true)); }
internal void AddLead(Lead l, string action) { _object.Remove(l.WorkflowID); _action.Remove(l.WorkflowID); _object.Add(l.WorkflowID, l); _action.Add(l.WorkflowID, action); }
public LeadDto Map(Lead entity) { return new LeadDto { Id = entity.Id, Name = entity.Name, Address1 = entity.Address1, Address2 = entity.Address2, Address3 = entity.Address3, PhoneNumber = entity.PhoneNumber, EmailAddress = entity.EmailAddress, AssignedToConsultantId = entity.AssignedToConsultantId, SignedUp = entity.SignedUp }; }
public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context() { var context = new XrmFakedContext(); var relationship = new XrmFakedRelationship() { IntersectEntity = "accountleads", Entity1Attribute = "accountid", Entity2Attribute = "leadid", Entity1LogicalName = "account", Entity2LogicalName = "lead" }; context.AddRelationship("accountleads", relationship); var service = context.GetFakedOrganizationService(); using (var ctx = new XrmServiceContext(service)) { var account = new Account() { Name = "Test account" }; ctx.AddObject(account); var contact = new Lead() { FirstName = "Jane", LastName = "Doe" }; ctx.AddRelatedObject(account, new Relationship("accountleads"), contact); var result = ctx.SaveChanges(); var resultaccount = ctx.CreateQuery<Account>() .ToList() .FirstOrDefault(); Assert.NotNull(resultaccount); Assert.Equal("Test account", resultaccount.Name); var reaultlead = ctx.CreateQuery<Lead>() .ToList() .FirstOrDefault(); Assert.NotNull(reaultlead); Assert.Equal("Jane", reaultlead.FirstName); Assert.Equal("Doe", reaultlead.LastName); var relationshipRecords = ctx.CreateQuery("accountleads") .ToList(); Assert.NotEmpty(relationshipRecords); } }
public ActionResult Post([FromBody] Lead l) { if (l == null) { return(BadRequest()); } _context.leads.Add(l); _context.SaveChanges(); return(Ok(_context.leads .Include(ls => ls.statustype) .Include(ls => ls.prioritytype) .Include(ls => ls.customer) .Include(ls => ls.customer.detail) .Include(ls => ls.employee) .ToList())); }
public void SendWelcomeEmailTest() { // Arrange var lead = new Lead(); lead.FirstName = "Fadi"; lead.LastName = "Mamar"; lead.Email = "*****@*****.**"; string messege = "Hello " + lead.FullName; string expected = "Message sent: Welcome" + " " + lead.FullName; // Act var confirmation = lead.SendWelcomeEmail(messege); // Assert Assert.AreEqual(expected, confirmation); }
public void Post(Lead lead) { if (ModelState.IsValid) { leads.Add(lead); //Get(lead.Id); } else { var errors = ModelState.Where(e => e.Value.Errors.Count > 0) .Select(e => new { Name = e.Key, Message = e.Value.Errors.First().ErrorMessage, Exception = e.Value.Errors.First().Exception }).ToList(); } }
public void Carregar() { Lead l = new Lead(); l.idlead = int.Parse(Request.QueryString["itemSel"]); l.clinina = UsuarioLogado; l = new LeadController().ListarAlt(l)[0]; ViewState.Add("itemSel", l); txtNome.Text = l.nome_lead; txtTel.Text = l.fone_lead; dropSexo.Text = l.sexo_lead; dropOrigem.Text = l.origem_lead; dropStatus.Text = l.status; }
public ActionResult Delete(int id) { Lead lead = _context.leads.FirstOrDefault(l => l.lead_id == id); if (lead == null) { return(NotFound()); } _context.leads.Remove(lead); _context.SaveChanges(); return(Ok(_context.leads .Include(l => l.statustype) .Include(l => l.prioritytype) .Include(l => l.customer) .Include(l => l.customer.detail) .Include(l => l.employee) .ToList())); }
public async Task <IHttpActionResult> DeleteLead(int id) { Lead lead = await db.Leads.FindAsync(id); if (lead == null) { return(NotFound()); } if (LeadExistsID(id)) { return(BadRequest()); } lead.IsDeleted = true; await db.SaveChangesAsync(); return(Ok(lead)); }
public async Task <Guid> Save(LeadSaveModel lead) { var leadModel = new Lead { Name = lead.Name, PinCode = lead.PinCode, Address = lead.Address, SubAreaId = lead.SubAreaId, Email = lead.Email, MobileNumber = lead.MobileNumber }; await dbContext.Leads.AddAsync(leadModel); await dbContext.SaveChangesAsync(); return(leadModel.Id); }
public async Task <ActionResult> LeadEdit(string id) { // Ensure the user is authenticated if (!SalesforceService.IsUserLoggedIn()) { // Should include a state argument to the URI so that when the dance is done, we can redirect to the page that we were requesting string myUri = SalesforceOAuthRedirectHandler.AuthorizationUri.ToString() + "&state=" + this.Url.RequestContext.HttpContext.Request.RawUrl; return(this.Redirect(myUri)); } // Initalize the Force client SalesforceService service = new SalesforceService(); ForceClient client = service.GetForceClient(); Lead lead = await client.QueryByIdAsync <Lead>("Lead", id); return(View(lead)); }
private void Reset_Click(object sender, EventArgs e) { MName.Clear(); LanguageBox.SelectedItem = null; Lead.Clear(); Others.Clear(); Genre.SelectedItem = null; YearPicker.ResetText(); DatePicker.ResetText(); R1.Checked = false; R2.Checked = false; R3.Checked = false; R4.Checked = false; R5.Checked = false; movier.Checked = false; seriesr.Checked = false; changeMade = false; }
public HttpResponseMessage Post(Lead request) { //TODO: 7. Write the lead to the DB var result = writeToDB(request); LeadResponse response = new LeadResponse() { LeadId = result.Item1, IsDuplicate = result.Item2, IsSuccessful = result.Item3, IsCapped = result.Item4, Messages = result.Item5.Split(';'), }; Console.WriteLine($"Lead received {request.FirstName} {request.Surname}"); return(Request.CreateResponse(HttpStatusCode.OK, response)); }
public static List<PointF> ECG_Complex__QRST_BBB (Patient _P, Lead _L) { float lerpCoeff = Math.Clamp (Math.InverseLerp (60, 160, _P.HR)), QRS = Math.Lerp (0.12f, 0.22f, 1 - lerpCoeff), QT = Math.Lerp (0.235f, 0.4f, 1 - lerpCoeff); List<PointF> thisBeat = new List<PointF> (); thisBeat = Plotting.Concatenate (thisBeat, ECG_Q (_P, _L, QRS / 6, -0.1f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_R (_P, _L, QRS / 6, 0.9f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_Q (_P, _L, QRS / 6, 0.3f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_R (_P, _L, QRS / 6, 0.7f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_S (_P, _L, QRS / 6, -0.3f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_J (_P, _L, QRS / 6, -0.1f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_ST (_P, _L, ((QT - QRS) * 2) / 5, 0f, Plotting.Last (thisBeat))); thisBeat = Plotting.Concatenate (thisBeat, ECG_T (_P, _L, ((QT - QRS) * 3) / 5, 0.1f, 0f, Plotting.Last (thisBeat))); return thisBeat; }
public bool UpdateLists(Lead data, List <Lists> listsToUpdate, string pagename) { foreach (var list in listsToUpdate) { switch (list) { case Lists.CBR_US_Certified: Update_CBR_US_Certified(data, pagename); break; case Lists.CBR_US_Non_Cert: Update_CBR_US_NonCert(data, pagename); break; } } return(true); }
public async Task <IActionResult> Edit(int id, [Bind("ID, Name, Phone, Email, Comment, Date")] Lead lead) { //Check for leads existance if (id != lead.ID) { return(NotFound()); } //Apply and save Edits if (ModelState.IsValid) { _Context.Update(lead); await _Context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(lead)); }
public bool CreateLead(LeadCreate model) { var entity = new Lead() { Name = model.Name, Company = model.Company, Phone = model.Phone, Email = model.Email, Converted = model.Converted }; using (var ctx = new ApplicationDbContext()) { ctx.Leads.Add(entity); return(ctx.SaveChanges() == 1); } }
public void ImportFromStubImportsStubAndCreatesContact() { DatabaseWebCampaign webCampaign = CreateWebCampaign(_campaign, new List <string>() { "emailaddress1", "mobilephone" }); webCampaign.Insert(Connection); DatabaseStub stub = CreateStub(webCampaign); string emailaddress1 = $"emailaddress1 {Guid.NewGuid()}"; stub.Contents.Add(new DatabaseStubElement() { Key = "emailaddress1", Value = emailaddress1 }); DatabaseStubPusher.GetInstance(Connection).Push(stub); DatabaseImportFromStub databaseImportFromStub = CreateDatabaseImportStub(webCampaign); ImportFromStub importFromStub = new ImportFromStub(Connection, databaseImportFromStub); importFromStub.ExecuteOption(new Administration.Option.Options.OptionReport(typeof(ImportFromStubTest))); Lead lead = Lead.ReadFromFetchXml(DynamicsCrmConnection, new List <string>() { "emailaddress1" }, new Dictionary <string, string>() { { "emailaddress1", emailaddress1 } }).Single(); lead.Delete(); Contact contact = Contact.ReadFromFetchXml(DynamicsCrmConnection, new List <string>() { "emailaddress1" }, new Dictionary <string, string>() { { "emailaddress1", emailaddress1 } }).Single(); contact.Delete(); }
public async Task <ActionResult> Filter(LeadListingViewModel leadListingModel) { var lead = new Lead(); var model = new LeadListingViewModel(); try { DateTime?nextFollowUpFromDate = leadListingModel.NextFollowUpFrom; DateTime?nextFollowUpToDate = leadListingModel.NextFollowUpTo; decimal? expectedValueFrom = leadListingModel.ExpectedValueFrom; decimal? expectedValueTo = leadListingModel.ExpectedValueTo; int? status = leadListingModel.Status; int? leadOwner = leadListingModel.LeadOwner; IEnumerable <Contact> spaceUsers = await lead.GetUsers(); Dictionary <int, string> statuses = await lead.GetAllStatuses(); IEnumerable <Lead> leads = await lead.GetAllLeads(nextFollowUpFromDate, nextFollowUpToDate, expectedValueFrom, expectedValueTo, status, leadOwner); model.LeadOwnersOptions = new SelectList(spaceUsers, "ProfileId", "Name", leadOwner); model.StatusOptions = new SelectList(statuses, "Key", "Value", status); if (leads.Any()) { model.Leads = leads.Select(x => new LeadView { Company = x.Company, LeadOwners = x.LeadOwners, ExpectedValue = x.ExpectedValue, Status = x.Status, NextFollowUp = x.NextFollowUp, PodioItemID = x.PodioItemID }); } } catch (PodioException ex) { ViewBag.error = ex.Error.ErrorDescription; } return(View("Index", model)); }
public void When_ordering_by_entity_reference_fields_ascending_expected_result_is_returned() { using (var context = new Xrm(orgAdminService)) { var lead1 = new Lead { LastName = "Jordi" }; lead1.Id = orgAdminService.Create(lead1); var lead2 = new Lead { LastName = "Skuba" }; lead2.Id = orgAdminService.Create(lead2); var contact1 = new Contact { FirstName = "Fred", LastName = "Bloggs", OriginatingLeadId = lead1.ToEntityReference() }; contact1.Id = orgAdminService.Create(contact1); var contact2 = new Contact { FirstName = "Jo", LastName = "Bloggs", OriginatingLeadId = lead2.ToEntityReference() }; contact2.Id = orgAdminService.Create(contact2); QueryExpression qry = new QueryExpression(Contact.EntityLogicalName) { ColumnSet = new ColumnSet(true) }; qry.AddOrder("originatingleadid", OrderType.Ascending); var results = orgAdminService.RetrieveMultiple(qry); var firstResultValue = (results.Entities[0] as Contact).OriginatingLeadId; Assert.Equal("Jordi", firstResultValue.Name); } }
private static Lead populateLeadFromDB(Npgsql.NpgsqlDataReader dr) { Lead newUser = new Lead(); newUser.LeadId = Helper.ConvertFromDBVal <int>(dr[0]); newUser.CompanyName = dr[1].ToString(); newUser.Contact1Title = dr[2].ToString(); newUser.Contact1FirstName = dr[3].ToString(); newUser.Contact2Title = dr[4].ToString(); newUser.Contact2FirstName = dr[5].ToString(); newUser.PrimaryPhoneNumber = dr[6].ToString(); newUser.AddtionalPhoneNumber = dr[7].ToString(); newUser.NumberToCall = Helper.ConvertFromDBVal <int>(dr[8]); newUser.FaxNumber = dr[9].ToString(); newUser.PrimaryEmailAddress = dr[10].ToString(); newUser.AdditonalEmailAddress = dr[11].ToString(); newUser.WebsiteLink = dr[12].ToString(); newUser.StreetAddress1 = dr[13].ToString(); newUser.StreetAddress2 = dr[14].ToString(); newUser.City = dr[15].ToString(); newUser.State = dr[16].ToString(); newUser.ZipCode = dr[17].ToString(); newUser.ZoneNumber = Helper.ConvertFromDBVal <int>(dr[18]); newUser.Status = dr[19].ToString(); newUser.AssignedSAUserId = Helper.ConvertFromDBVal <int>(dr[20]); newUser.CallbackDate = Helper.ConvertFromDBVal <DateTime>(dr[21]); newUser.IgnoredDate = Helper.DateConvertFromDBVal <DateTime>(dr[22]); newUser.AssignedAAUserId = Helper.ConvertFromDBVal <int>(dr[23]); newUser.Contact1LastName = dr[24].ToString(); newUser.Contact2LastName = dr[25].ToString(); newUser.Suppressed = Helper.ConvertFromDBVal <Boolean>(dr[26]); newUser.Ignored = Helper.ConvertFromDBVal <Boolean>(dr[27]); newUser.DateTimeImported = Helper.ConvertFromDBVal <DateTime>(dr[28]); newUser.Reassigned = Helper.ConvertFromDBVal <Boolean>(dr[29]); newUser.PrimaryPhoneChecked = Helper.ConvertFromDBVal <Boolean>(dr[30]); PGUploadedfileRepository upFile = new PGUploadedfileRepository(); //newUser.StatementFile = upFile.UploadedFiles.Single(row => row.leadID == newUser.LeadId); newUser.StatementFiles.AddRange(upFile.GetFileByLeadId(newUser.LeadId)); return(newUser); }
public void ReturnDefenitionWithOkDataForEmailContact() { var accessTokenProvider = new Mock <IAccessTokenProvider>(); var userId = 1; var contactProperty = new LeadProperty() { LeadId = 1, Type = "FromEmail", Value = "*****@*****.**" }; var contactProperty2 = new LeadProperty() { LeadId = 1, Type = "Subject", Value = "Email Subject" }; var contact = new Lead() { Id = 1, ClientId = 1, LeadType = "Email", Date = new DateTime(2014, 1, 1, 12, 30, 00) }; contact.Property.Add(contactProperty); contact.Property.Add(contactProperty2); var controller = new ContactDefenitionBuilder(accessTokenProvider.Object); accessTokenProvider.Setup(at => at.GenerateAccessUrl(userId, "/report/mail?clientId=" + contact.ClientId)) .Returns("Some Url With Access Token and Return Url"); var result = controller.GetContact(userId, contact); Assert.AreEqual("Email", result.Type); Assert.AreEqual("2014-01-01 12:30", result.Date); Assert.AreEqual("nyyt email", result.DisplayName); Assert.AreEqual("Email Subject", result.SubjectOrDuration); Assert.AreEqual("Subjekt", result.SubjectOrDurationDisplayName); Assert.AreEqual("*****@*****.**", result.From); Assert.AreEqual("Du har fått ett nyyt email från [email protected]. <a href=Some Url With Access Token and Return Url style=\"color: #009dd2;\">Visa</a>" + " eller <a href=Some Url With Access Token and Return Url style=\"color: #009dd2;\">Betygsätt</a> direkt!", result.Description); }
public void ReturnDefenitionWithOkDataForPhoneContact() { var accessTokenProvider = new Mock <IAccessTokenProvider>(); var userId = 1; var contactProperty = new LeadProperty() { LeadId = 1, Type = "Duration", Value = "90" }; var contactProperty2 = new LeadProperty() { LeadId = 1, Type = "CallerNumber", Value = "08123456" }; var contact = new Lead() { Id = 1, ClientId = 1, LeadType = "Phone", Date = new DateTime(2014, 1, 1, 12, 30, 00) }; contact.Property.Add(contactProperty); contact.Property.Add(contactProperty2); var controller = new ContactDefenitionBuilder(accessTokenProvider.Object); accessTokenProvider.Setup(at => at.GenerateAccessUrl(userId, "/report/phone?clientId=" + contact.ClientId)) .Returns("Some Url With Access Token and Return Url"); var result = controller.GetContact(userId, contact); Assert.AreEqual("Phone", result.Type); Assert.AreEqual("2014-01-01 12:30", result.Date); Assert.AreEqual("nyyt telefonsamtal", result.DisplayName); Assert.AreEqual("1:30", result.SubjectOrDuration); Assert.AreEqual("Samtalslängd", result.SubjectOrDurationDisplayName); Assert.AreEqual("08123456", result.From); Assert.AreEqual("Du har fått ett nyyt telefonsamtal från 08123456. <a href=Some Url With Access Token and Return Url style=\"color: #009dd2;\">Lyssna</a> " + "eller <a href=Some Url With Access Token and Return Url style=\"color: #009dd2;\">Betygsätt</a> direkt!", result.Description); }
public void Insert(Lead lead) { var max = GetAll().Max(x => x.Id) + 1; lead.Id = max; new SqlConnection(_connectionString).Insert(new SqlLeadDto { id = lead.Id, costumer_name = lead.CustomerName, costumer_phone = lead.CustomerPhone, region = lead.Region, sity = lead.Sity, street = lead.Street, house = lead.House, flat = lead.Flat, agreed = lead.Agreed, payed = lead.Payed, delivered = lead.Delivered, creating_date = lead.CreatingDate, delivery_date = lead.DeliveryDate, delivery_method = lead.DeliveryMethod, pay_method = lead.PayMethod, comment = lead.Comment, costumer_id = lead.Id, full_price = lead.FullPrice }); foreach (var dto in new SqlConnection(_connectionString).Query <SqlGoodLeadRelDto>( "SELECT * FROM LeadPenRel").Where(x => x.lead_id == lead.Id)) { new SqlConnection(_connectionString).Delete(dto); } foreach (var good in lead.Goods) { new SqlConnection(_connectionString).Insert(new SqlGoodLeadRelDto() { count = good.Count, engraving = good.Engraving, pen_id = good.GoodId, lead_id = lead.Id }); } }
public override Campaign Update(Guid id, Campaign campaign) { Campaign foundCampaign = CrmContext.Campaigns .Include(c => c.Infos) .Single(c => c.Id == campaign.Id); foundCampaign.Infos.Clear(); foundCampaign.Name = campaign.Name; foundCampaign.Description = campaign.Description; foundCampaign.Filter = campaign.Filter; var customerStatus = UnitOfWork.GetRepository <LeadStatusMaster>() .GetList(x => x.Name == "Customer") .Items.SingleOrDefault(); //currently we have support to parse multiple subDistrictIds with comma separator. string[] strSubDistrictIds = campaign.Filter.Split(','); for (int si = 0; si < strSubDistrictIds.Length; si++) { Guid?find = Guid.Parse(strSubDistrictIds[si]); var result = CrmContext.Leads .Where(x => x.Contact.ContactAddress.SubDistrictId == find) .ToArray(); for (int i = 0; i < result.Length; i++) { Lead lead = result[i]; CampaignInfo campaignInfo = new CampaignInfo(); campaignInfo.Id = Guid.NewGuid(); campaignInfo.IsInProgress = false; campaignInfo.LeadId = result[i].Id; foundCampaign.Infos.Add(campaignInfo); } } CrmContext.SaveChanges(); return(foundCampaign); }
public async Task CreateLead(LeadCreateModel leadModel) { if (!this.db.Leads.Any(a => a.Id == leadModel.Id)) { var lead = new Lead() { Name = leadModel.Name, PinCode = leadModel.PinCode, SubArea = leadModel.SubArea, Address = leadModel.Address, MobileNumber = leadModel.MobileNumber, Email = leadModel.Email }; await this.db.Leads.AddAsync(lead); await this.db.SaveChangesAsync(); } }
public async Task <IHttpActionResult> PostLead(Lead lead) { DataTransfer curUser = await GetCurrentUserInfo(); User user = userCrud.Table.First(u => u.Email == curUser.userName); lead.UserId = user.UserId; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } leadCrud.Insert(lead); return(CreatedAtRoute("DefaultApi", new { id = lead.LeadId }, lead)); }
public void SetUp() { _sut = new Lead("FakeToken", "FakeIdentificador", "FakeEmail") { Nome = "Value", Cargo = "Value", Telefone = "Value", Celular = "Value", Empresa = "Value", Estado = "Value", Cidade = "Value", Website = "Value", Twitter = "Value", CUtmz = "Value", TrafficSource = "Value", Tags = "Value", CreatedAt = DateTime.Today }; }
public ExpertNotificationEmailTemplate(Lead lead, int timeZoneOffset = 0) { _vehicleImgUrl = lead.CarImageUrl; _vdpUrl = lead.VdpUrl; _VIN = lead.CarVin; _customerFirstName = lead.FirstName; _customerLastName = lead.SecondName; _customerPhone = lead.UserPhone; _customerEmail = lead.UserEmail; _customerComment = lead.UserComment; _bookingDateTime = lead.BookingDateTimeUtc; _timeZoneOffset = timeZoneOffset; _vehicleTitle = lead.CarTitle; _expertName = (lead.Expert != null) ? lead.Expert.Name : "Skipped by customer"; _beverageName = (lead.Beverage != null) ? lead.Beverage.Name : "Skipped by customer"; _roadName = (lead.Route != null) ? lead.Route.Name : "Skipped by customer"; _locationType = lead.LocationType; _locationAddress = lead.LocationAddress; }
public ActionResult AssignAppointment(string text, string id) { string[] ids = id.Split(','); string[] names = text.Split(','); AppointmentSheet appointment; User user = _UsageRepository.GetUserIDByName(names[0], names[1]); foreach (string appointmentid in ids) { int aid = int.Parse(appointmentid); appointment = _AppointmentRepos.GetAppointmentByAppointmentId(aid); Lead lead = _LeadRepos.LeadByLeadID(appointment.ParentLeadId); _UsageRepository.SaveAssignedSALeads(lead, user.UserId); _UsageRepository.SaveAssignedAppointments(appointment, user.UserId); // need ref id to appoint parent_user_integer string EventReferencingId = appointment.Event_Reference; Web.ViewModel.CalendarEventViewModel cevm = new Web.ViewModel.CalendarEventViewModel(); CalendarEvent events = new CalendarEvent(); events = _EventsRepository.GetEventByAppointmentID(EventReferencingId); events.Parent_Appointment_Id = appointment.AppointmentSheetId; events.Parent_User_Id = user.UserId; events.appointment = true; events.street = appointment.Street; events.city = appointment.City; events.state = appointment.State; events.zipcode = appointment.ZipCode; events.description = ""; events.creator = appointment.CreatorId; events.assigned = appointment.AssignedSalesAgent; cevm.calendarEvent = events; _EventsRepository.SaveCalendarEvent(cevm.calendarEvent); } //return RedirectToAction("Index", "ImportLead"); return(Redirect("/AppointmentQueue/Index")); }
private void SendLead() { UTF8Encoding leadConvertor = new UTF8Encoding(); byte[] le1 = leadConvertor.GetBytes(this.getLeadName.Text); string name = leadConvertor.GetString(le1); byte[] le2 = leadConvertor.GetBytes(this.getLeadTitle.Text); string title = leadConvertor.GetString(le1); byte[] le3 = leadConvertor.GetBytes(this.getLeadBody.Text); string body = leadConvertor.GetString(le1); try { Lead l = new Lead() { LeadBody = body, LeadDate = TimeNow.TheTimeNow, LeadID = this.Master._CoachingDal.GetNextAvailableID("lead"), LeadMail = this.getLeadMail.Text, LeadName = name, LeadTitle = title, spLeadDate = TimeNow.TheTimeNow.ToShortDateString() }; this.Master._CoachingDal.Add("lead", l, TimeNow.TheTimeNow); this.Master._Logger.Log(new AdminException(". Lead " + title + "Was Successfully Received"), MethodBase.GetCurrentMethod().Name); this.leadLabel.ForeColor = Color.Blue; this.leadLabel.Text = "ההודעה נשלחה בהצלחה"; } catch (Exception e) { this.Master._Logger.Error(e, MethodBase.GetCurrentMethod().Name); this.leadLabel.ForeColor = Color.Red; this.leadLabel.Text = "אנא נס/י לשלוח שוב"; } finally { this.ClearFields(1); } }
public Lead UpdateLead(Lead objLead) { try { objLead.updateDate = DateTime.Now; using (var context = new FitnessCenterEntities()) { context.Leads.Attach(context.Leads.Single(varL => varL.ID == objLead.ID)); context.Leads.ApplyCurrentValues(objLead); context.SaveChanges(); return(objLead); } } catch (Exception ex) { throw ex; } }
public async Task <IHttpActionResult> PutLead(int id, Lead lead) { // get cur user info DataTransfer curUser = await GetCurrentUserInfo(); User user = userCrud.Table.First(u => u.Email == curUser.userName); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != lead.LeadId) { return(BadRequest("Editing the wrong lead")); } if (user.UserId != lead.UserId) { return(BadRequest("User did not create lead")); } leadCrud.Update(lead); try { leadCrud.Save(); } catch (DbUpdateConcurrencyException) { if (!LeadExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <ActionResult> Create([Bind(Include = "Id,CustomerName,FirmName,ContactNo,EmailId,City,State,EnquiryDate,Comments,CreatedOn,CreatedBy,ModifiedOn,ModifiedBy,EnquiryTypeId,CustomerProfileId,SalesTeamId,EventId,ApplicationId,UserId,AdvertisementId,IsUrgent,IsQualify,IsDisQualify,IsDeactivate")] Lead lead) { if (ModelState.IsValid) { db.Leads.Add(lead); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.EnquiryTypeId = new SelectList(db.EnquiryTypes, "Id", "Name", lead.EnquiryTypeId); ViewBag.CustomerProfileId = new SelectList(db.CustomerProfiles, "Id", "Name", lead.CustomerProfileId); ViewBag.SalesTeamId = new SelectList(db.SalesTeams, "Id", "Name", lead.SalesTeamId); ViewBag.EventId = new SelectList(db.Events, "Id", "Name", lead.EventId); ViewBag.ApplicationId = new SelectList(db.Applications, "Id", "Name", lead.ApplicationId); ViewBag.UserId = new SelectList(db.Users, "Id", "Name", lead.UserId); ViewBag.AdvertisementId = new SelectList(db.Advertisements, "Id", "Name", lead.AdvertisementId); return(View(lead)); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a unique identifier for this sample for preventing name conflicts. var sampleIdentifier = Guid.NewGuid(); // Retrieve/create the system users to use for the sample. var ldapPath = String.Empty; _systemUserIds = SystemUserProvider.RetrieveDelegates( _serviceProxy, ref ldapPath); // Retrieve the root business unit to use for creating the team for the // sample. var businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; businessUnitQuery.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery); var businessUnit = businessUnitResult.Entities[0].ToEntity<BusinessUnit>(); // Get the GUID of the current user. var who = new WhoAmIRequest(); var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who); _currentUserId = whoResponse.UserId; // Create a team for use in the sample. var team = new Team { AdministratorId = new EntityReference( "systemuser", _currentUserId), Name = String.Format("User Access Sample Team {0}", sampleIdentifier), BusinessUnitId = businessUnit.ToEntityReference() }; _teamId = _serviceProxy.Create(team); // Add the second user to the newly created team. var addToTeamRequest = new AddMembersTeamRequest { TeamId = _teamId, MemberIds = new[] { _systemUserIds[1] } }; _serviceProxy.Execute(addToTeamRequest); // Create a lead for use in the sample. var lead = new Lead { CompanyName = "User Access Sample Company", FirstName = "Sample", LastName = "Lead", Subject = "User Access Sample Lead", }; _leadId = _serviceProxy.Create(lead); // Create a task to associate to the lead. var leadReference = new EntityReference(Lead.EntityLogicalName, _leadId); var task = new Task { Subject = "User Access Sample Task", RegardingObjectId = leadReference }; _taskId = _serviceProxy.Create(task); // Create a letter to associate to the lead. var letter = new Letter { Subject = "User Access Sample Letter", RegardingObjectId = leadReference }; _serviceProxy.Create(letter); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a Lead record on which we will execute the Workflow. Lead lead = new Lead() { FirstName = "Diogo", LastName = "Andrade" }; _leadId = _serviceProxy.Create(lead); Console.WriteLine("Created Lead for workflow request."); // Define an anonymous type to define the possible values for // process type var ProcessType = new { Definition = 1, Activation = 2, Template = 3 }; // Define an anonymous type to define the possible values for // process category var ProcessCategory = new { Workflow = 0, Dialog = 1, }; // Define an anonymous type to define the possible values for // process scope var ProcessScope = new { User = 1, BusinessUnit = 2, Deep = 3, Global = 4 }; // Create the Workflow that we will execute. Workflow workflow = new Workflow() { Name = "Sample Workflow", // friendly name of the record Type = new OptionSetValue(ProcessType.Definition), Category = new OptionSetValue(ProcessCategory.Workflow), Scope = new OptionSetValue(ProcessScope.User), OnDemand = true, PrimaryEntity = Lead.EntityLogicalName, Xaml = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""ExecuteWorkflowSample"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:ExecuteWorkflowSample.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:ExecuteWorkflowSample.InputEntities> <this:ExecuteWorkflowSample.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:ExecuteWorkflowSample.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" Value=""[New Entity("phonecall")]"" /> <Sequence DisplayName=""CreateStep1: Set first activity for lead.""> <Sequence.Variables> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_3"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_4"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_5"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_6"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_7"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_8"" /> </Sequence.Variables> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.Boolean, ""True"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""directioncode"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_1]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""First call to "", ""String"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_3]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:GetEntityProperty Attribute=""fullname"" Entity=""[InputEntities("primaryEntity")]"" EntityName=""lead"" Value=""[CreateStep1_5]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_5 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_4]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_3, CreateStep1_4 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""subject"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_2]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""leadid"" Entity=""[InputEntities("primaryEntity")]"" EntityName=""lead"" Value=""[CreateStep1_7]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_7 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_6]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""regardingobjectid"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_6]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.OptionSetValue, ""1"", ""Picklist"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_8]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""prioritycode"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_8]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1: Set first activity for lead."" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities("CreateStep1_localParameter")]"" Value=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>" }; _workflowId = _serviceProxy.Create(workflow); Console.Write("Created workflow to call in Execute Workflow request, "); SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue(2) }; _serviceProxy.Execute(setStateRequest); Console.WriteLine("and activated."); }
/// <summary> /// /// </summary> /// /// <param name="lead"></param> /// <param name="callback"></param> /// <param name="asyncState"></param> /// /// <returns></returns> /// public IAsyncResult BeginAllocate(Lead lead, AsyncCallback callback, object asyncState) { return BeginOperation(lead, callback, asyncState, DoBeginAllocate); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a phone call is created to a contact regarding a lead. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetWorkingWithRelatedAttributesforNto1Relationships1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Create a lead. Lead lead = new Lead() { CompanyName = "Litware, Inc." }; _leadId = _service.Create(lead); Console.Write("Lead created, "); // Create a contact. Contact contact = new Contact() { FirstName = "Dan", LastName = "Park", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**" }; _contactId = _service.Create(contact); contact.ContactId = _contactId; Console.Write("contact created, "); // Create a blank phone call. PhoneCall phoneCall = new PhoneCall(); _phoneCallId = _service.Create(phoneCall); Console.Write("phone call created, "); // Create an ActivityParty for the phone call's "to" field. ActivityParty activityParty = new ActivityParty() { PartyId = new EntityReference { Id = _contactId, LogicalName = Contact.EntityLogicalName, }, ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create a phone call and add the properties we are updating. PhoneCall updatePhoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Test Phone Call", RegardingObjectId = new EntityReference { Id = _leadId, LogicalName = Lead.EntityLogicalName }, To = new ActivityParty[] { activityParty } }; // Update the phone call. UpdateRequest updateRequest = new UpdateRequest() { Target = updatePhoneCall }; _service.Execute(updateRequest); Console.Write("phone call updated.\n"); DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithRelatedAttributesforNto1Relationships1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
//<snippetRetrieveRecordWall> private void DisplayRecordWall(Lead lead) { // Display the first page of the record wall. var retrieveRecordWallReq = new RetrieveRecordWallRequest { Entity = lead.ToEntityReference(), CommentsPerPost = 2, PageSize = 10, PageNumber = 1 }; var retrieveRecordWallRes = (RetrieveRecordWallResponse)_serviceProxy.Execute(retrieveRecordWallReq); Console.WriteLine("\r\n Posts for lead {0}:", lead.FullName); foreach (Post post in retrieveRecordWallRes.EntityCollection.Entities) { DisplayPost(post); } }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = _serviceProxy.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = _serviceProxy.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); //<snippetWorkingWithLeads1> // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); //</snippetWorkingWithLeads1> foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = _serviceProxy.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRecords(promptforDelete); } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { Contact contact1 = new Contact { FirstName = "Colin", LastName = "Wilcox", Address1_City = "Redmond", Address1_StateOrProvince = "WA", Address1_PostalCode = "98052", Anniversary = new DateTime(2010, 3, 5), CreditLimit = new Money(300), Description = "Alpine Ski House", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(1), NumberOfChildren = 1, Address1_Latitude = 47.6741667, Address1_Longitude = -122.1202778, CreditOnHold = false }; _contactId1 = _serviceProxy.Create(contact1); Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName); Contact contact2 = new Contact { FirstName = "Brian", LastName = "Smith", Address1_City = "Bellevue", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98008", Anniversary = new DateTime(2010, 4, 5), CreditLimit = new Money(30000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = false }; _contactId2 = _serviceProxy.Create(contact2); Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName); Contact contact3 = new Contact { FirstName = "Darren", LastName = "Parker", Address1_City = "Kirkland", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98033", Anniversary = new DateTime(2010, 10, 5), CreditLimit = new Money(10000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = false }; _contactId3 = _serviceProxy.Create(contact3); Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName); Contact contact4 = new Contact { FirstName = "Ben", LastName = "Smith", Address1_City = "Kirkland", FamilyStatusCode = new OptionSetValue(3), Address1_StateOrProvince = "WA", Address1_PostalCode = "98033", Anniversary = new DateTime(2010, 7, 5), CreditLimit = new Money(12000), Description = "Coho Winery", StatusCode = new OptionSetValue(1), AccountRoleCode = new OptionSetValue(2), NumberOfChildren = 2, Address1_Latitude = 47.6105556, Address1_Longitude = -122.1994444, CreditOnHold = true }; _contactId4 = _serviceProxy.Create(contact4); Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName); Incident incident1 = new Incident { Title = "Test Case 1", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem Description = "Description for Test Case 1.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId2) }; _incidentId1 = _serviceProxy.Create(incident1); Console.Write("Created a sample incident 1: {0}, ", incident1.Title); Relationship relationship1 = new Relationship("incident_customer_contacts"); EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection(); relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1)); _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1); Console.Write("Added relationship between incident 1 and contact 1, "); Account account1 = new Account { Name = "Coho Winery", Address1_Name = "Coho Vineyard & Winery", Address1_City = "Redmond" }; _accountId1 = _serviceProxy.Create(account1); Console.Write("Created a sample account 1: {0}, ", account1.Name); Incident incident2 = new Incident { Title = "Test Case 2", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem Description = "Description for Sample Case 2.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId1) }; _incidentId2 = _serviceProxy.Create(incident2); Console.Write("Created a sample incident 2: {0}, ", incident2.Title); Relationship relationship2 = new Relationship("incident_customer_accounts"); EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection(); relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1)); _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2); Console.Write("Added relationship between incident 2 and account 1, "); Lead lead = new Lead() { FirstName = "Diogo", LastName = "Andrade" }; _leadId = _serviceProxy.Create(lead); Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName); Account account2 = new Account { Name = "Contoso Ltd", ParentAccountId = new EntityReference(Account.EntityLogicalName, _accountId1), Address1_Name = "Contoso Pharmaceuticals", Address1_City = "Redmond", OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId) }; _accountId2 = _serviceProxy.Create(account2); Console.Write("Created a sample account 2: {0}, ", account2.Name); Relationship relationship3 = new Relationship("account_primary_contact"); EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection(); relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2)); _serviceProxy.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3); Console.WriteLine("Added relationship between account 2 and contact 2."); }
public void When_doing_a_crm_linq_query_with_a_2_innerjoins_right_result_is_returned() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var contactId = Guid.NewGuid(); var accountId = Guid.NewGuid(); var accountId2 = Guid.NewGuid(); var lead = new Lead() { Id = Guid.NewGuid() }; //Contact is related to first account, but because first account is not related to itself then the query must return 0 records fakedContext.Initialize(new List<Entity>() { lead, new Account() { Id = accountId , Name = "Testing" }, new Account() { Id = accountId2, ParentAccountId = new EntityReference(Account.EntityLogicalName, accountId), PrimaryContactId = new EntityReference(Contact.EntityLogicalName, contactId) }, new Contact() { Id = contactId, NumberOfChildren = 2, OriginatingLeadId = lead.ToEntityReference()} }); var service = fakedContext.GetFakedOrganizationService(); using (XrmServiceContext ctx = new XrmServiceContext(service)) { //var matches = (from c in ctx.ContactSet // join a in ctx.AccountSet on c.ContactId equals a.PrimaryContactId.Id // join a2 in ctx.AccountSet on a.ParentAccountId.Id equals a2.AccountId // where c.NumberOfChildren == 2 // where a2.Name == "Testing" // select a2.Name).ToList(); var matches = (from a in ctx.AccountSet join c in ctx.ContactSet on a.PrimaryContactId.Id equals c.ContactId join l in ctx.LeadSet on c.OriginatingLeadId.Id equals l.LeadId select a).ToList(); Assert.True(matches.Count == 1); } }
/// <summary> /// /// </summary> /// /// <param name="lead"></param> /// <param name="callback"></param> /// <param name="asyncState"></param> /// <param name="waitCallback"></param> /// /// <returns></returns> /// private IAsyncResult BeginOperation(Lead lead, AsyncCallback callback, object asyncState, WaitCallback waitCallback) { AsyncResult<ExchangeDisposition> result = new AsyncResult<ExchangeDisposition>(callback, asyncState); AsyncOperation<Lead, AsyncResult<ExchangeDisposition>> operation = new AsyncOperation<Lead, AsyncResult<ExchangeDisposition>>(lead, result); ThreadPool.QueueUserWorkItem(waitCallback, operation); return result; }
/// <summary> /// /// </summary> /// /// <param name="lead"></param> /// /// <returns></returns> /// public ExchangeDisposition Allocate(Lead lead) { lock (gateways) { foreach (IPartnerGateway gateway in gateways) { gateway.BeginPost(lead, ReduceCallback, this); } } signal.WaitOne(timout, false); ExchangeDisposition allocation = new ExchangeDisposition(); allocation.Coverage = false; allocation.Responses = results; foreach (PartnerGatewayResponse response in results) { if (response.Coverage) { allocation.Coverage = true; break; } } return allocation; }
public LeadDto[] Map(Lead[] entities) { return entities.Select(Map).ToArray(); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { _initialAccount = new Account() { Name = "Contoso, Ltd" }; _initialAccount.Id = _serviceProxy.Create(_initialAccount); Console.WriteLine(" Created initial Account (Name={0})", _initialAccount.Name); _initialLead = new Lead() { Subject = "A Sample Lead", LastName = "Wilcox", FirstName = "Colin", }; _initialLead.Id = _serviceProxy.Create(_initialLead); Console.WriteLine(" Created initial Lead (Subject={0}, Name={1} {2})", _initialLead.Subject, _initialLead.FirstName, _initialLead.LastName); }
public void leadUpdate(Microsoft.Crm.Sdk.Samples.ServerConnection.Configuration serverconfig, ArrayList data) { try { using (_serviceProxy = Microsoft.Crm.Sdk.Samples.ServerConnection.GetOrganizationProxy(serverconfig)) { String a_id = (String)data[0]; Guid _leadId = new Guid(a_id); _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; Lead leadToUpdate = new Lead { FirstName = (String)data[1], EMailAddress1 = (String)data[2], Address1_City = (String)data[3], Address1_Country = (String)data[4], Address1_Latitude = Convert.ToDouble(data[5]), Address1_Longitude = Convert.ToDouble(data[6]), LeadId = _leadId }; _service.Update(leadToUpdate); } } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { throw; } }
public ActionResult Add(Lead lead, FormCollection form) { bool isNew = false; //write activity to the log if (lead.ID == 0) { isNew = true; lead.Status = LeadType.New; } if (!string.IsNullOrEmpty(form["Companies"])) { lead.CompanyID = System.Convert.ToInt32(form["Companies"]); // make sure we clear the company name reference if association already exists lead.CompanyName = string.Empty; } if (!string.IsNullOrEmpty(form["PriorityType"])) { lead.Priority = (PriorityType)Enum.Parse(typeof(CrumbCRM.PriorityType), form["PriorityType"], true); } if (!string.IsNullOrEmpty(form["Campaigns"])) lead.CampaignID = System.Convert.ToInt32(form["Campaigns"]); else if(!string.IsNullOrEmpty(form["CampaignName"])) { var campaign = new Campaign() { CreatedByID = _membershipService.GetCurrentMember().UserId, CreatedDate = DateTime.Now, Name = form["CampaignName"], Description = "" }; lead.CampaignID = _campaignService.Save(campaign); } lead.OwnerID = _membershipService.GetCurrentMember().UserId; _leadService.Save(lead); if (!string.IsNullOrEmpty(form["TagSelector"])) { var current = _tagService.GetByArea(AreaType.Lead); string[] tags = form["TagSelector"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); tags.ToList().ForEach(t => { var tag = _tagService.GetByName(t); if(tag == null) { tag = new Tag() { Name = t.ToLower(), CreatedDate = DateTime.Now, CreatedByID = _membershipService.GetCurrentMember().UserId }; _tagService.Save(tag); } if(!current.Contains(tag)) _leadService.AssignTag(lead, tag); }); } if (isNew) _activityService.Create("was added", AreaType.Lead, User.Identity.Name, lead.ID); TempData.Add("StatusMessage", "Lead added"); return RedirectToAction("Index"); }
private static int? SubmitOutcomeFromNewCall(CallOutcomeSubmission _los, CallOutcomeContext _context, int _callOutcomeID, int? _outcomeID) { // _los.eventLog.WriteEntry("CallOutcomeSubmission.SubmitOutcomeFromNewCall: Entered method"); var _call = (from co in _context.T_MollyMaidCallOutcome join ca in _context.T_Call on co.CallID equals ca.CallID join cn in _context.T_CallNeed on ca.CallID equals cn.CallID // new { _callID = ca.CallID, _needID = ca.NeedID } equals // new { _callID = cn.CallID, _needID = cn.NeedID } join cp in _context.T_Company on ca.CompanyID equals cp.CompanyID join tln in _context.T_L_Need on ca.NeedID equals tln.NeedID join tlo in _context.T_L_Outcome on ca.OutcomeID equals tlo.OutcomeID join tlnf in _context.T_L_NeedField on cn.NeedFieldID equals tlnf.NeedFieldID where co.CallOutcomeID == _callOutcomeID && cn.NeedID == ca.NeedID select new { co.MollyMaidLeadActionID, co.LeadAction, ca.NeedID, cp.FranchiseID, tln.Need, tlo.Outcome, tlnf.FieldName, cn.Visible, cn.ValueData }).ToList(); Lead _lead = new Lead(); _lead.FranNum = int.Parse(_call.FirstOrDefault().FranchiseID); LeadAction leadAction = new LeadAction(); leadAction.ActionDate = DateTime.Now; leadAction.ActionType = ACTION_TYPE_CALL_ATTEMPT; switch (_outcomeID) { case 36: // Sale leadAction.Notes = "New Inbound Call: Scheduled Appointment for " + (_call.Any(a => a.FieldName.Equals("AppointmentDateAndTime") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.Where(a => a.FieldName.Equals("AppointmentDateAndTime") && a.Visible).Single().ValueData.ToString() : "<Appointment data not found>"); // if null check is false, set to empty string; break; case 37: // No Sale leadAction.Notes = "New Inbound Call: No appointment scheduled - " + (_call.Any(a => a.FieldName.Equals("DetailedOutcome") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.Where(a => a.FieldName.Equals("DetailedOutcome") && a.Visible).Single().ValueData.ToString() : "<Detailed Outcome data not found>"); // if null check is false, set to empty string; break; default: leadAction.Notes = "New Inbound Call: Unknown Outcome"; break; } // set up the lead detail LeadDetail _detail = new LeadDetail(); _detail.LeadDate = DateTime.Now; string[] _nameParts = _call.Any(a => a.FieldName.Equals("Name") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.Single(a => a.FieldName.Equals("Name") && a.Visible).ValueData.ToString().Split(' ') : new string[]{"<First Name not found>", "<Last name not found>"}; _detail.FirstName = String.IsNullOrEmpty(_nameParts[0]) ? "<First Name not found>" : _nameParts[0]; // put any remaining _nameParts into LastName field for (int i = 1; i < _nameParts.Length; i++) { _detail.LastName += _nameParts[i] + " "; } if (String.IsNullOrEmpty(_detail.LastName)) { _detail.LastName = "<Last Name not found>"; } else { _detail.LastName.Trim(); } _detail.Address1 = _call.Any(a => a.FieldName.Equals("Address") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("Address") && a.Visible).ValueData.ToString() : "Value not found"; _detail.City = _call.Any(a => a.FieldName.Equals("City") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("City") && a.Visible).ValueData.ToString() : "Value not found"; _detail.State = _call.Any(a => a.FieldName.Equals("State") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("State") && a.Visible).ValueData.ToString() : "Value not found"; _detail.Zip = _call.Any(a => a.FieldName.Equals("ZipCode") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("ZipCode") && a.Visible).ValueData.ToString() : "Value not found"; _detail.Phone1 = _call.Any(a => a.FieldName.Equals("Phone") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("Phone") && a.Visible).ValueData.ToString() : "Value not found"; _detail.Email = _call.Any(a => a.FieldName.Equals("Email") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("Email") && a.Visible).ValueData.ToString() : "Value not found"; _detail.Frequency = _call.Any(a => a.FieldName.Equals("ServiceFrequency") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? ConvertServiceFrequency(_call.FirstOrDefault(a => a.FieldName.Equals("ServiceFrequency") && a.Visible).ValueData.ToString(), _call.FirstOrDefault().Need.ToString()) : ConvertServiceFrequency("", _call.FirstOrDefault().Need.ToString()); _detail.SquareFeet = _call.Any(a => a.FieldName.Equals("SquareFootage") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("SquareFootage") && a.Visible).ValueData.ToString() : "Value not found"; ; string[] _roomParts = _call.Any(a => a.FieldName.Equals("BedroomsBathroom") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("BedroomsBathroom") && a.Visible).ValueData.ToString().Split('/') : "Value not found/Value Not Found".Split('/'); _detail.Bedrooms = _roomParts[0]; _detail.Bathrooms = _roomParts[1]; _detail.Pets = _call.Any(a => a.FieldName.Equals("Pets") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("Pets") && a.Visible).ValueData.ToString() : "Value not found"; _detail.LeadSource = "Other"; _detail.LeadStatus = "New Lead"; _detail.NextAction = "Initial Contact"; _detail.Comments = _call.Any(a => a.FieldName.Equals("OtherInfo") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call.FirstOrDefault(a => a.FieldName.Equals("OtherInfo") && a.Visible).ValueData.ToString() : ""; _detail.Phone1Type = "Home"; _lead.LeadDetails = _detail; Outcome outcome = new Outcome(); outcome.NeedType = _call.FirstOrDefault().Need.ToString(); outcome.CallOutcome = _call.FirstOrDefault().Outcome.ToString(); try { outcome.CallOutcome = _call.FirstOrDefault().Outcome.ToString(); // ternary check for null outcome.DetailedCallOutcome = _call.Any(a => a.FieldName.Equals("DetailedOutcome") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call // if value is not null .Where(a => a.FieldName.Equals("DetailedOutcome") && a.Visible) .Single().ValueData.ToString() : ""; // if value is null, set to empty string // ternary check for null outcome.AdditionalNotes = _call.Any(a => a.FieldName.Equals("OtherInfo") && a.Visible && !String.IsNullOrEmpty(a.ValueData)) ? _call // if value is not null .Where(a => a.FieldName.Equals("OtherInfo") && a.Visible) .Single().ValueData.ToString() : ""; // if value is null, set to empty string // _los.eventLog.WriteEntry("CallOutcomeSubmission.SubmitFinalOutcome: " + outcome.DetailedCallOutcome + " :: " + outcome.AdditionalNotes); } catch (Exception e) { _los.eventLog.WriteEntry("CallOutcomeSubmission.SubmitFinalOutcome: " + e.Message); } leadAction.Outcome = outcome; _lead.LeadAction = leadAction; leadActionResult = client.SubmitLead(_lead); _los.eventLog.WriteEntry("CallOutcomeSubmission.SubmitFinalOutcome: leadActionResult = " + leadActionResult); return leadActionResult; }
/// <summary> /// /// </summary> /// /// <returns></returns> /// public ExchangeDisposition Allocate(Lead lead) { return Execute(lead); }
public void CreateLead(Lead lead) { leadRepository.Add(lead); SaveLead(); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create 3 contacts. Contact contact = new Contact() { FirstName = "Ben", LastName = "Andrews", EMailAddress1 = "*****@*****.**", Address1_City = "Redmond", Address1_StateOrProvince = "WA" }; Guid benAndrewsContactId = _service.Create(contact); _contactIds.Add(benAndrewsContactId); //Create a task associated with Ben Andrews Task task = new Task() { Subject = "Sample Task", RegardingObjectId = new EntityReference() { LogicalName = Contact.EntityLogicalName, Id = benAndrewsContactId, Name = contact.FullName } }; _taskIds.Add(_service.Create(task)); contact = new Contact() { FirstName = "Colin", LastName = "Wilcox", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA" }; _contactIds.Add(_service.Create(contact)); contact = new Contact() { FirstName = "Ben", LastName = "Smith", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA" }; _contactIds.Add(_service.Create(contact)); // Create 3 leads. Lead lead = new Lead() { FirstName = "Dan", LastName = "Wilson", EMailAddress1 = "*****@*****.**", Address1_City = "Redmond", Address1_StateOrProvince = "WA" }; _leadIds.Add(_service.Create(lead)); lead = new Lead() { FirstName = "Jim", LastName = "Wilson", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA" }; _leadIds.Add(_service.Create(lead)); lead = new Lead() { FirstName = "Denise", LastName = "Smith", EMailAddress1 = "*****@*****.**", Address1_City = "Bellevue", Address1_StateOrProvince = "WA" }; _leadIds.Add(_service.Create(lead)); // Create 5 customized Accounts for the LINQ samples. Account account = new Account { Name = "A. Datum Corporation", Address1_StateOrProvince = "Colorado", Address1_Telephone1 = "(206)555-5555", PrimaryContactId = new EntityReference(Contact.EntityLogicalName, _contactIds[0]) }; _accountIds.Add(_service.Create(account)); account = new Account { Name = "Adventure Works", Address1_StateOrProvince = "Illinois", Address1_County = "Lake County", Address1_Telephone1 = "(206)555-5555", OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadIds[0]) }; _accountIds.Add(_service.Create(account)); account = new Account { Name = "Coho Vineyard", Address1_StateOrProvince = "Washington", Address1_County = "King County", Address1_Telephone1 = "(425)555-5555", PrimaryContactId = new EntityReference(Contact.EntityLogicalName, _contactIds[1]), OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadIds[0]) }; _accountIds.Add(_service.Create(account)); account = new Account { Name = "Fabrikam", Address1_StateOrProvince = "Washington", Address1_Telephone1 = "(425)555-5555", PrimaryContactId = new EntityReference(Contact.EntityLogicalName, _contactIds[0]) }; _accountIds.Add(_service.Create(account)); account = new Account { Name = "Humongous Insurance", Address1_StateOrProvince = "Missouri", Address1_County = "Saint Louis County", Address1_Telephone1 = "(314)555-5555", PrimaryContactId = new EntityReference(Contact.EntityLogicalName, _contactIds[1]) }; _accountIds.Add(_service.Create(account)); // Create 10 basic Account records. for (int i = 1; i <= 10; i++) { account = new Account { Name = "Fourth Coffee " + i, Address1_StateOrProvince = "California" }; _accountIds.Add(_service.Create(account)); } }
public void EditLead(Lead leadToEdit) { leadRepository.Update(leadToEdit); SaveLead(); }
public async Task<bool> Send(LeadConduit.Interface.Models.VehicleProvider vp, Lead lead, ILog log) { bool result = false; string jsonLead = JsonConvert.SerializeObject(lead); AccessorResponse<InventoryItem> GIAccessorResponse = GlobalInventoryAccessor.Inventory.Retrieve((int)lead.GlobalInventoryId, lead.GlobalInventorySourceId); ParameterData parameterData = JsonSerializer.CreateDefault().Deserialize<ParameterData>(new JsonTextReader(new StringReader(vp.Parameters))); if (GIAccessorResponse != null && GIAccessorResponse.Success && GIAccessorResponse.Result.GlobalInventoryId != null) { if (GIAccessorResponse.Result.Detail != null) { //deserialize tag and use for token values into dictionary Dictionary<string, string> tokenValues = new Dictionary<string, string>() { {Tokens.DealixLead.LeadID, lead.Id.ToString() }, {Tokens.DealixLead.DateTime, lead.DateCreated.ToString()}, {Tokens.DealixLead.ThirdPartyFeedID, ""}, //lead.ThirdPartyFeedID {Tokens.DealixLead.VIN, GIAccessorResponse.Result.Detail.VIN.ToString()}, {Tokens.DealixLead.SenderFirstName, lead.FirstName}, {Tokens.DealixLead.SenderLastName, lead.LastName}, {Tokens.DealixLead.SenderEmailAddress, lead.EmailAddress}, {Tokens.DealixLead.SenderPhone, lead.Phone}, {Tokens.DealixLead.SenderCity, lead.City}, {Tokens.DealixLead.SenderLocation, lead.LocationAbbr}, {Tokens.DealixLead.SenderZipcode, lead.ZipCode}, {Tokens.DealixLead.SenderComments, lead.Comments} }; List<CFS.MessageCannon.V2.Interface.Contact> contacts = new List<CFS.MessageCannon.V2.Interface.Contact>() { new CFS.MessageCannon.V2.Interface.Contact { EmailAddress = lead.EmailAddress } }; //open xml file and replace [[token]] with values string fileName = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "Assets", "DealixLeadTemplate.xml"); FileStream xmlFile = File.Open(fileName, FileMode.Open); StreamReader rdr = new StreamReader(xmlFile); string xmlText = rdr.ReadToEnd(); rdr.Close(); xmlFile.Close(); foreach (var item in tokenValues) { xmlText = xmlText.Replace(item.Key, item.Value); } //send xmlText to url string responseText = null; string postUrl = "https://www.awesomecustomsite.com/FormFeed.aspx"; string postData = String.Format("xml={0}", HttpUtility.UrlEncode(xmlText)); byte[] formData = Encoding.UTF8.GetBytes(postData); HttpContent content = new ByteArrayContent(formData); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); HttpClient client = new HttpClient(); using (var response = client.PostAsync(new Uri(postUrl), content).Result) { result = verifyResponseCode(response, log); if (result) { log.Info(typeof(DealixLeadSender).Name, "Lead #{0} sent successfully.", lead.Id); } else { log.Warn(typeof(DealixLeadSender).Name, "Lead #{0} FAILED to send.", lead.Id); log.Warn(typeof(DealixLeadSender).Name, "Lead data sent to handler:\r\n{0}", jsonLead); } } } } return result; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region create users Console.WriteLine(" Creating users"); var ldapPath = ""; _users = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); _users.Add(SystemUserProvider.RetrieveSystemUser( "dparker", "Darren", "Parker", "Salesperson", _serviceProxy, ref ldapPath)); #endregion #region fetch root business unit // Retrieve the root business unit to use for creating the team for the // sample. var businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; businessUnitQuery.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery); _rootBusinessUnit = businessUnitResult.Entities[0].ToEntity<BusinessUnit>(); #endregion #region create new business unit Console.WriteLine(" Creating new business unit"); _buisnessUnit = new BusinessUnit() { Name = "A Sample Business Unit", ParentBusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _buisnessUnit.Id = _serviceProxy.Create(_buisnessUnit); #endregion #region create team Console.WriteLine(" Creating a user team"); _team = new Team { AdministratorId = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Name = "Sample team", BusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _team.Id = _serviceProxy.Create(_team); var salespersonRole = (from role in _context.RoleSet where role.Name == "Salesperson" && role.BusinessUnitId.Id == _rootBusinessUnit.Id select role).First(); // assign role to the team _serviceProxy.Associate( Team.EntityLogicalName, _team.Id, new Relationship("teamroles_association"), new EntityReferenceCollection() { salespersonRole.ToEntityReference() } ); // wait for the async job to finish for (int i = 1; i <= 30; i++) { Console.WriteLine(" Checking to see if the async job has finished {0}/30", i); var teamPrivileges = (RetrieveTeamPrivilegesResponse) _serviceProxy.Execute(new RetrieveTeamPrivilegesRequest { TeamId = _team.Id }); if (teamPrivileges.RolePrivileges.Any((rp) => rp.PrivilegeId == new Guid("A8ECAC53-09E8-4A13-B598-8D8C87BC3D33"))) // prvReadLead { break; } System.Threading.Thread.Sleep(1000); } #endregion #region add users to team Console.WriteLine(" Adding users to the team"); AddMembersTeamRequest addMembers = new AddMembersTeamRequest() { TeamId = _team.Id, MemberIds = new Guid[] { _users[0], _users[1] } }; _serviceProxy.Execute(addMembers); #endregion #region create leads Console.WriteLine(" Creating leads"); _leads[0] = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Joe", LastName = "Andreshak", }; _leads[0].Id = _serviceProxy.Create(_leads[0]); _leads[1] = new Lead { CompanyName = "Wingtip Toys", FirstName = "Diogo", LastName = "Andrade" }; _leads[1].Id = _serviceProxy.Create(_leads[1]); _leads[2] = new Lead { CompanyName = "The Phone Company", FirstName = "Ronaldo", LastName = "Smith Jr." }; _leads[2].Id = _serviceProxy.Create(_leads[2]); _leads[3] = new Lead { CompanyName = "Tailspin Toys", FirstName = "Andrew", LastName = "Sullivan", }; _leads[3].Id = _serviceProxy.Create(_leads[3]); #endregion #region assign leads Console.WriteLine(" Assigning leads to users and teams"); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Target = _leads[0].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[1]), Target = _leads[1].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[2]), Target = _leads[2].ToEntityReference() }); // give the team access to the record so that it can be assigned to it _serviceProxy.Execute(new GrantAccessRequest() { Target = _leads[3].ToEntityReference(), PrincipalAccess = new PrincipalAccess() { AccessMask = AccessRights.ReadAccess|AccessRights.WriteAccess, Principal = _team.ToEntityReference() } }); // assign the lead to the team _serviceProxy.Execute(new AssignRequest() { Assignee = _team.ToEntityReference(), Target = _leads[3].ToEntityReference() }); #endregion }
void Awake() { if (instance != null) { Destroy(gameObject); } else { instance = this; DontDestroyOnLoad(gameObject); } }
private void CreateRequiredRecords() { // Create leads for relating activity feed records to. Since there is an // active post rule config for creation of a new lead, creating the leads // should add an auto post to the record wall for each of the leads. _lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", MiddleName = "Thaulow", LastName = "Andersen", Subject = "Activity Feeds Sample 1" }; _serviceContext.AddObject(_lead1); _lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Mary", MiddleName = "Kay", LastName = "Andersen", Subject = "Activity Feeds Sample 2" }; _serviceContext.AddObject(_lead2); _lead3 = new Lead { CompanyName = "Fabrikam, Inc.", FirstName = "Andrew", LastName = "Sullivan", Subject = "Activity Feeds Sample 3" }; _serviceContext.AddObject(_lead3); _serviceContext.SaveChanges(); var columnSet = new ColumnSet(true); _lead1 = (Lead)_serviceProxy.Retrieve( Lead.EntityLogicalName, _lead1.Id, columnSet); _lead2 = (Lead)_serviceProxy.Retrieve( Lead.EntityLogicalName, _lead2.Id, columnSet); _lead3 = (Lead)_serviceProxy.Retrieve( Lead.EntityLogicalName, _lead3.Id, columnSet); Console.WriteLine(" The leads have been created."); }
/// <summary> /// /// </summary> /// /// <param name="lead"></param> /// /// <returns></returns> /// public ExchangeDisposition Execute(Lead lead) { OnExchangeServiceStart(this, new ExchangeEvent<IExchangeEngine>(this)); Stopwatch timer = new Stopwatch(); timer.Start(); ExchangeRuntime runtime = CreateRuntime(); runtime.Active = true; runtime.StoreData(ExchangeRuntime.LEAD, lead); runtime.Vertical = "DEBT"; runtime.VerticalType = "DATA"; runtime.LeadSource = LeadSource.WS; try { runtime.Invoke(); } catch (Exception exception) { ExceptionHandler<ServiceExceptionFactory>.Process(exception, true, "Failed to save outbound duplicate entity: {0}.", typeof(OutboundDuplicate)); ExchangeDisposition error = new ExchangeDisposition(); error.Aid = lead.Aid; error.Cid = lead.Cid; error.Tid = lead.Tid; error.Status = ExchangeRuntime.ERROR; error.Time = DateTime.Now; error.Guid = lead.Guid; error.Amount = 0; error.MatchCount = 0; return error; } timer.Stop(); // Audit Trail // runtime.AllocationAuditTrail.TotalElapsedTime = timer.ElapsedMilliseconds; runtime.FlagComplete(); OnExchangeServiceEnd(this, new ExchangeEvent<IExchangeEngine>(this)); if (runtime.ValidationErrors.Count > 0) { ExchangeDisposition error = new ExchangeDisposition(); error.Aid = lead.Aid; error.Cid = lead.Cid; error.Tid = lead.Tid; error.Status = ExchangeRuntime.INVALID; error.Time = DateTime.Now; error.Guid = lead.Guid; error.Amount = 0; error.MatchCount = 0; error.Errors = runtime.ValidationErrors; return error; } if (runtime.Errors.Count > 0) { ExchangeDisposition error = new ExchangeDisposition(); error.Aid = lead.Aid; error.Cid = lead.Cid; error.Tid = lead.Tid; error.Status = ExchangeRuntime.ERROR; error.Time = DateTime.Now; error.Guid = lead.Guid; error.Amount = 0; error.MatchCount = 0; return error; } if (runtime.IsInboundDuplicate) { ExchangeDisposition duplicate = new ExchangeDisposition(); duplicate.Aid = lead.Aid; duplicate.Cid = lead.Cid; duplicate.Tid = lead.Tid; duplicate.Status = ExchangeRuntime.DUPLICATE; duplicate.Time = DateTime.Now; duplicate.Guid = lead.Guid; duplicate.Amount = 0; duplicate.MatchCount = 0; return duplicate; } if (runtime.IsSuspect) { ExchangeDisposition suspect = new ExchangeDisposition(); suspect.Aid = lead.Aid; suspect.Cid = lead.Cid; suspect.Tid = lead.Tid; suspect.Status = ExchangeRuntime.PENDING_VERIFICATION; suspect.Time = DateTime.Now; suspect.Guid = lead.Guid; suspect.Amount = 0; suspect.MatchCount = 0; return suspect; } if (runtime.PendingMatch) { ExchangeDisposition pendingMatch = new ExchangeDisposition(); pendingMatch.Aid = lead.Aid; pendingMatch.Cid = lead.Cid; pendingMatch.Tid = lead.Tid; pendingMatch.Status = ExchangeRuntime.PENDING_MATCH; pendingMatch.Time = DateTime.Now; pendingMatch.Guid = lead.Guid; pendingMatch.Amount = 0; pendingMatch.MatchCount = 0; return pendingMatch; } ExchangeDisposition disposition = new ExchangeDisposition(); disposition.Aid = lead.Aid; disposition.Amount = 0.00; disposition.Cid = lead.Cid; disposition.Tid = lead.Tid; disposition.Status = ExchangeRuntime.ACCEPTED; disposition.Time = DateTime.Now; disposition.Guid = lead.Guid; disposition.MatchCount = runtime.AllocationCount; return disposition; }
protected void nextStep_Click(object sender, EventArgs e) { if (!validateForm()) return; int amountToCharge = Convert.ToInt32(ViewState["originalamount"]); string firstName = billTo_firstName.Text; string lastName = billTo_lastName.Text; string city = billTo_city.Text; string country = billTo_country.Text; string address = billTo_street1.Text; string state = billTo_state.Text; string zip = billTo_postalCode.Text; string phone = billTo_phoneNumber.Text; string email = billTo_email.Text; string numstudents = "1"; // numberOfStudents.SelectedValue.ToString(); string comments = billto_comments.Text; string couponcode = ""; // couponCode.Text; string registrationId = "0"; string company = txtcompany.Text; string leadsource = (findUs.SelectedItem.Text + " " + sourceOther.Text); var conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["classDBF"].ConnectionString); conn.Open(); try { string insertSql = string.Format( "Insert Into registration ( classId, amounttocharge, firstname, lastname, address, city , state, zipcode, country, phone, email, numstudents, couponcode, comments, DateCreated, company, leadsource ) " + " values ({0},{1},'{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',{11},'{12}', '{13}', '" + DateTime.Now + "','{14}', '{15}')", classID.Text, amountToCharge, firstName, lastName, address, city, state, zip, country, phone, email, numstudents, couponcode, comments, company, leadsource); var cmd = new OleDbCommand(insertSql, conn); cmd.ExecuteNonQuery(); cmd = new OleDbCommand("select max(registrationid) from registration", conn); registrationId = cmd.ExecuteScalar().ToString(); } catch (Exception ex) { Response.Write(ex.Message); return; } finally { conn.Close(); } if (ConfigurationManager.AppSettings["SendLeadsToSalesForce"] == "true") { try { var sf = new SalesForceHelper(); var lead = new Lead(); lead.FirstName = firstName; lead.LastName = lastName; lead.Company = company; lead.Email = email; lead.Phone = phone; if (leadsource.Length > 40) leadsource = leadsource.Substring(0, 40); lead.LeadSource = leadsource; lead.Street = address; lead.City = city; lead.State = state; lead.PostalCode = zip; lead.Description = "Web Site Registration Initiated - " + locationLabel.Text + " " + ClassHeader1.ClassType + " " + classDate.Text + " Comments: " + billto_comments.Text; var sr = sf.Binding.create(new sObject[] {lead}); foreach (var s in sr) { if (s.success) { Session["LeadId"] = s.id; break; } throw new Exception(string.Format("Error creating Lead: {0}", s.errors[0].message)); } } catch (Exception ex) { var objSendEmail = new SendMail(); objSendEmail.IsHTML = true; objSendEmail.Subject = "Error on pinnacle3learning.com - SalesForce Integration"; string body = "<b>Message</b><br>" + ex.Message + "<br><br>"; body += "<b>Attempting to Create Lead</b><br>" + firstName + " " + lastName + "<br><br>"; body += "<b>Page</b><br>register.aspx<br><br>"; body += "<b>Inner Exception</b><br>" + ex.InnerException + "<br><br>"; body += "<b>Stack Trace</b><br>" + ex.StackTrace + "<br><br>"; body += "<b>TimeStamp</b><br>" + DateTime.Now.ToString() + "<br><br>"; objSendEmail.Body = body; SendMail.Send(objSendEmail, true); } } nextStep.Visible = false; string url; // if the config setting allows it, go secure for the rest of the user's visit. if (ConfigurationManager.AppSettings["GoSecure"] == "true") { url = String.Format("https://{0}{1}", Request.ServerVariables["HTTP_HOST"], ResolveUrl("~/confirm.aspx?registrationid=" + registrationId)); } else { url = "confirm.aspx?registrationid=" + registrationId; } var redirect = "window.location.href='" + url + "'"; ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), redirect, true); }