Exemple #1
0
 private IQueryable BuildContactQuery()
 {
     try
     {
         var query = from contact in _ctx.CreateQuery("contact")
                     join party in _ctx.CreateQuery("account")
                     on contact["parentcustomerid"] equals party["accountid"]
                     where contact["crm_canal"].Equals(CANAL_COMMUNICATION_COURRIER) &&
                     contact["parentcustomerid"] != null &&
                     contact["fullname"] != null &&
                     contact["modifiedon"] != null
                     select new
         {
             contactHash = new ContactMapper(
                 (ContactPartySource)this,
                 ((EntityReference)contact["parentcustomerid"]).Id.ToString(),
                 (string)contact["fullname"],
                 ((DateTime)contact["modifiedon"]))
         };
         return(query);
     }
     catch (Exception Ex)
     {
         var Innermessage = Ex.InnerException != null ? Ex.InnerException.Message : "";
         Console.WriteLine($"[BuildContactQuery] {Ex.Message}  {Innermessage}");
         return(null);
     }
 }
Exemple #2
0
 private IQueryable BuildContactQuery()
 {
     try
     {
         var query = from contact in _ctx.CreateQuery("contact")
                     join role_client in _ctx.CreateQuery("crm_roleclient")
                     on contact["crm_role_client_id"] equals role_client["crm_roleclientid"]
                     join party in _ctx.CreateQuery("account")
                     on role_client["crm_account_id"] equals party["accountid"]
                     join client_facturation in _ctx.CreateQuery("crm_clientdefacturation")
                     on role_client["crm_clientdefacturation_id"] equals client_facturation["crm_clientdefacturationid"]
                     where role_client["crm_role"].Equals(CLIENT_FACTURATION_ROLE) &&
                     contact["crm_canal"].Equals(CANAL_COMMUNICATION_COURRIER) &&
                     contact["fullname"] != null &&
                     party["accountid"] != null &&
                     contact["modifiedon"] != null
                     select new
         {
             contactHash = new ContactMapper(
                 (ContactRoleSource)this,
                 ((Guid)party["accountid"]).ToString(),
                 (string)contact["fullname"],
                 ((DateTime)contact["modifiedon"]))
         };
         return(query);
     }
     catch (Exception Ex)
     {
         var Innermessage = Ex.InnerException != null ? Ex.InnerException.Message : "";
         Console.WriteLine($"[BuildContactQuery] {Ex.Message}  {Innermessage}");
         return(null);
     }
 }
Exemple #3
0
        protected string BuildImageTag(Entity entity)
        {
            const string defaultUrl = "/image-not-available-150x150.png/";
            var          url        = string.Empty;

            if (entity == null || string.IsNullOrWhiteSpace(entity.LogicalName))
            {
                return(string.Empty);
            }

            if (entity.LogicalName == "adx_webpage")
            {
                var webFileReference = entity.GetAttributeValue <EntityReference>("adx_image");
                if (webFileReference == null)
                {
                    var thumbnailURL = entity.GetAttributeValue <string>("adx_imageurl");
                    url = string.IsNullOrWhiteSpace(thumbnailURL) ? string.Empty : thumbnailURL;
                }
                else
                {
                    var webFile = ServiceContext.CreateQuery("adx_webfile").FirstOrDefault(e => e.GetAttributeValue <Guid>("adx_webfileid") == webFileReference.Id);
                    if (webFile != null)
                    {
                        url = ServiceContext.GetUrl(webFile);
                    }
                }

                if (string.IsNullOrWhiteSpace(url))
                {
                    url = defaultUrl;
                }
            }

            return(string.IsNullOrWhiteSpace(url) ? string.Empty : string.Format("<img alt='' src='{0}' runat='server' />", url));
        }
Exemple #4
0
        protected void RedirectToLoginIfNecessary()
        {
            if (Request.IsAuthenticated)
            {
                return;
            }

            var portal = PortalCrmConfigurationManager.CreatePortalContext();

            var portalPage = portal.Entity;

            if (portalPage == null)
            {
                return;
            }

            var webPage = ServiceContext.CreateQuery("adx_webpage").FirstOrDefault(w => w.GetAttributeValue <Guid>("adx_webpageid") == portalPage.Id);

            if (webPage == null || webPage.GetRelatedEntities(ServiceContext, new Relationship("adx_webpage_sitemarker")).Any(s => s.GetAttributeValue <string>("adx_name") == "Login" || s.GetAttributeValue <string>("adx_name") == "Page Not Found"))
            {
                return;
            }

            Response.ForbiddenAndEndResponse();
        }
Exemple #5
0
        private void BindPrimaryContact()
        {
            var empli = new ListItem
            {
                Text = " ",
            };

            PrimaryContactList.Items.Add(empli);

            var contacts = ServiceContext.CreateQuery("contact").Where(c => c.GetAttributeValue <EntityReference>("parentcustomerid") != null && c.GetAttributeValue <EntityReference>("parentcustomerid").Equals(AccountToEdit.ToEntityReference())).ToList();

            foreach (var contact in contacts)
            {
                var li = new ListItem
                {
                    Text  = contact.GetAttributeValue <string>("fullname"),
                    Value = contact.GetAttributeValue <Guid>("contactid").ToString()
                };

                if ((AccountToEdit.GetAttributeValue <EntityReference>("primarycontactid") != null) && (li.Value == AccountToEdit.GetAttributeValue <EntityReference>("primarycontactid").Id.ToString()))
                {
                    li.Selected = true;
                }

                PrimaryContactList.Items.Add(li);
            }

            if (contacts.Count < 1)
            {
                PrimaryContactList.Enabled = false;

                NoContactsExistWarningMessage.Visible = true;
            }
        }
