Esempio n. 1
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("Could not 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("Could not find account with accountid equal to '{0}'", 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;
        }
Esempio n. 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (IsPostBack)
            {
                return;
            }

            StartDate.SelectedDate = DateTime.Today;
            EndDate.SelectedDate   = DateTime.Today.AddDays(7);

            var services = XrmContext.CreateQuery("service").Where(s => s.GetAttributeValue <bool?>("isschedulable").GetValueOrDefault(false) && s.GetAttributeValue <string>("description").Contains("*WEB*")).ToList();

            if (!services.Any())
            {
                SearchPanel.Visible       = false;
                NoServicesMessage.Visible = true;

                return;
            }

            BindServicesDropDown(services);
            BindTimeZoneDropDown();
            BindTimeDropDowns();
        }
Esempio n. 4
0
        protected void PopulateMarketingLists()
        {
            if (Website == null)
            {
                MarketingLists.Visible = false;
                return;
            }

            var website = XrmContext.CreateQuery("adx_website").FirstOrDefault(w => w.GetAttributeValue <Guid>("adx_websiteid") == Website.Id);

            if (website == null)
            {
                MarketingLists.Visible = false;
                return;
            }

            // Note: Marketing Lists with 'Dynamic' Type (i.e. value of 1 or true) do not support manually adding members

            if (website.GetRelatedEntities(XrmContext, new Relationship("adx_website_list")).All(l => l.GetAttributeValue <bool>("type")))
            {
                MarketingLists.Visible = false;
                return;
            }

            MarketingListsListView.DataSource = website.GetRelatedEntities(XrmContext, new Relationship("adx_website_list")).Where(l => l.GetAttributeValue <bool>("type") == false);

            MarketingListsListView.DataBind();
        }
Esempio n. 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Thumbnail.ImageUrl = GetThumbnailUrl(Entity);

            CreateRequestLink.NavigateUrl = GetFirstChildUrl();

            var maxLatestArticlesSetting = ServiceContext.GetSiteSettingValueByName(Website, "service_request_max_kb_articles");

            int maxLatestArticles;

            maxLatestArticles = int.TryParse(maxLatestArticlesSetting, out maxLatestArticles) ? maxLatestArticles : 3;

            var latestArticles = Enumerable.Empty <Entity>().AsQueryable();

            var subject = Entity.GetAttributeValue <EntityReference>("adx_subjectid");

            if (subject != null)
            {
                latestArticles = XrmContext.CreateQuery("kbarticle")
                                 .Where(k => k.GetAttributeValue <OptionSetValue>("statecode") != null &&
                                        k.GetAttributeValue <OptionSetValue>("statecode").Value == (int)Enums.KbArticleState.Published &&
                                        k.GetAttributeValue <bool?>("msa_publishtoweb").GetValueOrDefault(false) &&
                                        k.GetAttributeValue <EntityReference>("subjectid").Id == subject.Id)
                                 .OrderByDescending(k => k.GetAttributeValue <DateTime>("createdon"))
                                 .Take(maxLatestArticles);
            }

            LatestArticlesList.DataSource = latestArticles;
            LatestArticlesList.DataBind();
        }
