protected void UpdateButton_Click(object sender, EventArgs e) { if (Case == null) { throw new NullReferenceException("Case must not be null. Update failed."); } Case.Adx_ModifiedByUsername = Contact.FullName; Case.Adx_ModifiedByIPAddress = Request.UserHostAddress; XrmContext.Attach(Case); XrmContext.UpdateObject(Case); XrmContext.SaveChanges(); XrmContext.Detach(Case); var contactName = Contact.FullName; var noteSubject = "Note created on " + DateTime.Now + " by " + contactName; if (!string.IsNullOrEmpty(NewNote.Text) || (Attachment.PostedFile != null && Attachment.PostedFile.ContentLength > 0)) { XrmContext.AddNoteAndSave(Case, noteSubject, "*WEB* " + NewNote.Text, Attachment.PostedFile); } if (System.Web.SiteMap.CurrentNode == null) { return; } Response.Redirect(Request.RawUrl); }
protected void ScheduleService_Click(object sender, EventArgs e) { var availableResourceId = (Guid)AvailableTimes.SelectedDataKey.Values["AvailableResource"]; var availableResource = XrmContext.ResourceSet.First(r => r.ResourceId == availableResourceId); var selectedStart = (DateTime)AvailableTimes.SelectedDataKey.Values["ScheduledStartUniversalTime"]; var selectedEnd = (DateTime)AvailableTimes.SelectedDataKey.Values["ScheduledEndUniversalTime"]; var appointment = new ServiceAppointment { ServiceId = Service.ToEntityReference(), Subject = "Web Service Scheduler: " + ServiceType.SelectedItem, ScheduledStart = selectedStart, ScheduledEnd = selectedEnd, Resources = new[] { new ActivityParty { PartyId = new EntityReference(availableResource.ObjectTypeCode, availableResource.Id) } }, Customers = new[] { new ActivityParty { PartyId = Contact.ToEntityReference() } } }; XrmContext.AddObject(appointment); XrmContext.SaveChanges(); XrmContext.SetState((int)Enums.ServiceAppointmentState.Scheduled, 4, appointment); var page = ServiceContext.GetPageBySiteMarkerName(Website, "Service Details"); Response.Redirect(string.Format("{0}?serviceid={1}", ServiceContext.GetUrl(page), appointment.Id)); }
protected void SetPrimaryContactButton_Click(object sender, EventArgs e) { var selectedGuid = new Guid(PrimaryContactList.SelectedItem.Value); var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == selectedGuid); if (contact == null) { throw new ApplicationException(string.Format("Couldn't find contact with contactid equal to {0}.", selectedGuid)); } var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == AccountToEdit.GetAttributeValue <Guid>("accountid")); if (account == null) { throw new ApplicationException(string.Format("An account with the account ID equal to {0} couldn’t be found.", AccountToEdit.GetAttributeValue <Guid>("accountid"))); } account.SetAttributeValue("primarycontactid", contact.ToEntityReference()); XrmContext.UpdateObject(contact); XrmContext.UpdateObject(account); XrmContext.SaveChanges(); SuccessMessage.Visible = true; }
protected void InviteButton_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } //create invitation Code var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == ContactToEdit.GetAttributeValue <Guid>("contactid")); if (contact == null) { throw new ArgumentNullException(string.Format("Unable to find contact with id equal to {0}", ContactToEdit.GetAttributeValue <Guid>("contactid"))); } var invitation = new Entity("adx_invitation"); invitation.SetAttributeValue("adx_name", "Auto-generated email confirmation"); invitation.SetAttributeValue("adx_type", new OptionSetValue(756150000)); // Single invitation.SetAttributeValue("adx_invitecontact", contact.ToEntityReference()); invitation.SetAttributeValue("adx_invitationcode", XrmContext.CreateInvitationCode()); XrmContext.AddObject(invitation); CreatePermissions(); XrmContext.SaveChanges(); // Execute workflow to send invitation code in confirmation email XrmContext.ExecuteWorkflowByName(ServiceContext.GetSiteSettingValueByName(Website, "Account/EmailConfirmation/WorkflowName") ?? "ADX Sign Up Email", invitation.Id); InvitationConfirmationMessage.Visible = true; }
protected void CreateCase_Click(object sender, EventArgs args) { RedirectToLoginIfAnonymous(); if (CaseEntitlementEnabled) { var supportRequest = new Entity("adx_supportrequest"); supportRequest["adx_name"] = "Support Request for {0}".FormatWith(Portal.User.GetAttributeValue <string>("fullname")); supportRequest["adx_responsiblecontact"] = Portal.User.ToEntityReference(); XrmContext.AddObject(supportRequest); XrmContext.SaveChanges(); var redirectUrl = BuildOpenNewSupportRequestUrl(supportRequest.Id); Response.Redirect(redirectUrl); } else { var redirectUrl = CreateCaseUrl(); Response.Redirect(redirectUrl); } }
protected void InviteContact(Entity contact) { var invitation = new Entity("adx_invitation"); invitation.SetAttributeValue("adx_name", "Auto-generated email confirmation"); invitation.SetAttributeValue("adx_type", new OptionSetValue(756150000)); // Single invitation.SetAttributeValue("adx_invitecontact", contact.ToEntityReference()); invitation.SetAttributeValue("adx_invitationcode", XrmContext.CreateInvitationCode()); var oppPermissions = new Entity("adx_opportunitypermissions"); oppPermissions.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_name", "opportunitity permissions for " + contact.GetAttributeValue <string>("fullname")); oppPermissions.SetAttributeValue("adx_contactid", contact.ToEntityReference()); oppPermissions.SetAttributeValue("adx_accountid", contact.GetAttributeValue <EntityReference>("parentcustomerid")); oppPermissions.SetAttributeValue("adx_scope", new OptionSetValue((int)Enums.OpportunityAccessScope.Self)); oppPermissions.SetAttributeValue("adx_read", true); var channelPermissions = new Entity("adx_channelpermissions"); channelPermissions.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_name", "channel permissions for " + contact.GetAttributeValue <string>("fullname")); channelPermissions.SetAttributeValue("adx_contactid", contact.ToEntityReference()); channelPermissions.SetAttributeValue("adx_accountid", contact.GetAttributeValue <EntityReference>("parentcustomerid")); XrmContext.AddObject(invitation); XrmContext.AddObject(channelPermissions); XrmContext.AddObject(oppPermissions); XrmContext.UpdateObject(contact); XrmContext.SaveChanges(); // Execute workflow to send invitation code in confirmation email XrmContext.ExecuteWorkflowByName(ServiceContext.GetSiteSettingValueByName(Website, "Account/EmailConfirmation/WorkflowName") ?? "ADX Sign Up Email", invitation.Id); }
protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e) { var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == (Contact.GetAttributeValue <EntityReference>("parentcustomerid") == null ? Guid.Empty : Contact.GetAttributeValue <EntityReference>("parentcustomerid").Id)); var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == e.EntityId); if (account == null || contact == null) { throw new Exception("Unable to retrieve account or contact for the logged in user."); } contact.SetAttributeValue("parentcustomerid", account.ToEntityReference()); //XrmContext.UpdateObject(account); if (Invite) { InviteContact(contact); } XrmContext.UpdateObject(contact); XrmContext.SaveChanges(); var url = GetUrlForRequiredSiteMarker("Manage Partner Account"); Response.Redirect(url.PathWithQueryString); }
protected void OpenNewSupportRequest_OnClick(object sender, EventArgs e) { RedirectToLoginIfAnonymous(); if (CaseEntitlementEnabled) { var supportRequest = new Entity("adx_supportrequest"); var metadataCache = new Dictionary <string, EntityMetadata>(); supportRequest.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_name", Subject.Text, metadataCache); supportRequest.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_title", Subject.Text, metadataCache); supportRequest["adx_responsiblecontact"] = Portal.User.ToEntityReference(); var product = Product.SelectedItem; Guid productId; if (product != null && Guid.TryParse(product.Value, out productId)) { supportRequest["adx_product"] = new EntityReference("product", productId); } XrmContext.AddObject(supportRequest); XrmContext.SaveChanges(); var redirectUrl = BuildOpenNewSupportRequestUrl(supportRequest.Id); Response.Redirect(redirectUrl); } else { var redirectUrl = CreateCaseUrl(); Response.Redirect(redirectUrl); } }
protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e) { var account = XrmContext.CreateQuery("account").FirstOrDefault(c => c.GetAttributeValue <Guid>("accountid") == e.EntityId); if (account == null) { throw new Exception(string.Format("An account with the account ID equal to {0} couldn’t be found.", e.EntityId)); } var parentCustomerAccount = Contact.GetAttributeValue <EntityReference>("parentcustomerid") == null ? null : XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == Contact.GetAttributeValue <EntityReference>("parentcustomerid").Id); if (parentCustomerAccount == null) { throw new Exception("Parent Customer Account could not be found associated to the current user's contact."); } account.SetAttributeValue("msa_managingpartnerid", parentCustomerAccount.ToEntityReference()); var accountId = account.GetAttributeValue <Guid>("accountid"); XrmContext.UpdateObject(account); XrmContext.SaveChanges(); var url = GetUrlForRequiredSiteMarker("Create Customer Contact"); url.QueryString.Set("AccountId", accountId.ToString()); url.QueryString.Set("SetAsPrimary", "true"); url.QueryString.Set(FromCreateOpportunity ? "FromCreateOpportunity" : "ReturnToAccount", "true"); Response.Redirect(url.PathWithQueryString); }
protected void AddToCart() { const string nameFormat = "Case Order for {0}"; var cart = new Entity("adx_shoppingcart"); cart.SetAttributeValue("adx_websiteid", Website.ToEntityReference()); cart.SetAttributeValue("adx_system", true); if (Contact == null) { cart.SetAttributeValue("adx_name", string.Format(nameFormat, VisitorID)); cart.SetAttributeValue("adx_visitorid", VisitorID); } else { cart.SetAttributeValue("adx_name", string.Format(nameFormat, Contact.GetAttributeValue <string>("fullname"))); cart.SetAttributeValue("adx_contactid", Contact.ToEntityReference()); } XrmContext.AddObject(cart); XrmContext.SaveChanges(); // Choose Parent Product var selectedValue = PlanPackageList.SelectedValue; var guids = selectedValue.Split('&'); var supportProductId = new Guid(guids[0]); var uomId = new Guid(guids[1]); var caseProduct = XrmContext.CreateQuery("product") .FirstOrDefault(p => p.GetAttributeValue <Guid>("productid") == supportProductId); var myUom = XrmContext.CreateQuery("uom") .FirstOrDefault(uom => uom.GetAttributeValue <Guid>("uomid") == uomId); var productId = caseProduct != null ? caseProduct.Id : Guid.Empty; cart = XrmContext.CreateQuery("adx_shoppingcart") .FirstOrDefault(sc => sc.GetAttributeValue <Guid>("adx_shoppingcartid") == cart.Id); var myCart = cart == null ? null : new ShoppingCart(cart, XrmContext); if (myCart == null) { throw new ApplicationException("Unable to retrieve case purchase shopping cart."); } myCart.AddProductToCart(productId, myUom, PriceListName); var total = myCart.GetCartTotal(); if (total < 0) { throw new ApplicationException("Case purchase shopping cart cannot have a sub-zero total value."); } AddCartToSupportRequest(myCart); }
protected void ScheduleListView_ItemCommand(object sender, ListViewCommandEventArgs e) { if (e == null || e.CommandArgument == null) { return; } var id = new Guid(e.CommandArgument.ToString()); switch (e.CommandName) { case "AddToSchedule": { // add this to the user's schedule var sessionSchedule = XrmContext.CreateQuery("adx_eventschedule").First(es => es.GetAttributeValue <Guid>("adx_eventscheduleid") == id); var registration = new Entity("adx_eventregistration"); registration.SetAttributeValue("adx_attendeeid", Attendee.ToEntityReference()); registration.SetAttributeValue("adx_eventid", sessionSchedule.GetAttributeValue <EntityReference>("adx_eventid")); registration.SetAttributeValue("adx_eventscheduleid", sessionSchedule.ToEntityReference()); registration.SetAttributeValue("adx_registrationdate", DateTime.UtcNow); XrmContext.AddObject(registration); XrmContext.SaveChanges(); } break; case "RemoveFromSchedule": { // remove this from the user's schedule var sessionSchedule = XrmContext.CreateQuery("adx_eventschedule").First(es => es.GetAttributeValue <Guid>("adx_eventscheduleid") == id); var eventSchedules = sessionSchedule.GetRelatedEntities(XrmContext, new Relationship("adx_eventschedule_eventregistration")).ToList(); var registration = eventSchedules.FirstOrDefault(er => er.GetAttributeValue <EntityReference>("adx_attendeeid") == Attendee.ToEntityReference()); XrmContext.DeleteObject(registration); XrmContext.SaveChanges(); } break; case "Feedback": { var feedbackPage = ServiceContext.GetPageBySiteMarkerName(Website, "Event Feedback"); if (feedbackPage != null) { var url = new UrlBuilder(ServiceContext.GetUrl(feedbackPage)); url.QueryString["id"] = id.ToString(); Response.Redirect(url.PathWithQueryString); } } break; } // redirect to current page (to avoid re-post issues) if (SiteMap.CurrentNode == null) { return; } Response.Redirect(SiteMap.CurrentNode.Url); }
protected void UpdateCartItems() { foreach (var item in CartItems.Items) { var cartItemIdTextBox = item.FindControl("CartItemID") as TextBox; if (cartItemIdTextBox == null) { continue; } var quantityTextBox = item.FindControl("Quantity") as TextBox; if (quantityTextBox == null) { continue; } int quantity; if (!int.TryParse(quantityTextBox.Text, out quantity)) { throw new InvalidOperationException("Could not parse quantity"); } try { var cartItemId = new Guid(cartItemIdTextBox.Text); var cartItem = Cart.GetCartItemByID(cartItemId) as ShoppingCartItem; if (cartItem == null) { throw new InvalidOperationException("Unable to find cart item corresponding to CartItemID"); } if (cartItem.Quantity != quantity) { cartItem.Quantity = quantity; } cartItem.UpdateItemPrice(PriceListName); } catch (FormatException) { throw new InvalidOperationException("Unable to parse Guid from CartItemID value"); } } XrmContext.SaveChanges(); }
protected void ResolveButton_Click(object sender, EventArgs e) { EditPanel.Enabled = false; CloseRelatedActivities(); Case.CustomerSatisfactionCode = int.Parse(Satisfaction.SelectedValue); XrmContext.Attach(Case); XrmContext.UpdateObject(Case); XrmContext.SaveChanges(); XrmContext.SetCaseStatusAndSave(Case, "Resolved", Resolution.Text); XrmContext.Detach(Case); Response.Redirect(Request.RawUrl); }
protected void ManagePermissionsButton_Click(object sender, EventArgs e) { var url = GetUrlForRequiredSiteMarker("Manage Permissions"); var permissionsCreated = CreatePermissions(); if (permissionsCreated) { XrmContext.SaveChanges(); } var id = ContactToEdit.GetAttributeValue <Guid>("contactid"); url.QueryString.Set("ContactID", id.ToString()); Response.Redirect(url.PathWithQueryString); }
protected void SubmitButton_Click(object sender, EventArgs e) { if (userName == passwordTextBox.Text) { Message1.Visible = true; Message1.Text = "Old password and new password must be different. Please try again."; } else { Message1.Visible = false; LoginContact.Adx_password = passwordTextBox.Text; LoginContact.Adx_changepasswordatnextlogon = false; XrmContext.Attach(LoginContact); XrmContext.UpdateObject(LoginContact); XrmContext.SaveChanges(); XrmContext.Detach(LoginContact); Response.Redirect("login", true); } }
private void SaveAccountDetails(Account account) { if (account == null) { return; } account.Name = AccountName.Text; account.WebSiteURL = AccountWebsite.Text; account.Address1_Line1 = AccountAddress1.Text; account.Address1_Line2 = AccountAddress2.Text; account.Address1_Line3 = AccountAddress3.Text; account.Address1_City = AccountCity.Text; account.Address1_StateOrProvince = AccountProvince.Text; account.Address1_PostalCode = AccountPostalCode.Text; account.Address1_Country = AccountCountry.Text; XrmContext.UpdateObject(account); XrmContext.SaveChanges(); }
protected void ProductItemCommand(object sender, CommandEventArgs e) { if (e.CommandName != "AddToCart") { return; } if (Cart == null) { const string nameFormat = "Cart for {0}"; var cart = new Entity("adx_shoppingcart"); cart.SetAttributeValue("adx_websiteid", Website.ToEntityReference()); if (Contact == null) { cart.SetAttributeValue("adx_name", string.Format(nameFormat, VisitorID)); cart.SetAttributeValue("adx_visitorid", VisitorID); } else { cart.SetAttributeValue("adx_name", string.Format(nameFormat, Contact.GetAttributeValue <string>("fullname"))); cart.SetAttributeValue("adx_contactid", Contact.ToEntityReference()); } XrmContext.AddObject(cart); XrmContext.SaveChanges(); } var productId = new Guid(e.CommandArgument.ToString()); if (Cart == null) { throw new Exception("Error Processing Cart."); } Cart.AddProductToCart(productId, PriceListName); Response.Redirect(Html.SiteMarkerUrl("Shopping Cart") ?? Request.Url.PathAndQuery); }
protected void ScheduleService_Click(object sender, EventArgs e) { var availableResourceId = (Guid)AvailableTimes.SelectedDataKey.Values["AvailableResource"]; var availableResource = XrmContext.CreateQuery("resource").First(r => r.GetAttributeValue <Guid>("resourceid") == availableResourceId); var selectedStart = (DateTime)AvailableTimes.SelectedDataKey.Values["ScheduledStartUniversalTime"]; var selectedEnd = (DateTime)AvailableTimes.SelectedDataKey.Values["ScheduledEndUniversalTime"]; var appointment = new Entity("serviceappointment"); appointment.SetAttributeValue("serviceid", Service.ToEntityReference()); appointment.SetAttributeValue("subject", "Web Service Scheduler: " + ServiceType.SelectedItem); appointment.SetAttributeValue("scheduledstart", selectedStart); appointment.SetAttributeValue("scheduledend", selectedEnd); var resourcesActivityParty = new Entity("activityparty"); resourcesActivityParty["partyid"] = new EntityReference(availableResource.GetAttributeValue <string>("objecttypecode"), availableResource.Id); var resources = new EntityCollection(new List <Entity> { resourcesActivityParty }); appointment.SetAttributeValue("resources", resources); var customersActivityParty = new Entity("activityparty"); customersActivityParty["partyid"] = Contact.ToEntityReference(); var customers = new EntityCollection(new List <Entity> { customersActivityParty }); appointment.SetAttributeValue("customers", customers); XrmContext.AddObject(appointment); XrmContext.SaveChanges(); XrmContext.SetState((int)ServiceAppointmentState.Scheduled, 4, appointment); var page = ServiceContext.GetPageBySiteMarkerName(Website, "Service Details"); Response.Redirect(string.Format("{0}?serviceid={1}", ServiceContext.GetUrl(page), appointment.Id)); }
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e) { if (LoginContact == null) { e.Authenticated = false; } else { if (LoginContact.Adx_username == Login1.UserName) { if (LoginContact.Adx_changepasswordatnextlogon.Value) { var portal = PortalCrmConfigurationManager.CreatePortalContext(); var website = (Adx_website)portal.Website; var page = (Adx_webpage)portal.ServiceContext.GetPageBySiteMarkerName(portal.Website, "ChangePassword"); string redirectURL = page.Adx_PartialUrl + "?UserName="******"&Password=" + Server.UrlEncode(Login1.Password); Response.Redirect(redirectURL); } else { LoginContact.Adx_LastSuccessfulLogon = DateTime.Now; XrmContext.Attach(LoginContact); XrmContext.UpdateObject(LoginContact); XrmContext.SaveChanges(); XrmContext.Detach(LoginContact); e.Authenticated = true; FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true); } } else { e.Authenticated = false; } } }
protected void SubmitButton_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } if (!Request.IsAuthenticated) { return; } if (AccountInformation.Visible) { var contactAccount = Contact.contact_customer_accounts; SaveAccountDetails(XrmContext.AccountSet.FirstOrDefault(a => a.AccountId == contactAccount.AccountId)); } if (SelfInformation.Visible) { var contact = XrmContext.MergeClone(Contact); SetContactDetails(contact); XrmContext.UpdateObject(contact); ManageLists(XrmContext, contact); XrmContext.SaveChanges(); } var snippet = RegistrationPanel.FindControl("ProfileUpdatedMsg"); if (snippet != null) { snippet.Visible = true; } }
protected void CreateButton_Click(object sender, EventArgs e) { var access = ServiceContext.GetCaseAccessByContact(Contact) as Adx_caseaccess; if (access == null || !access.Adx_Create.GetValueOrDefault()) { return; // no permission to create a case } PriorityCode.SelectedValue = PriorityCode.Items.FindByText(ServiceContext.GetSiteSettingValueByName(Website, "case/prioritycode")).Value; var subject = XrmContext.SubjectSet.First(s => s.Title == ServiceContext.GetSiteSettingValueByName(Website, "case/subject")); var incident = new Incident { Title = TitleTextBox.Text, PriorityCode = int.Parse(PriorityCode.SelectedValue), CaseTypeCode = int.Parse(CaseType.SelectedValue), SubjectId = subject.ToEntityReference(), CustomerId = Contact.ToEntityReference(), Adx_CreatedByUsername = Contact.FullName, Adx_CreatedByIPAddress = Request.UserHostAddress, }; XrmContext.AddObject(incident); XrmContext.SaveChanges(); var noteSubject = "Note created on " + DateTime.Now + " by " + Contact.FullName; XrmContext.AddNoteAndSave(incident, noteSubject, WebAnnotationPrefix + " " + Description.Text, Attachment.PostedFile); var page = ServiceContext.GetPageBySiteMarkerName(Website, "Cases"); Response.Redirect(ServiceContext.GetUrl(page)); }
protected void Register_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } // Determine if the user is already in the CRM as either a lead or customer var existingContact = XrmContext.ContactSet.FirstOrDefault(c => c.EMailAddress1 == EMail.Text); var existingLead = XrmContext.LeadSet.FirstOrDefault(l => l.EMailAddress1 == EMail.Text); var eventParticipant = new ActivityParty(); if (existingContact != null) { eventParticipant.contact_activity_parties = existingContact; eventParticipant.PartyId = new EntityReference(Contact.EntityLogicalName, existingContact.ContactId.GetValueOrDefault()); } else if (existingLead != null) { eventParticipant.lead_activity_parties = existingLead; eventParticipant.PartyId = new EntityReference(Lead.EntityLogicalName, existingLead.Id); } else { // No Contact or Lead previously exsits in the CRM // Create the registrant as a lead in the CRM var newLead = new Lead { Subject = string.Format("{0}, {1}: {2}", LastName.Text, FirstName.Text, Campaign.Name), FirstName = FirstName.Text, LastName = LastName.Text, CompanyName = CompanyName.Text, LeadQualityCode = 2, Telephone1 = Phone.Text, EMailAddress1 = EMail.Text, Address1_Line1 = Address1.Text, Address1_Line2 = Address2.Text, Address1_Line3 = Address3.Text, Address1_StateOrProvince = State.Text, Address1_PostalCode = PostalCode.Text, Address1_Country = Country.Text }; XrmContext.AddObject(newLead); XrmContext.SaveChanges(); existingLead = XrmContext.LeadSet.FirstOrDefault(l => l.EMailAddress1 == EMail.Text); if (existingLead != null) { eventParticipant.lead_activity_parties = existingLead; eventParticipant.PartyId = new EntityReference(Lead.EntityLogicalName, existingLead.Id); } } // Register user for event by creating a marketing response var registration = new CampaignResponse { Customer = new[] { eventParticipant }, RegardingObjectId = Campaign.ToEntityReference(), ResponseCode = 200000, Subject = string.Format("{0}, {1}: {2}", LastName.Text, FirstName.Text, Campaign.Name), ChannelTypeCode = 200000, ReceivedOn = DateTime.Now, FirstName = FirstName.Text, LastName = LastName.Text, MSA_StreetAddress1 = Address1.Text, MSA_StreetAddress2 = Address2.Text, MSA_StreetAddress3 = Address3.Text, MSA_City = City.Text, MSA_State = State.Text, MSA_PostalCode = PostalCode.Text, MSA_Country = Country.Text, CompanyName = CompanyName.Text, MSA_JobTitle = JobTitle.Text, Telephone = Phone.Text, EMailAddress = EMail.Text, Description = Notes.Text, MSA_PreferredMethodofCommunication = CommunicationMethod.SelectedIndex }; XrmContext.AddObject(registration); XrmContext.SaveChanges(); //Show Confirmation RegForm.Visible = false; ConfirmationMsg.Visible = true; EventExportLink.NavigateUrl = string.Format("/Event.axd?type=registration&id={0}", Campaign.Id); }
protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e) { var opportunity = XrmContext.CreateQuery("opportunity").First(o => o.GetAttributeValue <Guid>("opportunityid") == e.EntityId); var opportunityProductsFromLead = opportunity.GetAttributeValue <string>("adx_opportunityproductsfromlead"); var productsList = new List <Entity>(); if (!string.IsNullOrEmpty(opportunityProductsFromLead)) { var products = XrmContext.CreateQuery("product"); var words = opportunityProductsFromLead.Split(','); foreach (var word in words) { foreach (var product in products) { if (product.GetAttributeValue <string>("name").Trim().ToUpper() == word.Trim().ToUpper()) { productsList.Add(product); } } } } foreach (var leadProduct in productsList) { if (!XrmContext.IsAttached(leadProduct)) { XrmContext.Attach(leadProduct); } XrmContext.AddLink(opportunity, new Relationship("adx_opportunity_product"), leadProduct); } opportunity.SetAttributeValue("adx_referencecode", GetOpportunityReferenceCode()); var salesStage = opportunity.GetAttributeValue <OptionSetValue>("salesstagecode") == null ? 0 : opportunity.GetAttributeValue <OptionSetValue>("salesstagecode").Value; var response = (RetrieveAttributeResponse)ServiceContext.Execute(new RetrieveAttributeRequest { EntityLogicalName = "opportunity", LogicalName = "salesstagecode" }); var picklist = response.AttributeMetadata as PicklistAttributeMetadata; if (picklist == null) { return; } foreach (var option in picklist.OptionSet.Options) { if (option != null && option.Value != null && option.Value.Value == salesStage) { opportunity.SetAttributeValue("stepname", option.Label.GetLocalizedLabelString()); } } var leadType = XrmContext.CreateQuery("adx_leadtype").FirstOrDefault(lt => lt.GetAttributeValue <string>("adx_name") == "Partner Created"); if (leadType != null) { opportunity.SetAttributeValue("adx_leadtypeid", leadType.ToEntityReference()); } XrmContext.UpdateObject(opportunity); XrmContext.SaveChanges(); var url = GetUrlForRequiredSiteMarker("Accepted Opportunities"); Response.Redirect(url); }
protected void FindTimes_Click(object sender, EventArgs args) { var startTimeInMinutesFromMidnight = int.Parse(StartTime.SelectedValue); var startDate = StartDate.SelectedDate.AddMinutes(startTimeInMinutesFromMidnight); var endTimeInMinutesFromMidnight = int.Parse(EndTime.SelectedValue); var endDate = EndDate.SelectedDate.AddMinutes(endTimeInMinutesFromMidnight); if (!SelectedDatesAndTimesAreValid(startDate, endDate, startTimeInMinutesFromMidnight, endTimeInMinutesFromMidnight)) { return; } // Add the timezone selected to the CRM Contact for next time. var contact = XrmContext.ContactSet.FirstOrDefault(c => c.ContactId == Contact.Id); contact.Adx_TimeZone = int.Parse(TimeZoneSelection.SelectedValue); XrmContext.UpdateObject(contact); XrmContext.SaveChanges(); var usersMinutesFromGmt = GetUsersMinutesFromGmt(contact.Adx_TimeZone, XrmContext); var appointmentRequest = new AppointmentRequest { AnchorOffset = Service.AnchorOffset.GetValueOrDefault(), Direction = SearchDirection.Forward, Duration = Service.Duration.GetValueOrDefault(60), NumberOfResults = 10, RecurrenceDuration = endTimeInMinutesFromMidnight - startTimeInMinutesFromMidnight, RecurrenceTimeZoneCode = contact.Adx_TimeZone.GetValueOrDefault(), SearchRecurrenceRule = "FREQ=DAILY;INTERVAL=1", SearchRecurrenceStart = new DateTime(startDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc), SearchWindowEnd = new DateTime(endDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc), ServiceId = Service.ServiceId.GetValueOrDefault() }; var service = XrmContext; var searchRequest = new OrganizationRequest("Search"); searchRequest.Parameters["AppointmentRequest"] = appointmentRequest; var searchResults = (SearchResults)service.Execute(searchRequest).Results["SearchResults"]; var schedules = searchResults.Proposals.Select(proposal => new { ScheduledStart = proposal.Start.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt), ScheduledStartUniversalTime = proposal.Start.GetValueOrDefault().ToUniversalTime(), ScheduledEnd = proposal.End.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt), ScheduledEndUniversalTime = proposal.End.GetValueOrDefault().ToUniversalTime(), AvailableResource = proposal.ProposalParties.First().ResourceId }); AvailableTimes.DataSource = schedules; AvailableTimes.DataBind(); SearchPanel.Visible = false; ResultsDisplay.Visible = true; ScheduleServiceButton.Enabled = false; }
protected void FindTimes_Click(object sender, EventArgs args) { var startTimeInMinutesFromMidnight = int.Parse(StartTime.SelectedValue); var startDate = StartDate.SelectedDate.AddMinutes(startTimeInMinutesFromMidnight); var endTimeInMinutesFromMidnight = int.Parse(EndTime.SelectedValue); var endDate = EndDate.SelectedDate.AddMinutes(endTimeInMinutesFromMidnight); if (!SelectedDatesAndTimesAreValid(startDate, endDate, startTimeInMinutesFromMidnight, endTimeInMinutesFromMidnight)) { return; } // Add the timezone selected to the CRM Contact for next time. var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == Contact.Id); if (contact == null) { throw new ApplicationException(string.Format("Could not find user contact where contactid equals '{0}'", Contact.Id)); } contact.SetAttributeValue("adx_timezone", int.Parse(TimeZoneSelection.SelectedValue)); XrmContext.UpdateObject(contact); XrmContext.SaveChanges(); var usersMinutesFromGmt = GetUsersMinutesFromGmt(contact.GetAttributeValue <int?>("adx_timezone"), XrmContext); var appointmentRequest = new AppointmentRequest { AnchorOffset = Service.GetAttributeValue <int?>("anchoroffset").GetValueOrDefault(), Direction = SearchDirection.Forward, Duration = Service.GetAttributeValue <int?>("duration").GetValueOrDefault(60), NumberOfResults = 10, RecurrenceDuration = endTimeInMinutesFromMidnight - startTimeInMinutesFromMidnight, RecurrenceTimeZoneCode = contact.GetAttributeValue <int?>("adx_timezone").GetValueOrDefault(), SearchRecurrenceRule = "FREQ=DAILY;INTERVAL=1", SearchRecurrenceStart = new DateTime(startDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc), SearchWindowEnd = new DateTime(endDate.AddMinutes(usersMinutesFromGmt * -1).Ticks, DateTimeKind.Utc), ServiceId = Service.GetAttributeValue <Guid>("serviceid") }; var service = XrmContext; var searchRequest = new OrganizationRequest("Search"); searchRequest.Parameters["AppointmentRequest"] = appointmentRequest; var searchResults = (SearchResults)service.Execute(searchRequest).Results["SearchResults"]; var schedules = searchResults.Proposals.Select(proposal => new { ScheduledStart = proposal.Start.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt), ScheduledStartUniversalTime = proposal.Start.GetValueOrDefault().ToUniversalTime(), ScheduledEnd = proposal.End.GetValueOrDefault().ToUniversalTime().AddMinutes(usersMinutesFromGmt), ScheduledEndUniversalTime = proposal.End.GetValueOrDefault().ToUniversalTime(), AvailableResource = proposal.ProposalParties.First().ResourceId }).Where(proposal => proposal.ScheduledStartUniversalTime >= DateTime.UtcNow); if (!schedules.Any()) { SearchPanel.Visible = true; NoTimesMessage.Visible = true; ResultsDisplay.Visible = false; return; } AvailableTimes.DataSource = schedules; AvailableTimes.DataBind(); SearchPanel.Visible = false; ResultsDisplay.Visible = true; ScheduleServiceButton.Enabled = false; }
protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e) { var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == e.EntityId); if (contact == null) { throw new Exception(string.Format("A contact couldn't be found with a contact ID equal to {0}.", e.EntityId)); } var parentCustomerAccount = Contact.GetAttributeValue <EntityReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == Contact.GetAttributeValue <EntityReference>("parentcustomerid").Id); if (parentCustomerAccount == null) { throw new Exception("Parent Customer Account could not be found associated to the current user's contact."); } Guid accountId = (Guid.TryParse(CompanyNameList.SelectedValue, out accountId)) ? accountId : Guid.Empty; var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == accountId); var opportunity = OriginatingOpportunity == null ? null : XrmContext.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue <Guid>("opportunityid") == OriginatingOpportunity.Id); if (opportunity != null) { var contactCrossover = opportunity.GetRelatedEntities(XrmContext, new Relationship("adx_opportunity_contact")).FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid")); var oppnote = new Entity("adx_opportunitynote"); if (contactCrossover == null) { XrmContext.AddLink(opportunity, new Relationship("adx_opportunity_contact"), contact); oppnote.SetAttributeValue("adx_name", "Contact Added: " + contact.GetAttributeValue <string>("fullname")); oppnote.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote.SetAttributeValue("adx_description", "Contact Added: " + contact.GetAttributeValue <string>("fullname")); oppnote.SetAttributeValue("adx_opportunityid", opportunity.ToEntityReference()); var assignedToContact = opportunity.GetRelatedEntity(XrmContext, new Relationship("msa_contact_opportunity")); oppnote.SetAttributeValue("adx_assignedto", assignedToContact != null ? assignedToContact.GetAttributeValue <string>("fullname") : string.Empty); XrmContext.AddObject(oppnote); XrmContext.UpdateObject(opportunity); } } contact.SetAttributeValue("msa_managingpartnerid", parentCustomerAccount.ToEntityReference()); if (account != null) { contact.SetAttributeValue("parentcustomerid", account.ToEntityReference()); XrmContext.UpdateObject(account); } XrmContext.UpdateObject(contact); if (SetAsPrimary) { if (account == null) { throw new Exception(string.Format("An account with the account ID equal to {0} couldn’t be found.", accountId)); } account.SetAttributeValue("primarycontactid", contact.ToEntityReference()); XrmContext.UpdateObject(account); } XrmContext.SaveChanges(); if (opportunity != null) { var url = GetUrlForRequiredSiteMarker("Opportunity Details"); url.QueryString.Set("OpportunityID", opportunity.GetAttributeValue <Guid>("opportunityid").ToString()); Response.Redirect(url.PathWithQueryString); } else if (ReturnToAccount) { if (account == null) { throw new Exception(string.Format("An account with the account ID equal to {0} couldn’t be found.", accountId)); } var url = GetUrlForRequiredSiteMarker("Edit Customer Account"); url.QueryString.Set("AccountID", account.Id.ToString()); Response.Redirect(url.PathWithQueryString); } else if (FromCreateOpportunity) { if (account == null) { throw new Exception(string.Format("An account with the account ID equal to {0} couldn’t be found.", accountId)); } var url = GetUrlForRequiredSiteMarker("Create Opportunity"); url.QueryString.Set("AccountId", account.Id.ToString()); Response.Redirect(url.PathWithQueryString); } else { var url = GetUrlForRequiredSiteMarker("Manage Customer Contacts"); Response.Redirect(url.PathWithQueryString); } }
protected void SaveButton_Click(object sender, EventArgs args) { foreach (GridViewRow row in NewOpportunitiesList.Rows) { var dataKey = new Guid(NewOpportunitiesList.DataKeys[row.RowIndex].Value.ToString()); var cellCount = row.Cells.Count; var acceptCell = row.Cells[cellCount - 2]; var accept = acceptCell.FindControl(dataKey + "_accept") as CheckBox; var declineCell = row.Cells[cellCount - 1]; var decline = declineCell.FindControl(dataKey + "_decline") as CheckBox; var opportunity = XrmContext.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue <Guid>("opportunityid") == dataKey); if (SavedOpportunities.Contains(dataKey.ToString()) || (!accept.Checked && !decline.Checked) || (accept.Checked && decline.Checked)) { continue; } var partnerReference = opportunity.GetAttributeValue <EntityReference>("msa_partnerid"); if (partnerReference == null) { continue; } var partner = XrmContext.CreateQuery("account").First(a => a.GetAttributeValue <Guid>("accountid") == partnerReference.Id); var oppPermissions = XrmContext.GetOpportunityAccessByContactForParentAccount(Contact).Where(oa => oa.GetAttributeValue <bool?>("adx_acceptdecline").GetValueOrDefault(false)); if (partner.GetAttributeValue <int?>("adx_numberofopportunitiesdelivered").GetValueOrDefault(0) == 0) { partner.SetAttributeValue("adx_numberofopportunitiesdelivered", 1); } var touchrate = (double)(partner.GetAttributeValue <int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(0) + (partner.GetAttributeValue <int?>("adx_numberofopportunitiesdeclined").GetValueOrDefault(0))) / (partner.GetAttributeValue <int?>("adx_numberofopportunitiesdelivered").GetValueOrDefault(1)); partner.SetAttributeValue("adx_touchrate", touchrate); if (accept.Checked) { if (oppPermissions.ToList().Any()) { //we mark this opportunity as accepted opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Accepted)); opportunity.SetAttributeValue("stepname", OpportunityHistory.PipelinePhaseAccepted); opportunity.SetAttributeValue("adx_accepteddate", DateTime.UtcNow); partner.SetAttributeValue("adx_numberofopportunitiesaccepted", partner.GetAttributeValue <int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(0) + 1); } } else if (decline.Checked) { if (oppPermissions.ToList().Any()) { //we mark this opportunity as declined opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Declined)); opportunity.SetAttributeValue("stepname", OpportunityHistory.PipelinePhaseDeclined); partner.SetAttributeValue("adx_numberofopportunitiesdeclined", partner.GetAttributeValue <int?>("adx_numberofopportunitiesdeclined").GetValueOrDefault(0) + 1); partner.SetAttributeValue("adx_activeopportunitycount", partner.GetAttributeValue <int?>("adx_activeopportunitycount").GetValueOrDefault(0) - 1); XrmContext.AddLink(opportunity, new Relationship("adx_account_declinedopportunity"), partner); } } opportunity.SetAttributeValue("adx_expirydate", null); XrmContext.UpdateObject(opportunity); XrmContext.UpdateObject(partner); XrmContext.SaveChanges(); SavedOpportunities += dataKey + ","; } RestoreCheckedValues(); //Response.Redirect(Request.RawUrl); }