Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        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;
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
        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);
        }
Esempio n. 5
0
        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);
        }
Esempio n. 6
0
        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);
        }
Esempio n. 7
0
 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);
     }
 }
Esempio n. 8
0
        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();
        }
Esempio n. 9
0
        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;
                }
            }
        }
Esempio n. 10
0
        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;
            }
        }
Esempio n. 11
0
        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);
            }
        }
Esempio n. 12
0
        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);
        }
Esempio n. 13
0
        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;
        }
Esempio n. 14
0
        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 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);
        }