Esempio n. 6
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. 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();
            RedirectToLoginIfNecessary();

            service = new OrganizationService("Xrm");
            Guid id;

            if (Guid.TryParse(Request.QueryString["id"], out id))
            {
                XrmContext.CreateQuery("new_gift").FirstOrDefault(c => c.GetAttributeValue <Guid>("new_giftid") == id);
            }

            Guid            giftGuid = id;
            QueryExpression qe       = new QueryExpression("annotation");

            qe.ColumnSet.AllColumns = true;
            qe.Criteria.AddCondition("objectid", ConditionOperator.Equal, giftGuid);
            qe.ColumnSet.AddColumn("documentbody");
            EntityCollection ec = service.RetrieveMultiple(qe);

            if (ec.Entities.Count > 0)
            {
                byte[] fil          = Convert.FromBase64String(ec.Entities[0].Attributes["documentbody"].ToString());
                string base64String = Convert.ToBase64String(fil, 0, fil.Length);
                giftimage.ImageUrl = "data:image/jpeg;base64," + base64String;
            }
        }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                var returnUrl = string.Format("{0}?id={1}", ServiceContext.GetUrl(Entity), Request.QueryString["id"]);

                Response.Redirect(string.Format("~/login?ReturnUrl={0}", HttpUtility.UrlEncode(returnUrl)));

                return;
            }
            if (SessionEventScheduleID == null)
            {
                SessionScheduleNotFoundMessage.Visible = true;
                FeedbackFormPanel.Visible = false;
            }

            var schedule = XrmContext.CreateQuery("adx_eventschedule").FirstOrDefault(en => en.GetAttributeValue <Guid>("adx_eventscheduleid") == SessionEventScheduleID);

            EventName.Text = GetEventNameFromSchedule(XrmContext, schedule);

            if (schedule != null)
            {
                EventDate.Text = String.Format("{0:r}", schedule.GetAttributeValue <DateTime>("adx_starttime"));
            }
        }
        protected void OnItemUpdating(object sender, CrmEntityFormViewUpdatingEventArgs e)
        {
            if (PrimaryContactList.SelectedItem == null || PrimaryContactList.SelectedIndex == 0)
            {
                e.Values["primarycontactid"] = null;

                return;
            }

            Guid contactId;

            if (!Guid.TryParse(PrimaryContactList.SelectedItem.Value, out contactId))
            {
                return;
            }

            var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == contactId);

            if (contact == null)
            {
                throw new ApplicationException(string.Format("Couldn't find contact with contactid equal to {0}.", contactId));
            }

            e.Values["primarycontactid"] = contact.ToEntityReference();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();
            RedirectToLoginIfNecessary();

            service = new OrganizationService("Xrm");

            var portalContext = Microsoft.Xrm.Portal.Configuration.PortalCrmConfigurationManager.CreatePortalContext();

            var contact = portalContext.User;

            //var redemreqs = Enumerable.Empty<Entity>();
            //var searchQuery = Request["query"];
            //Guid giftid;

            string WebUrl = WebConfigurationManager.ConnectionStrings["Xrm"].ConnectionString;
            int    index  = WebUrl.IndexOf("=") + 1;
            int    index2 = WebUrl.IndexOf(";");

            WebUrl = WebUrl.Substring(index, index2 - index);
            //UrlHelper urlhelper;

            var redemreqs =
                from r in XrmContext.CreateQuery("new_redemptionrequest")
                join g in XrmContext.CreateQuery("new_gift") on r.GetAttributeValue <EntityReference>("new_gift").Id equals
                g.GetAttributeValue <Guid>("new_giftid")
                    where r.GetAttributeValue <EntityReference>("new_gift") != null
                    where
                r.GetAttributeValue <EntityReference>("new_contact").Id == contact.Id &&
                r.GetAttributeValue <bool>("new_isused") == false
                select new
            {
                redemreqid  = r.Id,
                EntityImage = "data:image/png;base64," + Convert.ToBase64String(g.GetAttributeValue <byte[]>("entityimage")),
                code        = r.GetAttributeValue <string>("new_name"),
                giftName    = g.GetAttributeValue <string>("new_name")
            };

            _redemreqs = EnumerableExtensions.CopyToDataTable(redemreqs);

            /*
             * _redemreqs = EnumerableExtensions.CopyToDataTable(redemreqs.Select(redemreq => new
             * {
             *  redemreqid = redemreq.GetAttributeValue<Guid>("new_redemptionrequestid"),
             *  //Image = gift.GetRelatedEntity(ServiceContext, new Relationship("new_gift_Annotations")) != null ? gift.GetRelatedEntity(ServiceContext, new Relationship("new_gift_Annotations")).GetAttributeValue<string>("documentbody") : " ",
             *  //EntityImage = WebUrl + redemreq.GetAttributeValue<string>("entityimage_url"),
             *  //EntityImage = WebUrl + redemreq.GetRelatedEntity(ServiceContext, new Relationship("new_new_gift_new_redemptionrequest_Gift")) != null ? redemreq.GetRelatedEntity(ServiceContext, new Relationship("new_new_gift_new_redemptionrequest_Gift")).GetAttributeValue<string>("entityimage_url") : " ",
             *  Code = redemreq.GetAttributeValue<string>("new_name"),
             *  GiftName = redemreq.GetRelatedEntity(ServiceContext, "new_new_gift_new_redemptionrequest_Gift") != null ? redemreq.GetRelatedEntity(ServiceContext, "new_new_gift_new_redemptionrequest_Gift").GetAttributeValue<string>("new_name") : " ",
             * }));//.OrderBy(gift => gift.GiftName));
             */
            _redemreqs.Columns["EntityImage"].ColumnName = "Gift Image";
            _redemreqs.Columns["Code"].ColumnName        = "Redemption No.";
            _redemreqs.Columns["GiftName"].ColumnName    = "Gift Name";

            MyGiftListView.DataKeyNames = new[] { "redemreqid" };
            MyGiftListView.DataSource   = _redemreqs;
            MyGiftListView.DataBind();
        }
        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);
        }