Exemple #6
0
        protected string GetThumbnailUrl(object webpageObject)
        {
            var webpageEntity = webpageObject as Entity;

            if (webpageEntity == null)
            {
                return(null);
            }

            var imageReference = webpageEntity.GetAttributeValue <EntityReference>("adx_image");

            if (imageReference == null)
            {
                return(null);
            }

            var webfile = ServiceContext.CreateQuery("adx_webfile").FirstOrDefault(file => file.GetAttributeValue <Guid>("adx_webfileid") == imageReference.Id);

            if (webfile == null)
            {
                return(null);
            }

            var url = new UrlBuilder(ServiceContext.GetUrl(webfile));

            return(url.PathWithQueryString);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var servicerequestnumber = Request.QueryString[ServiceRequestNumberQueryStringKey];

            if (string.IsNullOrWhiteSpace(servicerequestnumber))
            {
                ErrorPanel.Visible = true;

                return;
            }

            var serviceRequest = ServiceContext.CreateQuery("adx_servicerequest").FirstOrDefault(s => s.GetAttributeValue <string>("adx_servicerequestnumber") == servicerequestnumber);

            if (serviceRequest == null)
            {
                ErrorPanel.Visible = true;

                return;
            }

            ErrorPanel.Visible = false;

            var url = ServiceRequestDetailsUrl(serviceRequest.Id);

            if (url == null)
            {
                return;
            }

            Response.Redirect(url);
        }
Exemple #8
0
        private void PopulateDropDownList(EntityReference managingPartner)
        {
            if (managingPartner == null)
            {
                return;
            }

            CompanyNameList.Items.Add(new ListItem("None"));

            var accounts =
                ServiceContext.CreateQuery("account")
                .Where(
                    a =>
                    a.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null &&
                    a.GetAttributeValue <EntityReference>("msa_managingpartnerid").Equals(managingPartner))
                .OrderBy(a => a.GetAttributeValue <string>("name"));

            foreach (var account in accounts)
            {
                var li = new ListItem
                {
                    Text  = account.GetAttributeValue <string>("name"),
                    Value = account.GetAttributeValue <Guid>("accountid").ToString()
                };

                if ((ParentCustomerAccount != null) && (account.GetAttributeValue <Guid>("accountid") == ParentCustomerAccount.GetAttributeValue <Guid>("accountid")))
                {
                    li.Selected = true;
                }

                CompanyNameList.Items.Add(li);
            }
        }
Exemple #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serviceRequestTypes = ServiceContext.CreateQuery("adx_servicerequesttype").Where(s => s.GetAttributeValue <OptionSetValue>("statecode") != null && s.GetAttributeValue <OptionSetValue>("statecode").Value == 0).OrderBy(s => s.GetAttributeValue <string>("adx_name"));

            ServiceRequestTypesListView.DataSource = serviceRequestTypes;

            ServiceRequestTypesListView.DataBind();
        }
Exemple #10
0
        private DataServiceQuery CreateQuery(string entityName)
        {
            var entitySetName = entityName.InflectTo().Pluralized;
            var entityClrtype = DynamicTypeBuilder.Instance.GetDynamicType(entityName);

            var query = ServiceContext.CreateQuery(entityClrtype, entitySetName);

            return(query);
        }
