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 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 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 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 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 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 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 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 bool CreatePermissions() { var changes = false; var oppPermissions = XrmContext.CreateQuery("adx_opportunitypermissions").FirstOrDefault(op => op.GetAttributeValue <EntityReference>("adx_contactid") != null && op.GetAttributeValue <EntityReference>("adx_contactid").Equals(ContactToEdit.ToEntityReference())); if (oppPermissions == null) { oppPermissions = new Entity("adx_opportunitypermissions"); oppPermissions.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_name", "opportunitity permissions for " + ContactToEdit.GetAttributeValue <string>("fullname")); oppPermissions.SetAttributeValue("adx_contactid", ContactToEdit.ToEntityReference()); oppPermissions.SetAttributeValue("adx_accountid", ContactToEdit.GetAttributeValue <EntityReference>("parentcustomerid")); oppPermissions.SetAttributeValue("adx_scope", new OptionSetValue((int)Enums.OpportunityAccessScope.Self)); oppPermissions.SetAttributeValue("adx_read", true); XrmContext.AddObject(oppPermissions); changes = true; } var channelPermissions = ServiceContext.CreateQuery("adx_channelpermissions").FirstOrDefault(cp => cp.GetAttributeValue <EntityReference>("adx_contactid") != null && cp.GetAttributeValue <EntityReference>("adx_contactid").Equals(ContactToEdit.ToEntityReference())); if (channelPermissions == null) { channelPermissions = new Entity("adx_channelpermissions"); channelPermissions.SetAttributeStringTruncatedToMaxLength(XrmContext, "adx_name", "channel permissions for " + ContactToEdit.GetAttributeValue <string>("fullname")); channelPermissions.SetAttributeValue("adx_contactid", ContactToEdit.ToEntityReference()); channelPermissions.SetAttributeValue("adx_accountid", ContactToEdit.GetAttributeValue <EntityReference>("parentcustomerid")); XrmContext.AddObject(channelPermissions); changes = true; } return(changes); }
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 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 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); }