Esempio n. 12
0
        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);
        }
Esempio n. 13
0
        protected void Page_Load(object sender, EventArgs args)
        {
            if (Entity.LogicalName != "adx_webpage")
            {
                return;
            }

            var webPage = XrmContext.CreateQuery("adx_webpage")
                          .FirstOrDefault(e => e.GetAttributeValue <Guid>("adx_webpageid") == Entity.Id);

            if (webPage == null)
            {
                return;
            }

            var subject = webPage.GetAttributeValue <EntityReference>("adx_subjectid");

            if (subject == null)
            {
                MostPopularArticlesSearchData.Query =
                    Html.Setting("knowledgebase/search/query", "adx_averagerating_int:5^5 adx_averagerating_int:4^4 adx_averagerating_int:3 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5");
            }
            else
            {
                MostPopularArticlesSearchData.SelectParameters.Add("subjectid", subject.Id.ToString());

                MostPopularArticlesSearchData.Query =
                    Html.Setting("knowledgebase/search/querywithsubject", "adx_averagerating_int:5^5 adx_averagerating_int:4^4 adx_averagerating_int:3 +subjectid:@subjectid~0.99 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5");
            }

            var now = DateTime.UtcNow;

            MostPopularArticlesSearchData.SelectParameters.Add("thisyear", now.ToString("yyyy"));
            MostPopularArticlesSearchData.SelectParameters.Add("1yearago", now.AddYears(-1).ToString("yyyy"));
            MostPopularArticlesSearchData.SelectParameters.Add("2yearsago", now.AddYears(-2).ToString("yyyy"));
            MostPopularArticlesSearchData.SelectParameters.Add("3yearsago", now.AddYears(-3).ToString("yyyy"));
            MostPopularArticlesSearchData.SelectParameters.Add("4yearsago", now.AddYears(-4).ToString("yyyy"));
            MostPopularArticlesSearchData.SelectParameters.Add("5yearsago", now.AddYears(-5).ToString("yyyy"));

            if (subject == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(SearchData.Query))
            {
                SearchData.Query = "+subjectid:@subjectid~0.99 +msa_publishtoweb:1 createdon.year:@thisyear^2 createdon.year:@1yearago createdon.year:@2yearsago^0.5";
            }

            SearchData.SelectParameters.Add("subjectid", subject.Id.ToString());
            SearchData.SelectParameters.Add("thisyear", now.ToString("yyyy"));
            SearchData.SelectParameters.Add("1yearago", now.AddYears(-1).ToString("yyyy"));
            SearchData.SelectParameters.Add("2yearsago", now.AddYears(-2).ToString("yyyy"));
            SearchData.SelectParameters.Add("3yearsago", now.AddYears(-3).ToString("yyyy"));
            SearchData.SelectParameters.Add("4yearsago", now.AddYears(-4).ToString("yyyy"));
            SearchData.SelectParameters.Add("5yearsago", now.AddYears(-5).ToString("yyyy"));

            SubjectSearch.Visible = true;
        }
        private Entity GetPrimaryContactAndSetCompanyName()
        {
            if (OpenOpportunity == null)
            {
                return(null);
            }

            Entity primaryContact = null;

            var customer = OpenOpportunity.GetAttributeValue <EntityReference>("customerid");

            if (customer.LogicalName == "account")
            {
                var account = XrmContext.CreateQuery("account").First(a => a.GetAttributeValue <Guid>("accountid") == customer.Id);

                CompanyName.Text = account.GetAttributeValue <string>("name");

                primaryContact = account.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact"));

                var channelPermission = XrmContext.GetChannelAccessByContact(Contact);

                var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue <bool?>("adx_write").GetValueOrDefault(false));

                var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue <bool?>("adx_read").GetValueOrDefault(false));

                var parentAccount = (account.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null) ? XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == account.GetAttributeValue <EntityReference>("msa_managingpartnerid").Id) : null;

                if (parentAccount != null && ((channelPermission != null && channelPermission.GetAttributeValue <EntityReference>("adx_accountid") != null) && channelPermission.GetAttributeValue <EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference())) && (parentAccount.GetAttributeValue <OptionSetValue>("accountclassificationcode") != null && parentAccount.GetAttributeValue <OptionSetValue>("accountclassificationcode").Value == 100000000))
                {
                    if (channelWriteAccess)
                    {
                        CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>",
                                                         HttpUtility.HtmlEncode(EditAccountUrl(account.GetAttributeValue <Guid>("accountid"))),
                                                         HttpUtility.HtmlEncode(CompanyName.Text));
                    }
                    else if (channelReadAccess)
                    {
                        CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>",
                                                         HttpUtility.HtmlEncode(ReadOnlyAccountUrl(account.GetAttributeValue <Guid>("accountid"))),
                                                         HttpUtility.HtmlEncode(CompanyName.Text));
                    }
                }


                //CompanyName.Attributes.Add("style", "white-space: nowrap;");
            }
            else if (customer.LogicalName == "contact")
            {
                primaryContact = XrmContext.CreateQuery("contact").First(c => c.GetAttributeValue <Guid>("contactid") == customer.Id);

                var account = primaryContact.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact"));

                CompanyName.Text = account != null?account.GetAttributeValue <string>("name") : primaryContact.GetAttributeValue <string>("adx_organizationname");
            }

            return(primaryContact);
        }