Exemple #11
0
        protected void Page_Init(object sender, EventArgs e)
        {
            var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider();

            _sponsors = ServiceContext.CreateQuery("adx_eventsponsor")
                        .Where(es => es.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference())
                        .ToArray()
                        .Where(es => securityProvider.TryAssert(ServiceContext, es, CrmEntityRight.Read))
                        .ToArray();
        }
        public object FindByName(string entity, string nameField, string name)
        {
            using (OrganizationServiceProxy proxy = CRMHelper.Connect())
            {
                ServiceContext context = new ServiceContext(proxy);

                return (from s in context.CreateQuery(entity)
                         where s[nameField] == name
                         select s).FirstOrDefault();
            }
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider();

            Speakers.DataSource = ServiceContext.CreateQuery("adx_eventspeaker").Where(es => es.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference()).ToArray()
                                  .Where(es => securityProvider.TryAssert(ServiceContext, es, CrmEntityRight.Read))
                                  .OrderBy(es => es.GetAttributeValue <string>("adx_name"))
                                  .ToArray();

            Speakers.DataBind();
        }
        protected Boolean CheckIfScheduledForCurrentUser(Entity schedule, Guid contactId)
        {
            if (schedule == null)
            {
                return(false);
            }

            var eventSchedule = ServiceContext.CreateQuery("adx_eventschedule").FirstOrDefault(et => et.GetAttributeValue <Guid>("adx_eventscheduleid") == schedule.GetAttributeValue <Guid>("adx_eventscheduleid"));

            return(eventSchedule != null && ServiceContext.CheckIfScheduledForCurrentUser(eventSchedule, contactId));
        }
        private void AddContactDiv(Entity contact)
        {
            var account = (contact.GetAttributeValue <EntityReference>("parentcustomerid") != null) ?
                          ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == (contact.GetAttributeValue <EntityReference>("parentcustomerid") == null ? Guid.Empty : contact.GetAttributeValue <EntityReference>("parentcustomerid").Id)) : null;

            var companyName = account != null?account.GetAttributeValue <string>("name") : contact.GetAttributeValue <string>("adx_organizationname");

            HtmlGenericControl div;

            var channelPermission = ServiceContext.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 != null && account.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null) ?
                                ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == account.GetAttributeValue <EntityReference>("msa_managingpartnerid").Id) : null;

            string contactFormattedString = "";

            if ((parentAccount != null && channelPermission != null && channelPermission.GetAttributeValue <EntityReference>("adx_accountid") != null && (channelPermission.GetAttributeValue <EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference()))) ||
                (contact.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null && channelPermission != null && contact.GetAttributeValue <EntityReference>("msa_managingpartnerid").Equals(channelPermission.GetAttributeValue <EntityReference>("adx_accountid"))))
            {
                if (channelWriteAccess)
                {
                    contactFormattedString = string.Format(@"<i class=""fa fa-edit""></i><a href=""{0}"" class=""Edit"">{1}</a>",
                                                           EditContactUrl(contact.GetAttributeValue <Guid>("contactid")),
                                                           contact.GetAttributeValue <string>("fullname"));
                }
                else if (channelReadAccess)
                {
                    contactFormattedString = string.Format(@"<a href=""{0}"">{1}</a>",
                                                           ReadOnlyContactUrl(contact.GetAttributeValue <Guid>("contactid")),
                                                           contact.GetAttributeValue <string>("fullname"));
                }
            }
            else
            {
                contactFormattedString = contact.GetAttributeValue <string>("fullname");
            }

            div = new HtmlGenericControl("div")
            {
                InnerHtml = string.Format(@"<span class=""contact-name"">{0}</span>{1}",
                                          contactFormattedString,
                                          !string.IsNullOrEmpty(companyName)
                                        ? string.Format(@"<span class=""contact-company-name"">{0}</span>", Server.HtmlEncode(companyName)) : string.Empty)
            };

            // add div at the beginning for reverse chronological order
            OpportunityContactsPlaceHolder.Controls.AddAt(0, div);
        }
        public void LookupMaterial()
        {
            using (OrganizationServiceProxy proxy = CRMHelper.Connect())
            {
                ServiceContext context = new ServiceContext(proxy);

                Entity entity = (from it in context.CreateQuery("new_invoicetype")
                          where it["new_typeidinvoice"] == "07"
                          select it).FirstOrDefault();

                Console.WriteLine(entity.Id);
            }
        }
 public IEnumerable <Processamento> ObterUltimosProcessamentos(int take)
 {
     try
     {
         return
             ((from p in ServiceContext.CreateQuery <Processamento>(Nome)
               select p).Take(take).AsTableServiceQuery().ToList());
     }
     catch (Exception ex)
     {
         throw new RepositorioCloudTableException(
                   String.Format("Erro obtendo os {0} últimos processamentos.", take), ex);
     }
 }
Exemple #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            var polls = ServiceContext.CreateQuery("adx_poll")
                        .Where(p => p.GetAttributeValue <EntityReference>("adx_websiteid") == Website.ToEntityReference() && p.GetAttributeValue <DateTime?>("adx_expirationdate").GetValueOrDefault() <= DateTime.UtcNow)
                        .ToList();

            PollsArchiveListView.DataSource = polls;
            PollsArchiveListView.DataBind();
        }
 public List <EventoDeProcessamento> ObterEventos(Guid processamentoId)
 {
     try
     {
         return((from e in ServiceContext.CreateQuery <EventoDeProcessamento>(Nome)
                 where e.PartitionKey == processamentoId.ToString()
                 select e).AsTableServiceQuery().ToList());
     }
     catch (Exception ex)
     {
         throw new RepositorioCloudTableException(
                   String.Format("Erro obtendo eventos do processamento '{0}'.", processamentoId), ex);
     }
 }
 public Processamento ObterPorProcessamentoId(Guid processamentoId)
 {
     try
     {
         return
             ((from p in ServiceContext.CreateQuery <Processamento>(Nome)
               where p.ProcessamentoId == processamentoId
               select p).FirstOrDefault());
     }
     catch (Exception ex)
     {
         throw new RepositorioCloudTableException(
                   String.Format("Erro obtendo o processamento '{0}'.", processamentoId), ex);
     }
 }
        public string Find(string entity, string idField, string id, string field)
        {
            object value;

            using (OrganizationServiceProxy proxy = CRMHelper.Connect())
            {
                ServiceContext context = new ServiceContext(proxy);

                value = (from s in context.CreateQuery(entity)
                         where s[idField] == id
                         select s[field]).FirstOrDefault();
            }

            return value as string;
        }