Esempio n. 15
0
        private void PopulatePlanPackageList()
        {
            PlanPackageList.Items.Clear();

            var supportRequest = XrmContext.CreateQuery("adx_supportrequest")
                                 .FirstOrDefault(sr => sr.GetAttributeValue <Guid>("adx_supportrequestid") == CurrentStepEntityID);

            if (supportRequest == null)
            {
                throw new ApplicationException(string.Format("Could not find support request record with id equal to {0}", CurrentStepEntityID));
            }
            var supportRequestProductReference = supportRequest.GetAttributeValue <EntityReference>("adx_product");
            var parentProduct = supportRequestProductReference == null ? null : XrmContext.CreateQuery("product").FirstOrDefault(pp => pp.GetAttributeValue <Guid>("productid") == supportRequestProductReference.Id);
            IQueryable <Entity> supportProducts;

            if (parentProduct != null)
            {
                supportProducts = from product in XrmContext.CreateQuery("product")
                                  join supportedset in XrmContext.CreateQuery("adx_supportedproduct_productplan") on product.GetAttributeValue <Guid>("productid") equals supportedset.GetAttributeValue <Guid>("productidone")
                                  join supportedProduct in XrmContext.CreateQuery("product") on supportedset.GetAttributeValue <Guid>("productidtwo") equals supportedProduct.GetAttributeValue <Guid>("productid")
                                      where product.GetAttributeValue <OptionSetValue>("statecode") != null && product.GetAttributeValue <OptionSetValue>("statecode").Value == 0
                                      where product.GetAttributeValue <Guid>("productid") == parentProduct.GetAttributeValue <Guid>("productid")
                                      where supportedProduct.GetAttributeValue <OptionSetValue>("producttypecode") != null && supportedProduct.GetAttributeValue <OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan
                                  select supportedProduct;
            }
            else
            {
                supportProducts = XrmContext.CreateQuery("product").Where(p => p.GetAttributeValue <OptionSetValue>("statecode") != null && p.GetAttributeValue <OptionSetValue>("statecode").Value == 0 && p.GetAttributeValue <OptionSetValue>("producttypecode") != null && p.GetAttributeValue <OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.SupportPlan);
            }

            foreach (var supportProduct in supportProducts)
            {
                var supportUnit =
                    XrmContext.CreateQuery("uomschedule").FirstOrDefault(unit => unit.GetAttributeValue <Guid>("uomscheduleid") == (supportProduct.GetAttributeValue <EntityReference>("defaultuomscheduleid") == null ? Guid.Empty : supportProduct.GetAttributeValue <EntityReference>("defaultuomscheduleid").Id));

                var baseUom = XrmContext.CreateQuery("uom").FirstOrDefault(baseuom => baseuom.GetAttributeValue <string>("name") == supportUnit.GetAttributeValue <string>("baseuomname"));

                var uoms = XrmContext.CreateQuery("uom").Where(uom => uom.GetAttributeValue <Guid>("baseuom") == baseUom.Id);

                foreach (var u in uoms)
                {
                    var amount        = new Money(0);
                    var priceListItem = XrmContext.GetPriceListItemByPriceListNameAndUom(supportProduct.GetAttributeValue <Guid>("productid"), u.Id, PriceListName);

                    if (priceListItem != null)
                    {
                        amount = priceListItem.GetAttributeValue <Money>("amount");
                    }

                    PlanPackageList.Items.Add(new ListItem(
                                                  string.Format("{0} - {1} - {2}", supportProduct.GetAttributeValue <string>("name"), u.GetAttributeValue <string>("name"), amount.Value.ToString("c0")),
                                                  string.Format("{0}&{1}", supportProduct.GetAttributeValue <Guid>("productid"), u.GetAttributeValue <Guid>("uomid"))
                                                  ));
                }
            }
        }
Esempio n. 16
0
        protected void OnItemInserting(object sender, CrmEntityFormViewInsertingEventArgs e)
        {
            var schedule = XrmContext.CreateQuery("adx_eventschedule").FirstOrDefault(sn => sn.GetAttributeValue <Guid>("adx_eventscheduleid") == SessionEventScheduleID);

            e.Values["adx_name"]       = GetEventNameFromSchedule(XrmContext, schedule) + " session feedback from " + Contact.GetAttributeValue <string>("fullname");
            e.Values["adx_attendeeid"] = Contact.ToEntityReference();
            if (schedule != null)
            {
                e.Values["adx_eventscheduleid"] = schedule.ToEntityReference();
            }
        }
Esempio n. 17
0
        protected void Page_Load(object sender, EventArgs args)
        {
            if (IsPostBack)
            {
                return;
            }

            var dataAdapter = new UserCasesDataAdapter(new Adxstudio.Xrm.Cases.PortalContextDataAdapterDependencies(Portal, PortalName, Request.RequestContext));

            var permissionScopes = dataAdapter.SelectPermissionScopes();

            HideControlsBasedOnAccess(permissionScopes);

            var supportedProducts = XrmContext.CreateQuery("product")
                                    .Where(e => e.GetAttributeValue <OptionSetValue>("producttypecode") != null && e.GetAttributeValue <OptionSetValue>("producttypecode").Value == (int)ProductTypeCode.Supported)
                                    .OrderBy(e => e.GetAttributeValue <string>("name"))
                                    .ToArray();

            Product.DataSource     = supportedProducts.Select(e => new ListItem(e.GetAttributeValue <string>("name"), e.GetAttributeValue <Guid>("productid").ToString()));
            Product.DataTextField  = "Text";
            Product.DataValueField = "Value";
            Product.DataBind();

            if (supportedProducts.Length < 2)
            {
                Product.Visible = false;
            }

            var subject = Request.QueryString["subject"];

            if (!string.IsNullOrEmpty(subject))
            {
                Subject.Text = subject;
                ClearSearchButton.Visible = true;
                Deflection.Visible        = true;
            }

            Guid productId;

            if (Guid.TryParse(Request.QueryString["product"], out productId))
            {
                Product.SelectedValue = productId.ToString();

                SearchData.Query = "(+_logicalname:incident~0.9^2 +statecode:@resolvedincidentstatecode +productid:@product~0.9 +(@subject)) OR (-_logicalname:incident~0.9 +(@subject))";
            }
            else
            {
                SetProductSelectedValue();
            }

            Subject.Attributes["onkeydown"] = OnEnterKeyDownThenClick(SearchButton);
        }
Esempio n. 18
0
        protected void CancelService(Guid activityID)
        {
            var appointment = XrmContext.CreateQuery("serviceappointment").FirstOrDefault(a => a.GetAttributeValue <Guid>("activityid") == activityID);

            if (appointment == null)
            {
                return;
            }

            XrmContext.SetState((int)ServiceAppointmentState.Canceled, -1, appointment);

            Response.Redirect(Request.RawUrl);
        }
Esempio n. 19
0
        private string GetProductUrl(Entity product)
        {
            if (product == null || product.GetAttributeValue <EntityReference>("subjectid") == null)
            {
                return(null);
            }

            var productPage = XrmContext.CreateQuery("adx_webpage")
                              .FirstOrDefault(e => e.GetAttributeValue <EntityReference>("adx_subjectid") == product.GetAttributeValue <EntityReference>("subjectid") &&
                                              e.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference());

            return(productPage == null ? null : XrmContext.GetUrl(productPage));
        }