Exemple #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            if (Cart == null)
            {
                ShoppingCartPanel.Visible      = false;
                ShoppingCartEmptyPanel.Visible = true;

                return;
            }

            var cartItems = Cart.GetCartItems().Select(sci => sci.Entity).ToArray();

            if (!cartItems.Any())
            {
                ShoppingCartPanel.Visible      = false;
                ShoppingCartEmptyPanel.Visible = true;

                return;
            }

            ShoppingCartEmptyPanel.Visible = false;

            CartItems.DataSource = cartItems.Select(item =>
            {
                var product = ServiceContext.CreateQuery("product").First(p => p.GetAttributeValue <Guid>("productid") == (item.GetAttributeValue <EntityReference>("adx_productid") == null ? Guid.Empty : item.GetAttributeValue <EntityReference>("adx_productid").Id));

                return(new
                {
                    Id = item.GetAttributeValue <Guid>("adx_shoppingcartitemid"),
                    Description = product == null ? item.GetAttributeValue <string>("adx_name") : product.GetAttributeValue <string>("name"),
                    Price = item.GetAttributeValue <Money>("adx_quotedprice") != null ? item.GetAttributeValue <Money>("adx_quotedprice").Value : 0,
                    Quantity = item.GetAttributeValue <decimal?>("adx_quantity").GetValueOrDefault(1),
                    Total = item.GetAttributeValue <decimal?>("adx_quantity").GetValueOrDefault(1) * (item.GetAttributeValue <Money>("adx_quotedprice") != null ? item.GetAttributeValue <Money>("adx_quotedprice").Value : 0),
                    Url = GetProductUrl(product)
                });
            });

            CartItems.DataBind();

            Total.Text = Cart.GetCartTotal().ToString("C2");

            SaveToQuote.Visible = SaveToQuoteEnabled;
        }
Exemple #23
0
        protected void Page_Load(object sender, EventArgs args)
        {
            var setting = ServiceContext.CreateQuery("adx_sitesetting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name") == "twitter_feed_enabled");

            var twitterEnabled = false;

            if (setting != null)
            {
                bool.TryParse(setting.GetAttributeValue <string>("adx_value"), out twitterEnabled);
            }

            TwitterFeedPanel.Visible = twitterEnabled;

            ServiceRequestsListView.DataSource = GetServiceRequests();
            ServiceRequestsListView.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RedirectToLoginIfAnonymous();

            if (!IsPostBack)
            {
                //HideControlsBasedOnAccess(ServiceContext, Contact);
            }

            var result = new List <Entity>();

            var findContracts =
                from c in ServiceContext.CreateQuery("contractdetail")  //("contract")
                where c.GetAttributeValue <Guid?>("customerid") == Contact.GetAttributeValue <Guid?>("parentcustomerid")
                select c;

            result.AddRange(findContracts);

            //var contracts = new CaseAccess().CasesForCurrentUser.Cast<Incident>();

            var status = StatusDropDown.Text;

            var contractByStatus = string.Equals(status, "Active", StringComparison.InvariantCulture)
                ? result.Where(c => ((OptionSetValue)c.Attributes["statecode"]).Value == (int)Enums.ContractDetailState.Existing || ((OptionSetValue)c.Attributes["statecode"]).Value == (int)Enums.ContractDetailState.Renewed)
                : result.Where(c => ((OptionSetValue)c.Attributes["statecode"]).Value == (int)Enums.ContractDetailState.Expired || ((OptionSetValue)c.Attributes["statecode"]).Value == (int)Enums.ContractDetailState.Canceled);

            //var contractByStatus = string.Equals(status, "Active", StringComparison.InvariantCulture)
            //    ? result.Where(c => ((OptionSetValue)c.Attributes["statecode"]).Value == (int)Enums.ContractState.Active)
            //    : result.Where(c => ((OptionSetValue)c.Attributes["statecode"]).Value != (int)Enums.ContractState.Active);

            //var casesByCustomer = string.Equals(CustomerFilter.Text, "My", StringComparison.InvariantCulture)
            //    ? casesByStatus.Where(c => c.CustomerId.Id == Contact.ContactId)
            //    : string.Equals(CustomerFilter.Text, "My Company's", StringComparison.InvariantCulture)
            //        ? casesByStatus.Where(c => c.CustomerId.Id != Contact.ContactId)
            //        : casesByStatus;

            if (contractByStatus.Count() == 0)
            {
                return;
            }

            ContractList.DataKeyNames     = new[] { "contractid" };
            ContractList.DataSource       = contractByStatus.ToDataTable(XrmContext);
            ContractList.ColumnsGenerator = new CrmSavedQueryColumnsGenerator("Web Contract Lines");  //("Contracts Web View");
            ContractList.DataBind();
        }
 public Contrato ObterContrato(int atual)
 {
     try
     {
         Contrato contrato =
             (from e in ServiceContext.CreateQuery <Contrato>(Nome)
              where
              e.PartitionKey == Contrato.ObterPartitionKey(atual) && e.RowKey == Contrato.ObterRowKey(atual)
              select e).FirstOrDefault();
         return(contrato);
     }
     catch (Exception ex)
     {
         throw new RepositorioCloudTableException(
                   String.Format("Erro obtendo contrato '{0}'.", atual), ex);
     }
 }
        public MessageContracts.LookupResponseMessage Find(MessageContracts.LookupRequestMessage request)
        {
            object value;

            using (OrganizationServiceProxy proxy = CRMHelper.Connect())
            {
                ServiceContext context = new ServiceContext(proxy);

                value = (from s in context.CreateQuery(request.Lookup.Entity)
                                 where s[request.Lookup.IdField] == request.Lookup.Id
                                 select s[request.Lookup.Field]).FirstOrDefault();
            }

            return new MessageContracts.LookupResponseMessage()
            {
                Value = value as string
            };
        }
        protected void ScheduleListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var dataItem = e.Item as ListViewDataItem;

            if (dataItem == null || dataItem.DataItem == null)
            {
                return;
            }

            var scheduleItem = dataItem.DataItem as Entity;

            if (scheduleItem == null)
            {
                return;
            }

            var schedule = ServiceContext.CreateQuery("adx_eventschedule").FirstOrDefault(es => es.GetAttributeValue <Guid>("adx_eventscheduleid") == scheduleItem.GetAttributeValue <Guid>("adx_eventscheduleid"));

            var scheduleEvent = schedule.GetRelatedEntity(ServiceContext, new Relationship("adx_event_eventschedule"));

            var eventLocation = schedule.GetRelatedEntity(ServiceContext, new Relationship("adx_eventlocation_eventschedule"));

            var sessionEventControl = (CrmEntityDataSource)e.Item.FindControl("SessionEvent");

            var eventNameControl = (Property)e.Item.FindControl("EventName");

            var sessionEventLocationControl = (CrmEntityDataSource)e.Item.FindControl("SessionEventLocation");

            var eventLocationNameControl = (Property)e.Item.FindControl("EventLocationName");

            if (sessionEventControl != null && eventNameControl != null)
            {
                sessionEventControl.DataItem = scheduleEvent;

                eventNameControl.DataBind();
            }

            if (sessionEventLocationControl != null && eventLocationNameControl != null)
            {
                sessionEventLocationControl.DataItem = eventLocation;

                eventLocationNameControl.DataBind();
            }
        }
 public int ObterNumeroDoUltimoContrato()
 {
     try
     {
         Contrato contrato =
             (from e in ServiceContext.CreateQuery <Contrato>(Nome)
              select e).FirstOrDefault();
         if (contrato == null)
         {
             return(0);
         }
         return(contrato.Numero);
     }
     catch (Exception ex)
     {
         throw new RepositorioCloudTableException(
                   String.Format("Erro obtendo número do último contrato."), ex);
     }
 }