Esempio n. 20
0
        private void BindTimeZoneDropDown()
        {
            TimeZoneSelection.DataSource     = XrmContext.CreateQuery("timezonedefinition").OrderByDescending(t => t.GetAttributeValue <string>("userinterfacename")).Select(t => new ListItem(t.GetAttributeValue <string>("userinterfacename"), t.GetAttributeValue <int>("timezonecode").ToString(CultureInfo.InvariantCulture)));
            TimeZoneSelection.DataTextField  = "Text";
            TimeZoneSelection.DataValueField = "Value";
            TimeZoneSelection.DataBind();

            TimeZoneSelection.Items.Insert(0, new ListItem("Please Select One..."));

            if (Contact.GetAttributeValue <int?>("adx_timezone").HasValue)
            {
                TimeZoneSelection.SelectedValue = Contact.GetAttributeValue <int?>("adx_timezone").ToString();
            }
        }
        public bool IsListChecked(object listoption)
        {
            var list = (Entity)listoption;

            if (Request.IsAuthenticated)
            {
                var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == Contact.Id);

                return(contact != null &&
                       contact.GetRelatedEntities(XrmContext, new Relationship("listcontact_association"))
                       .Any(l => l.GetAttributeValue <Guid>("listid") == list.Id));
            }

            return(false);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();
            RedirectToLoginIfNecessary();

            service = new OrganizationService("Xrm");
            Guid id;

            if (Guid.TryParse(Request.QueryString["id"], out id))
            {
                XrmContext.CreateQuery("adx_membership").FirstOrDefault(c => c.GetAttributeValue <Guid>("adx_membershipid") == id);
            }

            Guid            redeemGuid = id;
            QueryExpression qe         = new QueryExpression("adx_membership");

            qe.ColumnSet.AllColumns = true;
            EntityCollection ec = service.RetrieveMultiple(qe);

            if (ec.Entities.Count > 0)
            {
                // img_qrcode
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                string        encoding      = ec.Entities[0]["adx_membershipid"].ToString();
                qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeScale        = 3;
                qrCodeEncoder.QRCodeVersion      = 7;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;

                var bw         = new ZXing.BarcodeWriter();
                var encOptions = new ZXing.Common.EncodingOptions()
                {
                    Width = 150, Height = 150, Margin = 0
                };
                bw.Options = encOptions;
                bw.Format  = ZXing.BarcodeFormat.QR_CODE;
                var          result  = new Bitmap(bw.Write(encoding));
                MemoryStream _stream = new MemoryStream();
                result.Save(_stream, ImageFormat.Jpeg);
                result.Dispose();

                ImageConverter converter    = new ImageConverter();
                byte[]         qrByte       = (byte[])converter.ConvertTo(new Bitmap(_stream), typeof(byte[]));
                string         base64String = Convert.ToBase64String(qrByte, 0, qrByte.Length);
                membershipQrImage.ImageUrl = "data:image/jpeg;base64," + base64String;
            }
        }
Esempio n. 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request["serviceid"]))
            {
                var page = ServiceContext.GetPageBySiteMarkerName(Website, "View Scheduled Services");

                Response.Redirect(ServiceContext.GetUrl(page));
            }

            var scheduledActivity   = XrmContext.CreateQuery("serviceappointment").First(s => s.GetAttributeValue <Guid>("activityid") == new Guid(Request["serviceid"]));
            var userTimeZone        = Contact.GetAttributeValue <int?>("adx_timezone").GetValueOrDefault();
            var timeZone            = XrmContext.CreateQuery("timezonedefinition").First(t => t.GetAttributeValue <int>("timezonecode") == userTimeZone);
            var usersMinutesFromGmt = GetUsersMinutesFromGmt(userTimeZone, XrmContext);

            serviceType.Text = scheduledActivity.GetRelatedEntity(XrmContext, new Relationship("service_service_appointments")).GetAttributeValue <string>("name");
            startTime.Text   = string.Format("{0} ({1})", scheduledActivity.GetAttributeValue <DateTime?>("scheduledstart").GetValueOrDefault().AddMinutes(usersMinutesFromGmt), timeZone.GetAttributeValue <string>("standardname"));
            endTime.Text     = string.Format("{0} ({1})", scheduledActivity.GetAttributeValue <DateTime?>("scheduledend").GetValueOrDefault().AddMinutes(usersMinutesFromGmt), timeZone.GetAttributeValue <string>("standardname"));
        }
Esempio n. 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();
            RedirectToLoginIfNecessary();

            service = new OrganizationService("Xrm");

            //var gifts = Enumerable.Empty<Entity>();

            //var searchQuery = Request["query"];
            //Guid giftid;

            DateTime startdate = new DateTime(DateTime.Today.Year, 1, 1, 0, 0, 1);

            DateTime enddate = new DateTime(DateTime.Today.Year, 12, 31, 23, 59, 50);

            string WebUrl = WebConfigurationManager.ConnectionStrings["Xrm"].ConnectionString;
            int    index  = WebUrl.IndexOf("=") + 1;
            int    index2 = WebUrl.IndexOf(";");

            WebUrl = WebUrl.Substring(index, index2 - index);
            var gifts = from g in XrmContext.CreateQuery("new_gift")
                        join n in XrmContext.CreateQuery("annotation")
                        on g.GetAttributeValue <Guid>("new_giftid") equals n.GetAttributeValue <EntityReference>("objectid").Id
                            where g.GetAttributeValue <DateTime>("new_redemptionstartdate") >= startdate &&
                        g.GetAttributeValue <DateTime>("new_redemptionenddate") <= enddate
                        select new
            {
                giftid        = g.Id,
                EntityImage   = "data:image/png;base64," + Convert.ToBase64String(g.GetAttributeValue <byte[]>("entityimage")),
                GiftName      = g.GetAttributeValue <string>("new_name"),
                PointRequired = Convert.ToInt32(g.GetAttributeValue <decimal>("new_pointsrequired")).ToString("N2")
            };

            _gifts = EnumerableExtensions.CopyToDataTable(gifts);

            _gifts.Columns["EntityImage"].ColumnName   = "Gift Image";
            _gifts.Columns["GiftName"].ColumnName      = "Gift Name";
            _gifts.Columns["PointRequired"].ColumnName = "Points Required";

            GiftListView.DataKeyNames = new[] { "giftid" };
            GiftListView.DataSource   = _gifts;
            GiftListView.DataBind();
        }
Esempio n. 25
0
        protected void Page_Load(object sender, EventArgs args)
        {
            var query = from jp in XrmContext.CreateQuery("adx_jobposting")
                        where jp.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference()
                        where jp.GetAttributeValue <OptionSetValue>("statecode") != null && jp.GetAttributeValue <OptionSetValue>("statecode").Value == 0
                        orderby jp.GetAttributeValue <string>("adx_name")
                        select new
            {
                Id          = jp.GetAttributeValue <Guid>("adx_jobpostingid"),
                Name        = jp.GetAttributeValue <string>("adx_name"),
                Description = jp.GetAttributeValue <string>("adx_description"),
                ClosingOn   = jp.GetAttributeValue <DateTime?>("adx_closingon")
            };

            var postings = query.ToArray().Where(e => IsOpen(e.ClosingOn));

            JobPostings.DataSource = postings;
            JobPostings.DataBind();
        }
        protected void OnItemInserting(object sender, CrmEntityFormViewInsertingEventArgs e)
        {
            var currentContact = XrmContext.MergeClone(Contact);

            if (currentContact == null)
            {
                return;
            }

            var contactParentCustomerAccount = currentContact.GetRelatedEntity(XrmContext, new Relationship("contact_customer_accounts"));

            if (contactParentCustomerAccount != null)
            {
                e.Values["msa_partnerid"] = contactParentCustomerAccount.ToEntityReference();
            }

            e.Values["msa_partneroppid"] = currentContact.ToEntityReference();

            e.Values["adx_createdbyusername"] = Contact.GetAttributeValue <string>("fullname");

            // e.Values["adx_createdbyipaddress"] = Request.UserHostAddress ?? "";

            e.Values["adx_partnercreated"] = true;

            // If no estimated revenue was submitted, leave as system-calculated.

            e.Values["isrevenuesystemcalculated"] = (!e.Values.ContainsKey("estimatedvalue")) || (e.Values["estimatedvalue"] == null);

            Guid accountId;

            if ((Account_dropdown.SelectedItem == null || Account_dropdown.SelectedIndex == 0) || !Guid.TryParse(Account_dropdown.SelectedItem.Value, out accountId))
            {
                return;
            }

            var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == accountId);

            if (account != null)
            {
                e.Values["customerid"] = account.ToEntityReference();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (ForceRegistration && !ServiceContext.ValidateProfileSuccessfullySaved(Contact))
            {
                MissingFieldsMessage.Visible = true;
            }

            if (ShowMarketingOptionsPanel)
            {
                MarketingOptionsPanel.Visible = true;
            }

            ProfileDataSource.FetchXml = _userFetchXmlFormat.FormatWith(Contact.Id);

            ProfileAlertInstructions.Visible = Contact.GetAttributeValue <bool?>("adx_profilealert") ?? false;

            if (IsPostBack)
            {
                return;
            }

            var contact = XrmContext.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == Contact.Id);

            if (contact == null)
            {
                throw new ApplicationException(string.Format("Couldn't retrieve contact record with contactid equal to {0}.", Contact.Id));
            }

            if (ShowMarketingOptionsPanel)
            {
                marketEmail.Checked = !contact.GetAttributeValue <bool>("donotemail");
                marketFax.Checked   = !contact.GetAttributeValue <bool>("donotfax");
                marketPhone.Checked = !contact.GetAttributeValue <bool>("donotphone");
                marketMail.Checked  = !contact.GetAttributeValue <bool>("donotpostalmail");
            }

            PopulateMarketingLists();
        }