Exemple #29
0
        private IEnumerable <SiteMapNode> GetServiceRequests()
        {
            var nodes = new List <SiteMapNode> {
            };

            var linkSet = ServiceContext.GetLinkSetByName(Website, "Service Requests List");

            if (linkSet != null)
            {
                var pages = from page in ServiceContext.CreateQuery("adx_webpage")
                            join link in ServiceContext.CreateQuery("adx_weblink")
                            on page.GetAttributeValue <Guid>("adx_webpageid") equals link.GetAttributeValue <EntityReference>("adx_pageid").Id
                            join set in ServiceContext.CreateQuery("adx_weblinkset")
                            on link.GetAttributeValue <EntityReference>("adx_weblinksetid").Id equals set.GetAttributeValue <Guid>("adx_weblinksetid")
                                where set.GetAttributeValue <string>("adx_name") == "Service Requests List"
                                where set.GetAttributeValue <EntityReference>("adx_websiteid").Id == Website.Id
                            select page;

                foreach (var page in pages)
                {
                    nodes.Add(System.Web.SiteMap.Provider.FindSiteMapNode(ServiceContext.GetUrl(page)));
                }
            }
            else
            {
                var page = ServiceContext.GetPageBySiteMarkerName(Website, "Service Requests List");

                if (page != null)
                {
                    var url = new UrlBuilder(ServiceContext.GetUrl(page));

                    var serviceRequestsNode = System.Web.SiteMap.Provider.FindSiteMapNodeFromKey(url.ToString());

                    if (serviceRequestsNode != null)
                    {
                        nodes = serviceRequestsNode.ChildNodes.Cast <SiteMapNode>().ToList();
                    }
                }
            }

            return(nodes);
        }
Exemple #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var featuredProductsCampaignCode = ServiceContext.GetSiteSettingValueByName(Website, "Retail/Featured Products Campaign Code");

            if (string.IsNullOrWhiteSpace(featuredProductsCampaignCode))
            {
                return;
            }

            var campaign = ServiceContext.CreateQuery("campaign").FirstOrDefault(c => c.GetAttributeValue <string>("codename") == featuredProductsCampaignCode);

            if (campaign != null)
            {
                Campaign = campaign.ToEntityReference();
            }
            else
            {
                FeaturedProductsPanel.Visible = false;
            }
        }
Exemple #31
0
        public DataServiceQuery GetObjectQuery(string objectName, string selector, CriteriaOperator criteria,
                                               bool includingDeleted)
        {
            var entitySetName = objectName.InflectTo().Pluralized;
            var entityClrtype = ResolveType(objectName);

            var query = ServiceContext.CreateQuery(entityClrtype, entitySetName);

            if (!includingDeleted)
            {
                query = ExcludeDeletedObjects(query);
            }
            if ((object)criteria != null)
            {
                query = query.Where(criteria);
            }
            if (!string.IsNullOrEmpty(selector))
            {
                query = (DataServiceQuery)query.Select(selector);
            }
            return(query);
        }
Exemple #32
0
        private void PopulateCustomerFilter()
        {
            CustomerFilter.Items.Clear();

            var accounts =
                ServiceContext.CreateQuery("account")
                .Where(
                    a =>
                    a.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null &&
                    a.GetAttributeValue <EntityReference>("msa_managingpartnerid")
                    .Equals(Contact.GetAttributeValue <EntityReference>("parentcustomerid")))
                .OrderBy(a => a.GetAttributeValue <string>("name"));

            CustomerFilter.Items.Add(new ListItem("All"));

            CustomerFilter.Items.Add(new ListItem("My"));

            foreach (var account in accounts)
            {
                CustomerFilter.Items.Add(new ListItem(account.GetAttributeValue <string>("name"), account.GetAttributeValue <Guid>("accountid").ToString()));
            }
        }