Esempio n. 28
0
        private void construct_processFlow()
        {
            Guid entityid = new Guid(Request.QueryString["id"]); // get the id of the entity from the page request params

            if (entityname == null)
            {
                EntityReference adx_form_ref = Entity.GetAttributeValue <EntityReference>("adx_entityform"); //get lookup field adx_entityform from the actuel page
                if (adx_form_ref != null)
                {
                    IOrganizationService service = (IOrganizationService)XrmContext;
                    ColumnSet            cols    = new ColumnSet(new String[] { "adx_name", "adx_entityname" });
                    Entity adx_form = service.Retrieve(adx_form_ref.LogicalName, adx_form_ref.Id, cols); // get the Entity from the EntityReference object
                    entityname = adx_form.GetAttributeValue <string>("adx_entityname");                  // the entityname of the Entity link to this page
                }
            }
            if (entityname != null)
            {
                var          myEntities      = XrmContext.CreateQuery(entityname).Where(t => (Guid)t[entityname + "id"] == entityid);
                Entity       myEntity        = (Entity)myEntities.First();                       // the Entity link to this page
                Guid         myProcessId     = myEntity.GetAttributeValue <Guid>("processid");   // the processid link to this entity
                var          processes       = XrmContext.CreateQuery("workflow").Where(t => (Guid)t["workflowid"] == myProcessId);
                var          process         = processes.First();                                // the process entity
                Guid         this_stageid    = myEntity.GetAttributeValue <Guid>("stageid");     // the stage id of this entity
                string       clientData_json = process.GetAttributeValue <string>("clientdata"); // the description of the process
                List <Stage> stages          = get_stages(clientData_json);                      // extract the list of stages in order
                ProcessFlow.InnerHtml = "";
                foreach (var stage in stages)
                {
                    HtmlGenericControl p = new HtmlGenericControl("p");
                    p.Attributes["class"] = "btn btn-default";
                    p.InnerHtml           = stage.label;

                    if (new Guid(stage.id) == this_stageid)
                    {
                        p.Attributes["class"] += " status";
                    }
                    ProcessFlow.Controls.Add(p);
                }
            }
        }
Esempio n. 29
0
        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));
        }
Esempio n. 30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (IsPostBack || Contact == null)
            {
                return;
            }

            var query = from eventSchedule in XrmContext.CreateQuery("adx_eventschedule")
                        join @event in XrmContext.CreateQuery("adx_event") on eventSchedule.GetAttributeValue <EntityReference>("adx_eventid").Id equals @event.GetAttributeValue <Guid>("adx_eventid")
                        join eventRegistration in XrmContext.CreateQuery("adx_eventregistration") on @event.GetAttributeValue <EntityReference>("adx_eventid").Id equals eventRegistration.GetAttributeValue <EntityReference>("adx_eventid").Id
                            where @event.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference()
                            where eventSchedule.GetAttributeValue <EntityReference>("adx_eventid") != null
                            where eventRegistration.GetAttributeValue <EntityReference>("adx_eventid") != null && eventRegistration.GetAttributeValue <EntityReference>("adx_attendeeid") == Contact.ToEntityReference()
                        select eventSchedule;

            var eventSchedules = query.ToArray();

            SessionSchedule.DataSource = eventSchedules;
            EmptyPanel.Visible         = !eventSchedules.Any();
        }