Exemple #33
0
        protected void PollsArchiveListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var listItem = e.Item as ListViewDataItem;

            if (listItem == null || listItem.DataItem == null)
            {
                return;
            }

            var poll = listItem.DataItem as Entity;

            var listView   = (ListView)e.Item.FindControl("PollResponsesListView");
            var totalLabel = (System.Web.UI.WebControls.Label)e.Item.FindControl("Total");

            var pollResponses = ServiceContext.CreateQuery("adx_polloption").Where(p => p.GetAttributeValue <EntityReference>("adx_pollid") == poll.ToEntityReference()).ToList();

            var totalVotes = pollResponses.Sum(p => p.GetAttributeValue <int?>("adx_votes").GetValueOrDefault(0));

            totalLabel.Text = totalVotes.ToString(CultureInfo.InvariantCulture);

            if (totalVotes <= 0)
            {
                return;
            }

            var results = from response in pollResponses
                          select new
            {
                Response   = response.GetAttributeValue <string>("adx_answer"),
                Count      = response.GetAttributeValue <int?>("adx_votes").GetValueOrDefault(0),
                Percentage = Convert.ToInt32((response.GetAttributeValue <int?>("adx_votes").GetValueOrDefault(0)) / ((float)totalVotes) * (100))
            };

            listView.DataSource = results;

            listView.DataBind();
        }
Exemple #34
0
        public IEnumerable <ItemDeContrato> ObterItensDoContrato(int atual)
        {
            try
            {
                string partitionKey  = Contrato.ObterPartitionKey(atual);
                string rowKeyInicial = ItemDeContrato.ObterRowKey(atual, 0);
                string rowKeyFinal   = ItemDeContrato.ObterRowKey(atual, int.MaxValue);

                CloudTableQuery <ItemDeContrato> query =
                    (from e in ServiceContext.CreateQuery <ItemDeContrato>(Nome)
                     where
                     e.PartitionKey == partitionKey &&
                     e.RowKey.CompareTo(rowKeyInicial) >= 0 &&
                     e.RowKey.CompareTo(rowKeyFinal) <= 0
                     select e).AsTableServiceQuery <ItemDeContrato>();

                return(query.ToList());
            }
            catch (Exception ex)
            {
                throw new RepositorioCloudTableException(
                          String.Format("Erro obtendo itens do contrato '{0}'.", atual), ex);
            }
        }
Exemple #35
0
  /// <summary>
  /// This method first connects to the Organization service and service context.
  /// Afterwards, several LINQ query techniques are demonstrated.
  /// </summary>
  /// <param name="serverConfig">Contains server connection information.</param>
  /// <param name="promptForDelete">When True, the user will be prompted to delete
  /// all created entities.</param>
  public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
  {
   try
   {

    // Connect to the Organization service. 
    // The using statement assures that the service proxy will be properly disposed.
    using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
    {
     // This statement is required to enable early-bound type support.
     _serviceProxy.EnableProxyTypes();

     _service = (IOrganizationService)_serviceProxy;

     CreateRequiredRecords();

     ServiceContext svcContext =
         new ServiceContext(_service);


     // Retrieve records with Skip/Take record paging. Setting a page size
     // can help you manage your Skip and Take calls, since Skip must be
     // passed a multiple of Take's parameter value.
     //<snippetUseLinqQuery1>
     int pageSize = 5;

     var accountsByPage = (from a in svcContext.AccountSet
                           select new Account
                           {
                            Name = a.Name,
                           });
     System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts");
     System.Console.WriteLine("======================================");
     foreach (var a in accountsByPage.Skip(2 * pageSize).Take(pageSize))
     {
      System.Console.WriteLine(a.Name);
     }
     //</snippetUseLinqQuery1>
     System.Console.WriteLine();
     System.Console.WriteLine("<End of Listing>");
     System.Console.WriteLine();
     //OUTPUT:
     //Skip 10 accounts, then Take 5 accounts
     //======================================
     //Fourth Coffee 6
     //Fourth Coffee 7
     //Fourth Coffee 8
     //Fourth Coffee 9
     //Fourth Coffee 10

     //<End of Listing>



     // Use orderBy to order items retrieved.
     //<snippetUseLinqQuery2>
     var orderedAccounts = from a in svcContext.AccountSet
                           orderby a.Name
                           select new Account
                           {
                            Name = a.Name,
                           };
     System.Console.WriteLine("Display accounts ordered by name");
     System.Console.WriteLine("================================");
     foreach (var a in orderedAccounts)
     {
      System.Console.WriteLine(a.Name);
     }
     //</snippetUseLinqQuery2>
     System.Console.WriteLine();
     System.Console.WriteLine("<End of Listing>");
     System.Console.WriteLine();
     //OUTPUT:
     //Display accounts ordered by name
     //================================
     //A. Datum Corporation
     //Adventure Works
     //Coho Vineyard
     //Fabrikam
     //Fourth Coffee 1
     //Fourth Coffee 10
     //Fourth Coffee 2
     //Fourth Coffee 3
     //Fourth Coffee 4
     //Fourth Coffee 5
     //Fourth Coffee 6
     //Fourth Coffee 7
     //Fourth Coffee 8
     //Fourth Coffee 9
     //Humongous Insurance

     //<End of Listing>


     // Filter multiple entities using LINQ.
     //<snippetUseLinqQuery3>
     var query = from c in svcContext.ContactSet
                 join a in svcContext.AccountSet
                               on c.ContactId equals a.PrimaryContactId.Id
                 where c.LastName == "Wilcox" || c.LastName == "Andrews"
                 where a.Address1_Telephone1.Contains("(206)")
                     || a.Address1_Telephone1.Contains("(425)")
                 select new
                 {
                  Contact = new Contact
                  {
                   FirstName = c.FirstName,
                   LastName = c.LastName,
                  },
                  Account = new Account
                  {
                   Address1_Telephone1 = a.Address1_Telephone1
                  }
                 };

     Console.WriteLine("Join account and contact");
     Console.WriteLine("List all records matching specified parameters");
     Console.WriteLine("Contact name: Wilcox or Andrews");
     Console.WriteLine("Account area code: 206 or 425");
     Console.WriteLine("==============================================");
     foreach (var record in query)
     {
      Console.WriteLine("Contact Name: {0} {1}",
          record.Contact.FirstName, record.Contact.LastName);
      Console.WriteLine("Account Phone: {0}",
          record.Account.Address1_Telephone1);
     }
     //</snippetUseLinqQuery3>
     Console.WriteLine("<End of Listing>");
     Console.WriteLine();
     //OUTPUT:
     //Join account and contact
     //List all records matching specified parameters
     //Contact name: Wilcox or Andrews
     //Account area code: 206 or 425
     //==============================================
     //Contact Name: Ben Andrews
     //Account Phone: (206)555-5555
     //Contact Name: Ben Andrews
     //Account Phone: (425)555-5555
     //Contact Name: Colin Wilcox
     //Account Phone: (425)555-5555
     //<End of Listing>



     // Build a complex query with LINQ. This query includes multiple
     // JOINs and a complex WHERE statement.
     //<snippetUseLinqQuery4>
     var complexQuery = from c in svcContext.ContactSet
                        join a in svcContext.AccountSet
                               on c.ContactId equals a.PrimaryContactId.Id
                        join l in svcContext.CreateQuery<Lead>()
                               on a.OriginatingLeadId.Id equals l.LeadId
                        where c.LastName == "Wilcox" || c.LastName == "Andrews"
                        where a.Address1_Telephone1.Contains("(206)")
                            || a.Address1_Telephone1.Contains("(425)")
                        select new
                        {
                         Contact = new Contact
                         {
                          FirstName = c.FirstName,
                          LastName = c.LastName,
                         },
                         Account = new Account
                         {
                          Address1_Telephone1 = a.Address1_Telephone1
                         },
                         Lead = new Lead
                         {
                          LeadId = l.LeadId
                         }
                        };

     Console.WriteLine("Join account, contact and lead");
     Console.WriteLine("List all records matching specified parameters");
     Console.WriteLine("Contact name: Wilcox or Andrews");
     Console.WriteLine("Account area code: 206 or 425");
     Console.WriteLine("==============================================");
     foreach (var record in complexQuery)
     {
      Console.WriteLine("Lead ID: {0}",
          record.Lead.LeadId);
      Console.WriteLine("Contact Name: {0} {1}",
          record.Contact.FirstName, record.Contact.LastName);
      Console.WriteLine("Account Phone: {0}",
          record.Account.Address1_Telephone1);
     }
     //</snippetUseLinqQuery4>
     Console.WriteLine("<End of Listing>");
     Console.WriteLine();
     //OUTPUT:
     //Join account, contact and lead
     //List all records matching specified parameters
     //Contact name: Wilcox or Andrews
     //Account area code: 206 or 425
     //==============================================
     //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818
     //Contact Name: Colin Wilcox
     //Account Phone: (425)555-5555
     //<End of Listing>

     //Retrieve a related Task for a Contact
     //Shows requirement that LoadProperty must be used to access the related record.
     //<snippetUseLinqQuery5>
     Contact benAndrews = svcContext.ContactSet.Where(c => c.FullName == "Ben Andrews").FirstOrDefault();
     if (benAndrews != null)
     {
      //benAndrews.Contact_Tasks is null until LoadProperty is used.
      svcContext.LoadProperty(benAndrews, "Contact_Tasks");
      Task benAndrewsFirstTask = benAndrews.Contact_Tasks.FirstOrDefault();
      if (benAndrewsFirstTask != null)
      {
       Console.WriteLine("Ben Andrews first task with Subject: '{0}' retrieved.", benAndrewsFirstTask.Subject);
      }
     }
     //</snippetUseLinqQuery5>

     DeleteRequiredRecords(promptForDelete);
    }
   }

   // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
   catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
   {
    // You can handle an exception here or pass it back to the calling method.
    throw;
   }
  }
        public void Notify(Toyota.Tsusho.CRM.API.MessageContracts.OrderNotifyRequestMessage request)
        {
            using (OrganizationServiceProxy proxy = CRMHelper.Connect())
            {
                ServiceContext context = new ServiceContext(proxy);

                foreach (OrderItemDataContract item in request.Items)
                {
                    bool add = false;

                    Entity entity = null;

                    Invoice record = (from a in context.InvoiceSet
                                      where a.new_saporderno == item.Invoice.new_saporderno
                                      select a).FirstOrDefault();

                    if (record == null)
                    {
                        add = true;

                        record = new Invoice();
                    }

                    //CustomerId Lookup

                    Contact contact = (from c in context.ContactSet
                                       where c.new_customeraccountnumber == item.Invoice.CustomerId.Name
                                       select c).FirstOrDefault();

                    if (contact == null)
                        throw new Exception(String.Format("No Contact could be retrieved for {0}", item.Invoice.CustomerId.Name));

                    //SalesOrder

                    SalesOrder order = null;

                    if (item.Invoice.SalesOrderId != null)
                    {
                        order = (from o in context.SalesOrderSet
                                            where o.new_DBMOrderNumber == item.Invoice.SalesOrderId.Name
                                            select o).FirstOrDefault();
                    }

                    //SalesOffice

                    Territory salesOffice = null;

                    if (item.Invoice.new_salesoffice != null)
                    {
                        entity = (from s in context.CreateQuery("territory")
                                     where s["new_sapcode"] == item.Invoice.new_salesoffice.Name
                                     select s).FirstOrDefault();

                        if (entity != null)
                            salesOffice = entity.ToEntity<Territory>();
                    }

                    //Plant

                   entity = (from p in context.CreateQuery("territory")
                                     where p["new_sapcode"] == item.Invoice.new_plant.Name
                                     select p).FirstOrDefault();

                   Territory plant = null;

                    if(entity != null)
                        plant = entity.ToEntity<Territory>();

                    //new_invoicetype

                    new_invoicetype invoiceType = null;

                    if(item.Invoice.new_invoicetype != null)
                    {
                        entity = (from it in context.CreateQuery("new_invoicetype")
                                     where it["new_typeidinvoice"] == item.Invoice.new_invoicetype.Name
                                     select it).FirstOrDefault();

                        if(entity != null)
                            invoiceType = entity.ToEntity<new_invoicetype>();
                    }

                    //Populate Order Fields

                    record.new_saporderno = item.Invoice.new_saporderno;

                    record.new_client = item.Invoice.new_client;

                    if (contact != null)
                        record.CustomerId = contact.ToEntityReference();

                    if (order != null)
                        record.SalesOrderId = order.ToEntityReference();

                    record.new_precedingdocument = item.Invoice.new_precedingdocument;

                    if (salesOffice != null)
                        record.new_salesoffice = salesOffice.ToEntityReference();

                    if(plant != null)
                        record.new_plant = plant.ToEntityReference();

                    record.new_customeradviser = item.Invoice.new_customeradviser;
                    record.new_billingdate = item.Invoice.new_billingdate;
                    record.new_licenseplatenumber = item.Invoice.new_licenseplatenumber;
                    record.new_country = item.Invoice.new_country;
                    record.new_counterreading = item.Invoice.new_counterreading;
                    record.new_counterunit = item.Invoice.new_counterunit;
                    record.new_orderstatus = item.Invoice.new_orderstatus;
                    record.new_netvalue = item.Invoice.new_netvalue;
                    record.new_vehicleguid = item.Invoice.new_vehicleguid;

                    if (invoiceType != null)
                        record.new_invoicetype = invoiceType.ToEntityReference();

                    if (add)
                        context.AddObject(record);
                    else
                        context.UpdateObject(record);

                    //Invoice Detail

                    //We will nowdelete all line item s and readd them
                    //if we do not do this we will get duplicate records.

                    if (record.invoice_details != null)
                    {
                        foreach (InvoiceDetail detail in record.invoice_details)
                            context.DeleteObject(detail);
                    }

                    foreach (InvoiceDetail lineItem in item.InvoiceDetails)
                    {
                        InvoiceDetail detail = new InvoiceDetail();

                        //new_material

                        new_modelsalescode material = null;

                        if(detail.new_material != null)
                        {
                            material = (from m in context.new_modelsalescodeSet
                                            where m.new_name == lineItem.new_material.Name
                                        select m).FirstOrDefault();
                        }

                        //Plant

                        Territory detailPlant = null;

                        if (lineItem.new_plant != null)
                        {
                            entity = (from p in context.CreateQuery("territory")
                                      where p["new_sapcode"] == lineItem.new_plant.Name
                                      select p).FirstOrDefault();

                            if (entity != null)
                                detailPlant = entity.ToEntity<Territory>();
                        }

                        //Populate Invoice Detail

                        detail.LineItemNumber = lineItem.LineItemNumber;
                        detail.new_pricingreferencematerial = lineItem.new_pricingreferencematerial;
                        detail.new_lvhierno = lineItem.new_lvhierno;

                        if (material != null)
                            detail.new_material = material.ToEntityReference();

                        detail.new_materialgroup = lineItem.new_materialgroup;
                        detail.ProductDescription = lineItem.ProductDescription;
                        detail.IsPriceOverridden = lineItem.IsPriceOverridden;
                        detail.IsProductOverridden = lineItem.IsProductOverridden;
                        detail.new_description1 = lineItem.new_description1;
                        detail.new_itemcategory = lineItem.new_itemcategory;
                        detail.new_deleteitem = lineItem.new_deleteitem;
                        detail.Quantity = lineItem.Quantity;
                        detail.new_targetqtyuom = lineItem.new_targetqtyuom;
                        detail.new_baseunit = lineItem.new_baseunit;
                        detail.new_targetqtyuom = lineItem.new_targetqtyuom;
                        detail.new_division = lineItem.new_division;
                        detail.PricePerUnit = lineItem.PricePerUnit;
                        detail.new_salesunit = lineItem.new_salesunit;

                        if (detailPlant != null)
                            detail.new_plant = detailPlant.ToEntityReference();

                        detail.new_storagelocation = lineItem.new_storagelocation;

                        context.AddRelatedObject(record, new Relationship("invoice_details"), detail);
                    }
                }

                context.SaveChanges();
            }
        }