Exemple #1
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
            ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            if (context.MessageName.ToLower() == "create")
            {
                Entity entity = null;
                entity = (Entity)context.InputParameters["Target"];

                var constanta = (from p in orgContext.CreateQuery("new_constant")
                                 select p).FirstOrDefault();

                string current_number = String.Format("SL-P-{0}",
                            constanta.GetAttributeValue<String>("new_dogovor").ToString());

                entity.Attributes.Add("new_agreem_number", current_number);

                service.Update(entity);

                Entity con = new Entity("new_constant");
                con.Id = constanta.Id;
                con.Attributes.Add("new_dogovor", (Convert.ToInt32(constanta.GetAttributeValue<String>("new_dogovor").ToString()) + 1).ToString());
                service.Update(con);
            }
        }
        public CrmVcardUpdateService(string userEmail)
        {
            if (string.IsNullOrWhiteSpace(userEmail))
            {
                throw new ArgumentException("userEmail must be a valid email address", "userEmail");
            }

            // Establish CRM connection
            var crmConnection = CrmConnection.Parse(CloudConfigurationManager.GetSetting("CrmConnectionString"));
            var serviceUri = new Uri(crmConnection.ServiceUri + "/XRMServices/2011/Organization.svc");
            this.service = new OrganizationServiceProxy(serviceUri, null, crmConnection.ClientCredentials, null);

            // This statement is required to enable early-bound type support.
            this.service.EnableProxyTypes(Assembly.GetAssembly(typeof(SystemUser)));

            // Create context
            this.orgContext = new OrganizationServiceContext(this.service);

            // Retrieve the system user ID of the user to impersonate.
            this.impersonatedUser = (from user in this.orgContext.CreateQuery<SystemUser>() where user.InternalEMailAddress == userEmail select user).FirstOrDefault();

            // We impersonate the user that has sent the email
            if (this.impersonatedUser == null)
            {
                throw new Exception("User not found in CRM");
            }

            this.service.CallerId = this.impersonatedUser.Id;
        }
        public void CheckSalesOrderToday()
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {
                var correntSales = (from c in orgContext.CreateQuery<SalesOrder>()
                                    where c.new_Termagreement >= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 00:00:00")).ToUniversalTime() &&
                                           c.new_Termagreement <= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 23:59:59")).ToUniversalTime() &&
                                           (c.new_articipationof == new OptionSetValue(100000000) ||
                                           c.new_participationlaw == new OptionSetValue(100000000) ||
                                           c.new_participationlo == new OptionSetValue(100000000) ||
                                           c.new_participationob == new OptionSetValue(100000000) ||
                                           c.new_participationsp == new OptionSetValue(100000000))
                                    select new ProxyToSendEmailExtended
                                    {
                                        recordId = c.Id,
                                        Name = c.Name,
                                        agreementLaw = (c.new_agreedlaw == false && Equals(c.new_participationlaw, new OptionSetValue(100000000))) ? c.new_lawdepartment : null,
                                        agreementLog = (c.new_agreedlog == false && Equals(c.new_participationlo, new OptionSetValue(100000000))) ? c.new_logistics : null,
                                        agreementFin = (c.new_agreed == false && Equals(c.new_articipationof, new OptionSetValue(100000000))) ? c.new_financedepartment : null,
                                        agreementAc = (c.new_agreed_ac == false && Equals(c.new_participationob, new OptionSetValue(100000000))) ? c.new_accountant : null,
                                        agreementSd = (c.new_agreed_sd == false && Equals(c.new_participationsp, new OptionSetValue(100000000))) ? c.new_salesdepartment : null
                                    }).ToList();

                SendEmail(correntSales, service, 1);
            }
        }
Exemple #4
0
        private void PurchaseDealUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service)
        {
            List<new_purchase_deal> _cdealListForUpdate = (from i in orgContext.CreateQuery<new_purchase_deal>()
                                                           where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                           (i.new_purchase_deal_stage == new OptionSetValue(100000000) ||
                                                           i.new_purchase_deal_stage == new OptionSetValue(100000002) ||
                                                           i.new_purchase_deal_stage == new OptionSetValue(100000001)) &&
                                                           i.new_opportunity_status == new OptionSetValue(100000000)
                                                           select i).ToList();

            foreach ( var item in _cdealListForUpdate )
            {
                new_purchase_deal _updateDeal = new new_purchase_deal();
                _updateDeal.Id = item.Id;
                if ( item.new_ship_portid == null )
                    continue;
                if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Одеса" )
                {
                    _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_odessa;
                }
                else if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Миколаїв" )
                {
                    _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_nikolaev;
                }
                service.Update(_updateDeal);
            }
        }
 public List<Entity> GetRoles()
 {
     OrganizationServiceContext org = new OrganizationServiceContext(service);
     return (from role in org.CreateQuery("role")
             select new Entity("role")
             {
                 Id = role.Id
             }).ToList();
 }
Exemple #6
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.PrimaryEntityName != new_paymentprovider.EntityLogicalName
                    || context.MessageName.ToLower() != "create")
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var PaymentProvaider = (Entity)context.InputParameters["Target"];
                    var PaymentProvaiderCurrent = PaymentProvaider.ToEntity<new_paymentprovider>();
                    //new_paymentsprovider

                    if (PaymentProvaiderCurrent.new_invoice == null || PaymentProvaiderCurrent.new_provider == null)
                        return;

                    var listProductInvoice = (from i in orgContext.CreateQuery<InvoiceDetail>()
                                              where i.InvoiceId.Id == PaymentProvaiderCurrent.new_invoice.Id &&
                                              i.new_provider.Id == PaymentProvaiderCurrent.new_provider.Id
                                              select i).ToList();

                    if (listProductInvoice == null) return;

                    foreach (var item in listProductInvoice)
                    {
                        service.Create(new new_paymentsprovider()
                        {
                            new_isproductoverridden = item.IsProductOverridden,
                            new_productid = item.ProductId,
                            new_productdescription = item.ProductDescription,
                            new_numberorderatthesupplier = item.new_Numberorderatthesupplier,
                            new_manufacturer = item.new_manufacturer,
                            TransactionCurrencyId = item.TransactionCurrencyId,
                            new_purchaseprice = item.new_purchaseprice,
                            new_amountpurchase = item.new_amountpurchase,
                            new_pricepurchaseusd = item.new_pricepurchaseusd,
                            new_totalpurchaseusd = item.new_totalpurchaseusd,
                            new_quantity = item.Quantity,
                            new_paymentprovider = PaymentProvaiderCurrent.ToEntityReference(),
                            new_provider = item.new_provider,
                            new_nds = item.new_nds
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
Exemple #7
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create" ||
                        context.PrimaryEntityName != SalesOrder.EntityLogicalName)
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var order = (Entity)context.InputParameters["Target"];

                    var neworder = order.ToEntity<SalesOrder>();

                    var constanta = (from i in orgContext.CreateQuery<new_constant>()
                                     select i).FirstOrDefault();

                    var user = (from i in orgContext.CreateQuery<SystemUser>()
                                where i.Id == order.GetAttributeValue<EntityReference>("ownerid").Id
                                select i).FirstOrDefault();

                    StringBuilder nomer = new StringBuilder();
                    nomer.Append(string.Format("{0}-{1}/СЛГУ-{2}", constanta.new_salesordernumber,
                                                                    DateTime.Now.Year.ToString(),
                                                                    user.new_abbreviation));

                    //var updateOrder = new SalesOrder(){
                    //    Id = order.Id,
                    //    OrderNumber =
                    //}
                    neworder.new_ordernumber = nomer.ToString();

                    var updateConstanta = new new_constant()
                    {
                        Id = constanta.Id,
                        new_salesordernumber = (Convert.ToInt32(constanta.new_salesordernumber) + 1).ToString()
                    };
                    service.Update(updateConstanta);
                    orgContext.SaveChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #8
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext orgContext = new OrganizationServiceContext(service);

            if (context.MessageName.ToLower() == "create")
            {
                try
                {
                    Entity entity = null;
                    entity = (Entity)context.InputParameters["Target"];
                    //Entity preMessageImage = (Entity)context.PreEntityImages["Target"];

                    if (entity.GetAttributeValue<EntityReference>("productid") == null)
                        return;

                    var productId = entity.GetAttributeValue<EntityReference>("productid").Id;

                    var productPrice = (from p in orgContext.CreateQuery("product")
                                        where p.GetAttributeValue<Guid>("productid") == productId
                                        select new Proxy
                                        {
                                            Price = p.GetAttributeValue<Money>("standardcost"),
                                            Currency = p.GetAttributeValue<EntityReference>("transactioncurrencyid")
                                        }
                                        ).FirstOrDefault();

                    if (productPrice == null) { return; }

                    var currencyUSD = (from i in orgContext.CreateQuery("sl_exchangerate")
                                       where i.GetAttributeValue<EntityReference>("sl_transactioncurrencyid").Id == productPrice.Currency.Id
                                       && i.GetAttributeValue<OptionSetValue>("statecode") == new OptionSetValue(0)
                                       select i.GetAttributeValue<decimal>("sl_exchangerate")).FirstOrDefault();

                    decimal currentPrice = (productPrice.Price.Value * currencyUSD) + (productPrice.Price.Value * currencyUSD) * (decimal)0.03;

                    Entity UpdateEntity = new Entity(entity.LogicalName);
                    UpdateEntity.Id = entity.Id;
                    UpdateEntity.Attributes.Add("new_usdprice", currentPrice);
                    service.Update(UpdateEntity);
                }
                catch(Exception ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
        }
Exemple #9
0
        public void Execute(IServiceProvider serviceProvider)
        {
            var context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));
            var factory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);

            Entity _correntEntity;

            using ( var orgContext = new OrganizationServiceContext(service) )
            {
                if ( context.MessageName.ToLower() == "create" )
                {
                    _correntEntity = (Entity) context.InputParameters["Target"];
                }
                else if ( context.MessageName.ToLower() == "update" )
                {
                    _correntEntity = context.PostEntityImages["Post"];
                }
                else
                {
                    return;
                }

                new_aprove_price _proxyentity = _correntEntity.ToEntity<new_aprove_price>();

                if ( _proxyentity.new_cropid == null ||
                    _proxyentity.new_approve == false )
                {
                    return;
                }

                if ( _proxyentity.new_recom_purchase_price_nikolaev == null &&
                    _proxyentity.new_recom_purchase_price_odessa == null )
                {
                    return;
                }

                List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                            where port.new_name == "Одеса" ||
                                            port.new_name == "Миколаїв"
                                            select port).ToList();

                PurchaseOrderUpdateMethod(_proxyentity, _portList, orgContext, service);
                PurchaseTaskUpdateMethod(_proxyentity, _portList, orgContext, service);
                PurchaseCropUpdateMethod(_proxyentity, _portList, orgContext, service);
                PurchaseDealUpdateMethod(_proxyentity, _portList, orgContext, service);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create" ||
                        context.PrimaryEntityName != Invoice.EntityLogicalName)
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var invoice = (Entity)context.InputParameters["Target"];
                    var newinvoice = invoice.ToEntity<Invoice>();

                    if (newinvoice.Name != null && !newinvoice.Name.Contains("СЛГУ"))
                    {
                        return;
                    }

                    var constanta = (from i in orgContext.CreateQuery<new_constant>()
                                     select i).FirstOrDefault();

                    var userAbbreviation = (from i in orgContext.CreateQuery<SystemUser>()
                                            where i.Id == newinvoice.OwnerId.Id
                                            select i.new_abbreviation).FirstOrDefault();
                    StringBuilder nomer = new StringBuilder();

                    nomer.Append(string.Format("{0}{1}-1", userAbbreviation, constanta.new_invoicenumder));
                    newinvoice.Name = nomer.ToString();

                    var updateConstanta = new new_constant()
                    {
                        Id = constanta.Id,
                        new_invoicenumder = (Convert.ToInt32(constanta.new_invoicenumder) + 1).ToString()
                    };
                    service.Update(updateConstanta);
                    orgContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        /// <summary>
        /// Demonstrates how to programmatically create a Workflow from an existing
        /// Process Template.
        /// </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
            {
                //<snippetCreateProcessFromTemplate1>
                // 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();

                    OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);

                    CreateRequiredRecords();

                    CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest()
                    {
                        WorkflowName = "Workflow From Template",
                        WorkflowTemplateId = _processTemplateId
                    };

                    // Execute request.
                    CreateWorkflowFromTemplateResponse response = (CreateWorkflowFromTemplateResponse)_serviceProxy.Execute(request);
                    _processId = response.Id;

                    // Verify success.
                    // Retrieve the name of the workflow.
                    ColumnSet cols = new ColumnSet("name");
                    Workflow newWorkflow = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols);
                    if (newWorkflow.Name == "Workflow From Template")
                    {
                        Console.WriteLine("Created {0}.", request.WorkflowName);
                    }

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetCreateProcessFromTemplate1>
            }

            // 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;
            }
        }
Exemple #12
0
        private void PurchaseCropUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service)
        {
            List<Guid> _cropListForUpdate = (from i in orgContext.CreateQuery<new_purchase_crop>()
                                             where i.new_crop.Id == _proxyentity.new_cropid.Id &&
                                             i.new_offer_status == new OptionSetValue(100000000)
                                             select i.Id).ToList();

            foreach ( var item in _cropListForUpdate )
            {
                new_purchase_crop _updateCrop = new new_purchase_crop();
                _updateCrop.Id = item;
                _updateCrop.new_recom_price_mykolaiv = _proxyentity.new_recom_purchase_price_nikolaev;
                _updateCrop.new_recom_price_odesa = _proxyentity.new_recom_purchase_price_odessa;
                service.Update(_updateCrop);
            }
        }
Exemple #13
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create")
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var supp = (Entity)context.InputParameters["Target"];

                    if (supp.GetAttributeValue<EntityReference>("new_contractorder") == null ||
                        supp.GetAttributeValue<EntityReference>("new_contractorder").Id == null)
                        return;

                    var count = service.Retrieve("salesorder", supp.GetAttributeValue<EntityReference>("new_contractorder").Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new[] { "new_agreemnumber" }));
                    if (count != null)
                    {
                        var number = count.GetAttributeValue<string>("new_agreemnumber") ?? "1";
                        supp["new_name"] = number;
                        orgContext.ClearChanges();
                        orgContext.Attach(supp);
                        orgContext.UpdateObject(supp);

                        Entity upOrder = new Entity();
                        upOrder.Id = supp.GetAttributeValue<EntityReference>("new_contractorder").Id;
                        upOrder.LogicalName = supp.GetAttributeValue<EntityReference>("new_contractorder").LogicalName;
                        upOrder.Attributes.Add("new_agreemnumber", (Convert.ToInt32(number) + 1).ToString());

                        service.Update(upOrder);
                        orgContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        public bool CreateInvoiceDetail(ExcelProxyInvoiceDetail invoicedetail, EntityReference product)
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {
                var newinvoiceeDetail = new InvoiceDetail()
                {
                    ProductId = product,
                    IsPriceOverridden = true,
                    Quantity = Convert.ToInt32(invoicedetail.Count),
                    PricePerUnit = new Money(Convert.ToDecimal(invoicedetail.Priceperunit)),
                    //new_purchaseprice = new Money(Convert.ToDecimal(invoicedetail.Purchaseprice)),
                    //new_amountpurchase = new Money(Convert.ToDecimal(invoicedetail.Amountpurchase)),
                    //new_pricepurchaseusd = Convert.ToDouble(invoicedetail.Pricepurchaseusd),
                    //InvoiceId = mainEntityId,
                    //new_kursspeka = Convert.ToDouble(invoicedetail.Exchangerates),
                    //new_viborkurs = new OptionSetValue(100000003),
                    //new_totalpurchaseusd = Convert.ToDouble(invoicedetail.totalUSD),
                    //UoMId = (from i in orgContext.CreateQuery<UoM>()
                    //         where i.Name == "Базовая единица"
                    //         //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666")
                    //         select new EntityReference
                    //         {
                    //             Id = i.Id,
                    //             LogicalName = i.LogicalName,
                    //             Name = i.Name
                    //         }).FirstOrDefault()
                };

                try
                {
                    service.Create(newinvoiceeDetail);
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
            return true;
        }
 public void CheckInvoiceToday()
 {
     using (var orgContext = new OrganizationServiceContext(service))
     {
         var correntInvoice = (from c in orgContext.CreateQuery<Invoice>()
                               where (c.PaymentTermsCode.Value == 34 ||
                                      c.PaymentTermsCode.Value == 35) &&
                                      c.DueDate >= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 00:00:00")).ToUniversalTime() &&
                                      c.DueDate <= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 23:59:59")).ToUniversalTime() &&
                                      (c.new_agreedlogistician == false ||
                                      c.new_agreedCFO == false ||
                                      c.new_agreedlawyer == false)
                               select new ProxyToSendEmail
                               {
                                   recordId = c.Id,
                                   Name = c.Name,
                                   agreementLaw = c.new_agreedlawyer == false ? c.new_lawyer : null,
                                   agreementLog = c.new_agreedlogistician == false ? c.new_Logist : null,
                                   agreementFin = c.new_agreedCFO == false ? c.new_CSO : null
                               }).ToList();
         SendEmail(correntInvoice, service, 1);
     }
 }
Exemple #16
0
        public void Monitoring()
        {
            try
            {
                using (var orgContext = new OrganizationServiceContext(service))
                {
                    List<MonitoringColection> listRecords;
                    List<Product> CultivationColection = GetProductFromCRM(orgContext);
                    List<TopCollection> TopSelected;

                    listRecords = (from i in orgContext.CreateQuery<new_monitoring>()
                                   where i.statecode == new_monitoringState.Active
                                   select new MonitoringColection
                                   {
                                       MonitoringRecordId = i.Id,
                                       PriceOfNikolaev = i.new_purchase_price_nikolaev,
                                       PriceOfOdessa = i.new_purchase_price_odessa,
                                       Cultivation = i.new_cropid
                                   }).ToList();

                    if (listRecords.Count == 0 || CultivationColection.Count == 0)
                        return;

                    foreach (var item in CultivationColection)
                    {

                    }
                   // TopPriceOddesa = new TopCollection { TopPrice = listRecords.Max(x => x.PriceOfOdessa), MonitoringRecordId = listRecords.Max(x => x.MonitoringRecordId) };
                    //TopPriceNIkolaev = new TopCollection { TopPrice = listRecords.Max(x => x.PriceOfNikolaev), MonitoringRecordId = listRecords.Max(x => x.MonitoringRecordId) };
                }
            }
            catch (InvalidPluginExecutionException ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
Exemple #17
0
 public BaseTask(OrganizationServiceContext context, ITrace trace)
 {
     _context = context;
     _trace   = trace;
 }
        /// <summary>
        /// This method first connects to the Organization service and creates the
        /// OrganizationServiceContext. Then, several entity creation and relationship
        /// operations are performed.
        /// </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();

                    // The OrganizationServiceContext is an object that wraps the service
                    // proxy and allows creating/updating multiple records simultaneously.
                    _orgContext = new OrganizationServiceContext(_service);

                    // Create a new contact called Mary Kay Andersen.
                    var contact = new Contact()
                    {
                        FirstName                = "Mary Kay",
                        LastName                 = "Andersen",
                        Address1_Line1           = "23 Market St.",
                        Address1_City            = "Sammamish",
                        Address1_StateOrProvince = "MT",
                        Address1_PostalCode      = "99999",
                        Telephone1               = "12345678",
                        EMailAddress1            = "*****@*****.**",
                        Id = Guid.NewGuid()
                    };
                    _contactId = contact.Id;
                    _orgContext.AddObject(contact);
                    Console.Write("Instantiating contact, ");

                    // Create an account called Contoso.
                    var account = new Account()
                    {
                        Name          = "Contoso",
                        Address1_City = "Redmond",
                        // set the account category to 'Preferred Customer'
                        AccountCategoryCode = new OptionSetValue(1),
                        LastUsedInCampaign  = DateTime.Now,
                        MarketCap           = new Money(120000),
                        DoNotEMail          = true,
                        Description         = "Contoso is a fictional company!",
                        Id = Guid.NewGuid(),
                    };
                    _accountId = account.Id;
                    Console.Write("instantiating account, ");

                    // Set Mary Kay Andersen as the primary contact
                    _orgContext.AddRelatedObject(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and creating both records in CRM.");

                    // Remove the primary contact value from Mary Kay Andersen
                    _orgContext.Attach(contact);
                    _orgContext.DeleteLink(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.Write("Removing primary contact status, ");

                    // Add Mary Kay Andersen to the contact list for the account Contoso.
                    _orgContext.Attach(account);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        account,
                        new Relationship("contact_customer_accounts"),
                        contact);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and adding contact to account's contact list.");

                    // Add a note with a document attachment to the contact's record.
                    var attachment = File.OpenRead("sample.txt");
                    var data       = new byte[attachment.Length];
                    attachment.Read(data, 0, (int)attachment.Length);

                    var note = new Annotation()
                    {
                        Subject      = "Note subject...",
                        NoteText     = "Note Details....",
                        DocumentBody = Convert.ToBase64String(data),
                        FileName     = Path.GetFileName(attachment.Name),
                        MimeType     = "text/plain",
                        Id           = Guid.NewGuid(),
                        // Associate the note to the contact.
                        ObjectId       = contact.ToEntityReference(),
                        ObjectTypeCode = Contact.EntityLogicalName
                    };
                    _annotationId = note.Id;
                    Console.Write("Instantiating a note, ");
                    _orgContext.AddObject(note);
                    _orgContext.Attach(contact);
                    // Set the contact as the Regarding attribute of the note.
                    _orgContext.AddLink(
                        contact,
                        new Relationship("Contact_Annotation"),
                        note);
                    SaveChangesHelper(note, contact);
                    Console.WriteLine("creating the note in CRM and linking to contact.");

                    // Change the owning user of the contact Mary Kay Andersen
                    // Find a user with an email address of "*****@*****.**"
                    var newOwner = (from u in _orgContext.CreateQuery <SystemUser>()
                                    where u.InternalEMailAddress == "*****@*****.**"
                                    select u).Single();
                    AssignRequest assignRequest = new AssignRequest()
                    {
                        Target   = contact.ToEntityReference(),
                        Assignee = newOwner.ToEntityReference()
                    };
                    _orgContext.Execute(assignRequest);
                    Console.WriteLine("Changing ownership of contact record.");

                    // Create a new price list called Retail Price List.
                    var priceList = new PriceLevel()
                    {
                        Name        = "Retail Price List",
                        BeginDate   = DateTime.Now,
                        EndDate     = DateTime.Now,
                        Description = "Contoso's primary pricelist.",
                        Id          = Guid.NewGuid()
                    };
                    _priceLevelId = priceList.Id;
                    _orgContext.AddObject(priceList);
                    Console.Write("Instantiating price list ");

                    // Create a new product called Widget A.
                    var newProduct = new Product()
                    {
                        Name             = "Widget A",
                        Description      = "Industrial widget for hi-tech industries",
                        ProductStructure = new OptionSetValue(1), // 1 = Product
                        QuantityOnHand   = 2,
                        ProductNumber    = "WIDG-A",
                        Price            = new Money(decimal.Parse("12.50")),
                        QuantityDecimal  = 2, // Sets the Decimals Supported value
                        Id = Guid.NewGuid(),
                        DefaultUoMScheduleId = new EntityReference(
                            UoMSchedule.EntityLogicalName,
                            _orgContext.CreateQuery <UoMSchedule>().First().Id),
                        DefaultUoMId = new EntityReference(
                            UoM.EntityLogicalName,
                            _orgContext.CreateQuery <UoM>().First().Id)
                    };
                    _productId = newProduct.Id;
                    _orgContext.AddObject(newProduct);
                    Console.WriteLine("and product.");
                    SaveChangesHelper(priceList, newProduct);

                    // Add Widget A to the Retail Price List.
                    var priceLevelProduct = new ProductPriceLevel()
                    {
                        ProductId    = newProduct.ToEntityReference(),
                        UoMId        = newProduct.DefaultUoMId,
                        Amount       = new Money(decimal.Parse("12.50")),
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid()
                    };
                    _productPriceLevelId = priceLevelProduct.Id;
                    _orgContext.AddObject(priceLevelProduct);
                    Console.Write("Associating product to price list, ");

                    // Publish the product
                    SetStateRequest publishRequest = new SetStateRequest
                    {
                        EntityMoniker = newProduct.ToEntityReference(),
                        State         = new OptionSetValue((int)ProductState.Active),
                        Status        = new OptionSetValue(1)
                    };
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("and publishing the product.");


                    // Create a new quote for Contoso.
                    var newQuote = new Quote()
                    {
                        Name = "Quotation for Contoso",
                        // Sets the pricelist to the one we've just created
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid(),
                        CustomerId   = account.ToEntityReference()
                    };
                    _quoteId = newQuote.Id;
                    _orgContext.AddObject(newQuote);
                    _orgContext.Attach(account);
                    _orgContext.AddLink(
                        newQuote,
                        new Relationship("quote_customer_accounts"),
                        account);
                    Console.Write("Instantiating a quote, ");

                    // Add a quote product to this quote.
                    var quoteProduct = new QuoteDetail()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        Quantity  = 1,
                        QuoteId   = newQuote.ToEntityReference(),
                        UoMId     = newProduct.DefaultUoMId,
                        Id        = Guid.NewGuid()
                    };
                    _quoteDetailId = quoteProduct.Id;
                    _orgContext.AddObject(quoteProduct);
                    Console.WriteLine("and adding product to quote.");

                    // Create a sales opportunity with Contoso.
                    var oppty = new Opportunity()
                    {
                        Name = "Interested in Widget A",
                        EstimatedCloseDate        = DateTime.Now.AddDays(30.0),
                        EstimatedValue            = new Money(decimal.Parse("300000.00")),
                        CloseProbability          = 25,                    // 25% probability of closing this deal
                        IsRevenueSystemCalculated = false,                 // user-calculated revenue
                        OpportunityRatingCode     = new OptionSetValue(2), // warm
                        CustomerId = account.ToEntityReference(),
                        Id         = Guid.NewGuid()
                    };
                    _opportunityId = oppty.Id;
                    _orgContext.AddObject(oppty);
                    Console.Write("Instantiating opportunity, ");
                    //_orgContext.AddLink(
                    //    oppty,
                    //    new Relationship("opportunity_customer_accounts"),
                    //    account);
                    SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct,
                                      quoteProduct, oppty, account);
                    Console.WriteLine("and creating all records in CRM.");

                    // Associate quote to contact, which adds the Contact record in the
                    // "Other Contacts" section of a Quote record.
                    _orgContext.Attach(contact);
                    _orgContext.Attach(newQuote);
                    _orgContext.AddLink(
                        contact,
                        new Relationship("contactquotes_association"),
                        newQuote);
                    SaveChangesHelper(contact, newQuote);
                    Console.WriteLine("Associating contact and quote.");

                    // Create a case for Mary Kay Andersen.
                    var serviceRequest = new Incident()
                    {
                        Title          = "Problem with Widget B",
                        PriorityCode   = new OptionSetValue(1), // 1 = High
                        CaseOriginCode = new OptionSetValue(1), // 1 = Phone
                        CaseTypeCode   = new OptionSetValue(2), // 2 = Problem
                        SubjectId      =
                            new EntityReference(
                                Subject.EntityLogicalName,
                                _orgContext.CreateQuery <Subject>()
                                .First().Id),                     // use the default subject
                        Description = "Customer can't switch the product on.",
                        FollowupBy  = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                        CustomerId  = contact.ToEntityReference(),
                        Id          = Guid.NewGuid()
                    };
                    _incidentId = serviceRequest.Id;
                    _orgContext.AddObject(serviceRequest);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        serviceRequest,
                        new Relationship("incident_customer_contacts"),
                        contact);
                    SaveChangesHelper(serviceRequest, contact);
                    Console.WriteLine("Creating service case for contact.");

                    // Deactivate the Mary Kay Andersen contact record.
                    SetStateRequest setInactiveRequest = new SetStateRequest
                    {
                        EntityMoniker = contact.ToEntityReference(),
                        State         = new OptionSetValue((int)ContactState.Inactive),
                        Status        = new OptionSetValue(2)
                    };
                    _orgContext.Execute(setInactiveRequest);
                    Console.WriteLine("Deactivating the contact record.");

                    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 EarlyBoundReadApplicationPermitTest()
 {
     OrganizationServiceContext orgContext = new OrganizationServiceContext(OrganizationServiceProxy);
 }
Exemple #20
0
        public override ApplicationPath GetApplicationPath(OrganizationServiceContext context, Entity entity)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            if (entity.LogicalName == "adx_communityforumpost")
            {
                var thread = entity.GetRelatedEntity(context, "adx_communityforumthread_communityforumpost".ToRelationship());

                if (thread != null)
                {
                    return(GetForumPostApplicationPath(context, entity, thread));
                }
            }

            if (entity.LogicalName == "adx_blogpostcomment")
            {
                var post = entity.GetRelatedEntity(context, "adx_blogpost_blogpostcomment".ToRelationship());

                if (post != null)
                {
                    return(GetBlogPostCommentApplicationPath(context, entity, post));
                }
            }

            if (entity.LogicalName == "adx_shortcut")
            {
                return(GetShortcutApplicationPath(context, entity));
            }

            if (entity.LogicalName == "adx_ideaforum")
            {
                return(GetIdeaForumApplicationPath(context, entity));
            }

            if (entity.LogicalName == "adx_idea")
            {
                return(GetIdeaApplicationPath(context, entity));
            }

            if (entity.LogicalName == "adx_issue")
            {
                return(GetIssueApplicationPath(context, entity));
            }

            if (entity.LogicalName == "incident")
            {
                return(GetIncidentApplicationPath(context, entity));
            }

            if (entity.LogicalName == "kbarticle")
            {
                return(GetKbArticleApplicationPath(context, entity));
            }

            if (entity.LogicalName == "knowledgearticle")
            {
                return(GetKnowledgeArticleApplicationPath(context, entity));
            }

            if (entity.LogicalName == "category")
            {
                return(GetCategoryApplicationPath(context, entity));
            }

            // We want new behaviour for adx_webpages -- paths for this entity will now have a trailing slash ('/').
            if (entity.LogicalName == "adx_webpage")
            {
                var path = base.GetApplicationPath(context, entity);

                // If the path is an external URL (it shouldn't be, but just in case), return the original path untouched.
                if (path.ExternalUrl != null)
                {
                    return(path);
                }

                // If the path does not already have a trailing slash (it shouldn't), append one.
                return(path.AppRelativePath.EndsWith("/")
                                        ? path
                                        : ApplicationPath.FromAppRelativePath("{0}/".FormatWith(path.AppRelativePath)));
            }

            // Support adx_webfiles with a parent adx_blogpost, instead of adx_webpage.
            if (entity.LogicalName == "adx_webfile" && entity.GetAttributeValue <EntityReference>("adx_blogpostid") != null)
            {
                var post = entity.GetRelatedEntity(context, "adx_blogpost_webfile".ToRelationship());

                if (post != null)
                {
                    var postPath       = GetApplicationPath(context, post);
                    var filePartialUrl = entity.GetAttributeValue <string>("adx_partialurl");

                    if (postPath != null && filePartialUrl != null)
                    {
                        return(ApplicationPath.FromAppRelativePath("{0}/{1}".FormatWith(postPath.AppRelativePath.TrimEnd('/'), filePartialUrl)));
                    }
                }
            }

            var lookup = new Dictionary <string, Tuple <string[], Relationship, string, string, bool> >
            {
                {
                    "adx_communityforumthread",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_communityforumthreadid" },
                        "adx_communityforum_communityforumthread".ToRelationship(),
                        "adx_communityforum",
                        null,
                        false)
                },
                {
                    "adx_communityforum",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_partialurl" },
                        "adx_webpage_communityforum".ToRelationship(),
                        "adx_webpage",
                        "Forums",
                        false)
                },
                {
                    "adx_event",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_partialurl" },
                        "adx_webpage_event".ToRelationship(),
                        "adx_webpage",
                        "Events",
                        false)
                },
                {
                    "adx_survey",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_partialurl" },
                        "adx_webpage_survey".ToRelationship(),
                        "adx_webpage",
                        "Surveys",
                        false)
                },
                {
                    "adx_blog",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_partialurl" },
                        "adx_webpage_blog".ToRelationship(),
                        "adx_webpage",
                        null,
                        true)
                },
                {
                    "adx_blogpost",
                    new Tuple <string[], Relationship, string, string, bool>(
                        new[] { "adx_partialurl", "adx_blogpostid" },
                        "adx_blog_blogpost".ToRelationship(),
                        "adx_blog",
                        null,
                        true)
                },
            };

            Tuple <string[], Relationship, string, string, bool> urlData;

            if (lookup.TryGetValue(entity.LogicalName, out urlData))
            {
                var partialUrlLogicalName = urlData.Item1.FirstOrDefault(logicalName =>
                {
                    var partialUrlValue = entity.GetAttributeValue(logicalName);

                    return(partialUrlValue != null && !string.IsNullOrWhiteSpace(partialUrlValue.ToString()));
                });

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

                var relationship     = urlData.Item2;
                var siteMarker       = urlData.Item4;
                var addTrailingSlash = urlData.Item5;

                var websiteRelativeUrl = GetApplicationPath(context, entity, partialUrlLogicalName, relationship, GetApplicationPath, siteMarker);

                if (websiteRelativeUrl != null)
                {
                    if (addTrailingSlash && websiteRelativeUrl.PartialPath != null && !websiteRelativeUrl.PartialPath.EndsWith("/"))
                    {
                        websiteRelativeUrl = ApplicationPath.FromPartialPath("{0}/".FormatWith(websiteRelativeUrl.PartialPath));
                    }

                    var website = WebsiteProvider.GetWebsite(context, entity);

                    var path = WebsitePathUtility.ToAbsolute(website, websiteRelativeUrl.PartialPath);

                    return(ApplicationPath.FromPartialPath(path));
                }
            }

            return(base.GetApplicationPath(context, entity));
        }
Exemple #21
0
        private ApplicationPath GetKnowledgeArticleApplicationPath(OrganizationServiceContext context, Entity article)
        {
            article.AssertEntityName("knowledgearticle");

            var number = article.GetAttributeValue <string>("articlepublicnumber");

            if (string.IsNullOrEmpty(number))
            {
                return(null);
            }

            var httpContext = HttpContext.Current;

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

            var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            var routeData          = RouteTable.Routes.GetRouteData(httpContextWrapper);

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

            var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, routeData));

            var languageLocaleCode = article.Contains("language_locale.code") ? article.GetAttributeValue <AliasedValue>("language_locale.code").Value as string : null;

            if (string.IsNullOrWhiteSpace(languageLocaleCode))
            {
                var localeid = article.GetAttributeValue <EntityReference>("languagelocaleid");
                if (localeid != null)
                {
                    var locale = context.CreateQuery("languagelocale").FirstOrDefault(lang => lang.GetAttributeValue <Guid>("languagelocaleid") == localeid.Id);
                    if (locale != null)
                    {
                        languageLocaleCode = locale.GetAttributeValue <string>("code");
                    }
                }
            }

            // If multi-language is enabled, return URL using in approriate multi-language URL format.
            var    contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
            string url = string.Empty;

            if (contextLanguageInfo.IsCrmMultiLanguageEnabled && ContextLanguageInfo.DisplayLanguageCodeInUrl)
            {
                var actionUrl = urlHelper.Action("Article", "Article", new { number = number, area = "KnowledgeManagement" });

                // if actionUrl is null, ex: deactivated root page.
                if (actionUrl == null)
                {
                    return(null);
                }

                url = string.Format("{0}{1}", httpContext.Request.Url.GetLeftPart(UriPartial.Authority), actionUrl);
                url = contextLanguageInfo.FormatUrlWithLanguage(false, languageLocaleCode, new Uri(url));
            }
            else
            {
                url = urlHelper.Action("Article", "Article", new { number = number, lang = languageLocaleCode, area = "KnowledgeManagement" });
            }

            return(url == null ? null : ApplicationPath.FromAbsolutePath(url));
        }
        /// <summary>
        /// Demonstrates how to programmatically execute a workflow.
        /// </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();

                    OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);

                    CreateRequiredRecords();

                    // Create an ExecuteWorkflow request.
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        WorkflowId = _workflowId,
                        EntityId   = _leadId
                    };
                    Console.Write("Created ExecuteWorkflow request, ");

                    // Execute the workflow.
                    ExecuteWorkflowResponse response =
                        (ExecuteWorkflowResponse)_serviceProxy.Execute(request);
                    Console.WriteLine("and sent request to service.");


                    #region Check success

                    ColumnSet        cols            = new ColumnSet("statecode");
                    QueryByAttribute retrieveOpQuery = new QueryByAttribute();
                    retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName;
                    retrieveOpQuery.ColumnSet  = cols;
                    retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id);

                    // Wait for the asyncoperation to complete.
                    // (wait no longer than 1 minute)
                    for (int i = 0; i < 60; i++)
                    {
                        System.Threading.Thread.Sleep(1000);

                        EntityCollection retrieveOpResults =
                            _serviceProxy.RetrieveMultiple(retrieveOpQuery);

                        if (retrieveOpResults.Entities.Count() > 0)
                        {
                            AsyncOperation op =
                                (AsyncOperation)retrieveOpResults.Entities[0];
                            if (op.StateCode == AsyncOperationState.Completed)
                            {
                                _asyncOperationId = op.AsyncOperationId.Value;
                                Console.WriteLine("AsyncOperation completed successfully.");
                                break;
                            }
                        }

                        if (i == 59)
                        {
                            throw new TimeoutException("AsyncOperation failed to complete in under one minute.");
                        }
                    }

                    // Retrieve the task that was created by the workflow.
                    cols = new ColumnSet("activityid");
                    QueryByAttribute retrieveActivityQuery = new QueryByAttribute();
                    retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName;
                    retrieveActivityQuery.ColumnSet  = cols;
                    retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade");

                    EntityCollection results =
                        _serviceProxy.RetrieveMultiple(retrieveActivityQuery);

                    if (results.Entities.Count() == 0)
                    {
                        throw new InvalidOperationException("Phone call activity was not successfully created");
                    }
                    else
                    {
                        Console.WriteLine("Phone call activity successfully created from workflow.");
                    }

                    #endregion Check success

                    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;
            }
        }
 private static IEnumerable <IWebLink> CreateWebLinkSubTree(OrganizationServiceContext serviceContext, EntityReference entity, ICrmEntitySecurityProvider securityProvider, IEntityUrlProvider urlProvider, ILookup <Guid, Entity> childWebLinkLookup)
 {
     return(childWebLinkLookup[entity.Id]
            .Select(e => CreateWebLink(serviceContext, e, securityProvider, urlProvider, childWebLinkLookup)));
 }
 public NoteRepository(IPluginContext pluginContext, OrganizationServiceContext context)
     : base(pluginContext, context)
 {
 }
Exemple #25
0
        public static FetchXml GetFetchXmlFilteredToSingleEntity(this ICrmEntityIndexer indexer, string fetchXml, OrganizationServiceContext dataContext, string entityLogicalName, Guid id)
        {
            var filteredFetchXml = XDocument.Parse(fetchXml);

            var entity = filteredFetchXml.XPathSelectElements("/fetch/entity")
                         .Where(e => e.Attributes("name").Any(a => a.Value == entityLogicalName))
                         .FirstOrDefault();

            if (entity == null)
            {
                throw new InvalidOperationException("Invalid FetchXML, unable to find entity element in FetchXML:\n\n{0}".FormatWith(filteredFetchXml));
            }

            var existingFilter = entity.XPathSelectElement("filter");

            var idFilter = new XElement("filter");

            idFilter.Add(new XAttribute("type", "and"));

            var condition = new XElement("condition");

            var primaryKey = GetPrimaryKeyField(indexer, dataContext, entityLogicalName);

            condition.Add(new XAttribute("attribute", primaryKey));
            condition.Add(new XAttribute("operator", "eq"));
            condition.Add(new XAttribute("value", id.ToString()));

            idFilter.Add(condition);

            if (existingFilter != null)
            {
                existingFilter.Remove();

                idFilter.Add(existingFilter);
            }

            entity.Add(idFilter);

            return(new FetchXml(filteredFetchXml));
        }
Exemple #26
0
        public void Processes(Annotation annotation, IOrganizationService service)
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {
                var invoiceMain = (from y in orgContext.CreateQuery <Invoice>()
                                   where y.Id == annotation.ObjectId.Id
                                   select y).FirstOrDefault();
                var exel = new ExcelReader().ExcelOpenSpreadsheets(annotation.DocumentBody.ToString(),
                                                                   annotation.FileName.ToString());

                if (exel == null)
                {
                    return;
                }

                if (exel.Tables[0].Rows[1][0].ToString() != "SKU")
                {
                    return;
                }

                var data = new CreateNewProduct();
                List <ExcelProxyInvoice> invoice = new List <ExcelProxyInvoice>();
                data.service      = service;
                data.mainEntityId = annotation.ObjectId;
                for (int i = 2; i < exel.Tables[0].Rows.Count; i++)
                {
                    var product       = new ExcelProxyProduct();
                    var invoicedetail = new ExcelProxyInvoiceDetail();

                    if (exel.Tables[0].Rows[i][0].ToString() != string.Empty && exel.Tables[0].Rows[i][0].ToString() != "Итого:")
                    {
                        product.SKU    = exel.Tables[0].Rows[i][0].ToString();
                        product.Vendor = exel.Tables[0].Rows[i][1].ToString();
                        //product.recomendetPriceUSD = exel.Tables[0].Rows[i][10].ToString();
                        product.Product = exel.Tables[0].Rows[i][2].ToString();

                        invoicedetail.Product          = exel.Tables[0].Rows[i][2].ToString();
                        invoicedetail.Count            = exel.Tables[0].Rows[i][3].ToString();
                        invoicedetail.Priceperunit     = exel.Tables[0].Rows[i][4].ToString();
                        invoicedetail.Baseamount       = exel.Tables[0].Rows[i][5].ToString();
                        invoicedetail.Purchaseprice    = exel.Tables[0].Rows[i][6].ToString();
                        invoicedetail.Amountpurchase   = exel.Tables[0].Rows[i][7].ToString();
                        invoicedetail.Pricepurchaseusd = exel.Tables[0].Rows[i][11].ToString();
                        invoicedetail.Exchangerates    = exel.Tables[0].Rows[i][13].ToString();
                        invoicedetail.totalUSD         = exel.Tables[0].Rows[i][12].ToString();

                        invoice.Add(new ExcelProxyInvoice
                        {
                            Marza         = exel.Tables[0].Rows[i][8].ToString(),
                            MarzaPersent  = exel.Tables[0].Rows[i][9].ToString(),
                            totalUSD      = exel.Tables[0].Rows[i][12].ToString(),
                            exchangeRates = exel.Tables[0].Rows[i][13].ToString()
                        });

                        EntityReference idProduct = data.ProductFromSpec(product, invoiceMain.PriceLevelId);

                        if (idProduct == null)
                        {
                            throw new InvalidPluginExecutionException("Product not found");
                        }
                        if (data.CreateInvoiceDetail(invoicedetail, idProduct) == false)
                        {
                            throw new InvalidPluginExecutionException("InvoiceDetail don`t create");
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                decimal sum = (from i in invoice
                               select Convert.ToDecimal(i.Marza)).Sum();
                decimal percent = (from i in invoice
                                   select Convert.ToDecimal(i.MarzaPersent)).Average();
                decimal totalUSD = (from i in invoice
                                    select Convert.ToDecimal(i.totalUSD)).Sum();
                double rates = (from i in invoice
                                select Convert.ToDouble(i.exchangeRates)).Average();

                var updateInvoice = new Invoice()
                {
                    Id = annotation.ObjectId.Id,
                    //new_marginUSD = invoiceMain.new_marginUSD + (double)sum,
                    //new_morginpercentage = percent == 0 ? 0 : (invoiceMain.new_morginpercentage ?? 0 + percent),
                    //new_USD = invoiceMain.new_USD + (double)totalUSD,
                    //new_exchangerate = invoiceMain.new_exchangerate ?? 0 + rates
                };

                service.Update(updateInvoice);
            }
        }
Exemple #27
0
        static void Main(string[] args)
        {
            //Authenticate
            string           connectionstring = "AuthType=Office365;Url = https://org31728cfd.crm.dynamics.com/; Username = [email protected];Password = 3452Anj1!";
            CrmServiceClient service          = new CrmServiceClient(connectionstring);

            //create a contact

            Entity account = new Entity("account");

            account.Attributes.Add("name", "Acme2");

            Guid guid = service.Create(account);

            Console.WriteLine(guid);

            Console.Read();
            Console.WriteLine("If no writing above this it failed.");

            // fetch xml learning
            string query = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
            <entity name='account'>
            <attribute name='name' />
            <attribute name='address1_city' />
            <attribute name='primarycontactid' />
            <attribute name='telephone1' />
            <attribute name='accountid' />
            <order attribute='name' descending='false' />
            <filter type='and'>
            <condition attribute='ownerid' operator='eq-userid' />
            <condition attribute='statecode' operator='eq' value='0' />
            </filter>
            <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
            <attribute name='emailaddress1' />
            </link-entity>
            </entity>
            </fetch>";

            EntityCollection collection = service.RetrieveMultiple(new FetchExpression(query));

            foreach (Entity Account in collection.Entities)
            {
                Console.WriteLine(Account.Attributes["name"].ToString());
            }


            // Count number of Account using fetch

            string query2 = @"<fetch distinct='false' mapping='logical' aggregate='true'>
            <Entity name='entity name'>
            <Attribute name='attribute name' aggregate='count alias='aliasname'/>
            </entity>
            </fetch>";

            EntityCollection collection2 = service.RetrieveMultiple(new FetchExpression(query2));

            foreach (Entity item in collection2.Entities)
            {
                Console.WriteLine(((AliasedValue)item.Attributes["aliasname"]).Value.ToString());
            }

            // Note Aggregate limit 50,000 Values

            //using Linq to query collection
            using (OrganizationServiceContext context = new OrganizationServiceContext(service))
            {
                var records = from account2 in context.CreateQuery("account")
                              select account2;

                foreach (var record in records)
                {
                    if (record.Attributes.Contains("name"))
                    {
                        Console.WriteLine(record.Attributes["name"].ToString());
                    }
                }
            }

            // Using join statements using Linq
            using (OrganizationServiceContext contex2 = new OrganizationServiceContext(service))
            {
                var records2 = from c in contex2.CreateQuery("account")
                               join
                               a in contex2.CreateQuery("contact")
                               on c["parentcustomerid"] equals a["accountid"]
                               where c["accountid"] != null
                               select new
                {
                    name        = c["name"],
                    Accountname = a["Fullname"]
                };
                foreach (var record in records2)
                {
                    Console.WriteLine(record.name + " " + record.Accountname);
                }
            }

            // Create Contact using Late Binding
            Entity c = new Entity("contact");

            // Early binding need to add the classes using CRM utility tool use in command line then interactive mode to generate class file
            // Contact contact = new Contact();
            // contact. // Add Your Attribute

            // Linq query with early binding
            // using (svcContext context = new svcContext(service))
            // {
            //      get accounts
            //  var accounts = from a in context.AccountSet
            //             where a.address1_City == "Seattle"
            //           select a;
            // }
        }
Exemple #28
0
        public override Entity GetWebsite(OrganizationServiceContext context, Entity entity)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            var entitiesWithoutWebsites = new Dictionary <string, Relationship>
            {
                // extended portal entities
                { "adx_communityforumthread", "adx_communityforum_communityforumthread".ToRelationship() },
                { "adx_communityforumpost", "adx_communityforumthread_communityforumpost".ToRelationship() },
                { "adx_eventschedule", "adx_event_eventschedule".ToRelationship() },
                { "adx_blogpost", "adx_blog_blogpost".ToRelationship() },
                { "adx_blogpostcomment", "adx_blogpost_blogpostcomment".ToRelationship() },

                // base portal entities
                { "adx_weblink", "adx_weblinkset_weblink".ToRelationship() }
            };

            Relationship hasWebsiteRelationship;

            if (entitiesWithoutWebsites.TryGetValue(entity.LogicalName, out hasWebsiteRelationship))
            {
                return(GetWebsite(context, context.RetrieveRelatedEntity(entity, hasWebsiteRelationship)));
            }

            var lookup = new Dictionary <string, Relationship>
            {
                // extended portal entities
                { "adx_communityforum", "adx_website_communityforum".ToRelationship() },
                { "adx_eventsponsor", "adx_website_eventsponsor".ToRelationship() },
                { "adx_eventspeaker", "adx_website_eventspeaker".ToRelationship() },
                { "adx_event", "adx_website_event".ToRelationship() },
                { "adx_publishingstate", "adx_website_publishingstate".ToRelationship() },
                { "adx_survey", "adx_website_survey".ToRelationship() },
                { "adx_blog", "adx_website_blog".ToRelationship() },

                // base portal entities
                { "adx_weblinkset", "adx_website_weblinkset".ToRelationship() },
                { "adx_webpage", "adx_website_webpage".ToRelationship() },
                { "adx_webfile", "adx_website_webfile".ToRelationship() },
                { "adx_sitemarker", "adx_website_sitemarker".ToRelationship() },
                { "adx_pagetemplate", "adx_website_pagetemplate".ToRelationship() },
                { "adx_contentsnippet", "adx_website_contentsnippet".ToRelationship() }
            };

            Relationship websiteRelationship;

            if (lookup.TryGetValue(entity.LogicalName, out websiteRelationship))
            {
                return(context.RetrieveRelatedEntity(entity, websiteRelationship));
            }

            return(null);
        }
Exemple #29
0
 private List<Product> GetProductFromCRM(OrganizationServiceContext orgContext)
 {
     return (from c in orgContext.CreateQuery<Product>()
             select c).ToList();
 }
        private EntityReference ToTransactionCurrency(string p, decimal? value)
        {
            using (var orgContext = new OrganizationServiceContext(this.service))
            {
                if (p == "USD")
                {
                    return (from i in orgContext.CreateQuery<TransactionCurrency>()
                            where i.ISOCurrencyCode == p
                            select i).FirstOrDefault().ToEntityReference();
                }
                var TransactionCurrencyId = (from i in orgContext.CreateQuery<TransactionCurrency>()
                                             where i.ISOCurrencyCode == p
                                             select i.Id).FirstOrDefault();

                TransactionCurrency entityForUpdate = new TransactionCurrency()
                {
                    Id = TransactionCurrencyId,
                    LogicalName = TransactionCurrency.EntityLogicalName,
                    ExchangeRate = value
                };

                service.Update(entityForUpdate);
                return entityForUpdate.ToEntityReference();
            }
        }
Exemple #31
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            String        PayloadDetails = request.Get(executionContext);
            int?          optionSetValue;
            int           ErrorCode           = 400; //400 -- bad request
            String        _ErrorMessage       = string.Empty;
            String        _ErrorMessageDetail = string.Empty;
            Guid          ContactId           = Guid.Empty;
            Guid          CrmGuid             = Guid.Empty;
            StringBuilder ErrorMessage        = new StringBuilder();
            String        UniqueReference     = string.Empty;
            Guid?         ExistingID          = null;

            try
            {
                objCommon = new SCII.Helper(executionContext);
                objCommon.tracingService.Trace("Load CRM Service from context --- OK");
                Entity AccountObject = new Entity(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME);

                objCommon.tracingService.Trace("attempt to seriallised new");
                SCII.OrganisationRequest AccountPayload = JsonConvert.DeserializeObject <SCII.OrganisationRequest>(PayloadDetails);
                objCommon.tracingService.Trace("seriallised object working");
                var ValidationContext = new ValidationContext(AccountPayload, serviceProvider: null, items: null);
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResults        = null;
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResultsAddress = null;

                var     isValid        = objCommon.Validate(AccountPayload, out ValidationResults);
                Boolean isValidAddress = AccountPayload.address == null ? true :
                                         objCommon.Validate(AccountPayload.address, out ValidationResultsAddress);

                if (AccountPayload.address != null && AccountPayload.address.type != null)
                {
                    if (!Enum.IsDefined(typeof(SCII.AddressTypes), AccountPayload.address.type))
                    {
                        ErrorMessage.Append(String.Format("Option set value for address of type {0} not found;", AccountPayload.address.type));
                    }
                }

                if (isValid & isValidAddress && ErrorMessage.Length == 0)
                {
                    objCommon.tracingService.Trace("length{0}", AccountPayload.name.Length);

                    objCommon.tracingService.Trace("hierarchylevel level: {0}", AccountPayload.hierarchylevel);

                    if (AccountPayload.hierarchylevel == 0 || !String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationHierarchyLevel), AccountPayload.hierarchylevel))
                        )
                    {
                        objCommon.tracingService.Trace("before assinging value");

                        if (AccountPayload.hierarchylevel != 0)
                        {
                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL] = new OptionSetValue(AccountPayload.hierarchylevel);
                        }
                        objCommon.tracingService.Trace("after assinging value");
                        if (!String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationType), AccountPayload.type)))
                        {
                            //check if crn exists

                            OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                            if (AccountPayload.crn != null && AccountPayload.crn != string.Empty)
                            {
                                ExistingID = objCommon.CheckIfSameIdenfierExists(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, AccountPayload.crn, null);
                                objCommon.tracingService.Trace("company housid from identifier:" + ExistingID);
                            }
                            //var checkCRNExistis = from c in orgSvcContext.CreateQuery("account")
                            //                      where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] == AccountPayload.crn
                            //                      select new { organisationid = c.Id };


                            if (ExistingID == null)
                            {
                                objCommon.tracingService.Trace("After completing validation 12" + AccountPayload.type);
                                optionSetValue = AccountPayload.type;
                                objCommon.tracingService.Trace("before assigning type  " + AccountPayload.type);
                                objCommon.tracingService.Trace(optionSetValue.ToString());
                                objCommon.tracingService.Trace("after  setting up option set value");
                                OptionSetValueCollection BusinessTypes = new OptionSetValueCollection();
                                BusinessTypes.Add(new OptionSetValue(optionSetValue.Value));
                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TYPE] = BusinessTypes;
                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.NAME] = AccountPayload.name == null ? string.Empty : AccountPayload.name;
                                //AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] = AccountPayload.crn == string.Empty ? null : AccountPayload.crn;


                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TELEPHONE1] = AccountPayload.telephone == null ? string.Empty : AccountPayload.telephone;
                                if (AccountPayload.validatedwithcompanieshouse != null)
                                {
                                    bool isValidCompaniesHouse = false;
                                    if (Boolean.TryParse(AccountPayload.validatedwithcompanieshouse.ToString(), out isValidCompaniesHouse))
                                    {
                                        AccountObject[SCS.AccountContants.VALIDATED_WITH_COMPANYHOUSE] = isValidCompaniesHouse;
                                    }
                                    else
                                    {
                                        ErrorMessage = ErrorMessage.Append(string.Format("Validated with companyhouse value {0} is not valid;",
                                                                                         AccountPayload.validatedwithcompanieshouse));
                                    }
                                }
                                objCommon.tracingService.Trace("after  setting other fields");

                                bool IsValidGuid;
                                Guid ParentAccountId;
                                if (AccountPayload.parentorganisation != null && !string.IsNullOrEmpty(AccountPayload.parentorganisation.parentorganisationcrmid))
                                {
                                    objCommon.tracingService.Trace("before checking value");
                                    IsValidGuid = Guid.TryParse(AccountPayload.parentorganisation.parentorganisationcrmid, out ParentAccountId);
                                    if (IsValidGuid)
                                    {
                                        var checkParentOrgExists = from c in orgSvcContext.CreateQuery("account")
                                                                   where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.ACCOUNTID] == AccountPayload.parentorganisation.parentorganisationcrmid
                                                                   select new
                                        {
                                            organisationid = c.Id
                                        };
                                        if (checkParentOrgExists.FirstOrDefault() != null)
                                        {
                                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.PARENTACCOUNTID]
                                                = new EntityReference(SCS.AccountContants.ENTITY_NAME, ParentAccountId);
                                            objCommon.tracingService.Trace("after assinging value");
                                        }
                                        else
                                        {
                                            objCommon.tracingService.Trace("throwing error becuase organisation does not exists.");
                                            throw new Exception("Parent account id does not exists.");
                                        }
                                    }
                                    else
                                    {
                                        objCommon.tracingService.Trace("invalid Guid.");
                                        throw new Exception("Invalid parent account Id.");
                                    }
                                }

                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.EMAILADDRESS1] = AccountPayload.email;
                                objCommon.tracingService.Trace("before createing guid:");
                                CrmGuid = objCommon.service.Create(AccountObject);

                                objCommon.CreateIdentifier(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, AccountPayload.crn, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid));
                                //create contactdetail record for primary contact details
                                if (AccountPayload.email != null)
                                {
                                    objCommon.tracingService.Trace("email id before upsert contact");
                                    objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, AccountPayload.email, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid), false, false);
                                    objCommon.tracingService.Trace("email id after upsert contact");
                                }
                                if (AccountPayload.telephone != null)
                                {
                                    objCommon.tracingService.Trace("telephone before upsert contact");

                                    objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, AccountPayload.telephone, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid), false, false);
                                    objCommon.tracingService.Trace("telephone after upsert contact");
                                }

                                objCommon.tracingService.Trace("after createing guid:{0}", CrmGuid.ToString());
                                Entity AccountRecord = objCommon.service.Retrieve("account", CrmGuid, new Microsoft.Xrm.Sdk.Query.ColumnSet(SCS.AccountContants.UNIQUEREFERENCE));
                                UniqueReference = (string)AccountRecord[SCS.AccountContants.UNIQUEREFERENCE];
                                if (AccountPayload.address != null)
                                {
                                    objCommon.CreateAddress(AccountPayload.address, new EntityReference(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME, CrmGuid));
                                }
                                ErrorCode = 200;
                            }
                            else
                            {
                                ErrorCode    = 412;
                                ErrorMessage = ErrorMessage.Append(string.Format("Company house id already exists.;"));
                            }
                        }
                        else
                        {
                            ErrorCode    = 400;
                            ErrorMessage = ErrorMessage.Append(string.Format("Option set value {0} for orgnisation type does not exists.",
                                                                             AccountPayload.type));
                        }
                    }
                    else
                    {
                        ErrorCode    = 400;
                        ErrorMessage = ErrorMessage.Append(string.Format("Option set value {0} for orgnisation hirarchy level not found.",
                                                                         AccountPayload.hierarchylevel));
                    }
                }
                else
                {
                    objCommon.tracingService.Trace("inside validation result");
                    //ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResults)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }

                    if (ValidationResultsAddress != null)
                    {
                        foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResultsAddress)
                        {
                            ErrorMessage.Append(vr.ErrorMessage + " ");
                        }
                    }
                    ErrorCode = 400;
                }
            }
            catch (Exception ex)
            {
                objCommon.tracingService.Trace("inside exception");

                ErrorCode = 500;
                ErrorMessage.Append(ex.Message);
                _ErrorMessageDetail = ex.Message;
                ErrorCode           = 400;
                this.response.Set(executionContext, _ErrorMessageDetail);
                objCommon.tracingService.Trace(ex.Message);
            }
            finally
            {
                objCommon.tracingService.Trace("finally block start");
                SCIIR.AccountResponse responsePayload = new SCIIR.AccountResponse()
                {
                    code     = ErrorCode,
                    message  = ErrorMessage.ToString(),
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",

                    status = ErrorCode == 200 ? "success" : "failure",
                    data   = new SCIIR.AccountData()
                    {
                        accountid       = CrmGuid,
                        uniquereference = UniqueReference,
                        error           = new SCIIR.ResponseErrorBase()
                        {
                            details = _ErrorMessageDetail
                        }
                    }
                };
                objCommon.tracingService.Trace("attempting to serialise");

                string json = JsonConvert.SerializeObject(responsePayload);

                response.Set(executionContext, json);
                // OutputCode.Set(executionContext, _errorCode);

                objCommon.tracingService.Trace("json {0}", json);
                objCommon.tracingService.Trace("finally block end");
            }
        }
 private IQueryable <TEntity> FilterWebFiles <TEntity>(OrganizationServiceContext context, IQueryable <TEntity> queryable) where TEntity : Entity
 {
     return(FilterByWebsiteAndSecurity(context, queryable));
 }
        public override IEnumerable <Tuple <Entity, EntityReference> > GetTreeParents(OrganizationServiceContext serviceContext, EntityReference website)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }
            if (website == null)
            {
                throw new ArgumentNullException("website");
            }

            try
            {
                return(serviceContext.CreateQuery("adx_blog")
                       .Where(e => e.GetAttributeValue <EntityReference>("adx_websiteid") == website)
                       .ToArray()
                       .Select(e => new Tuple <Entity, EntityReference>(e, e.GetAttributeValue <EntityReference>("adx_parentpageid"))));
            }
            catch (FaultException <OrganizationServiceFault> )
            {
                return(new Tuple <Entity, EntityReference>[] {});
            }
        }
 private bool HasReadAccess <TEntity>(OrganizationServiceContext context, TEntity entity) where TEntity : Entity
 {
     return(_securityProvider.TryAssert(context, entity, CrmEntityRight.Read));
 }
Exemple #35
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = factory.CreateOrganizationService(context.UserId);

                if (context.MessageName == "Create")
                {
                    object blok = new object();
                    int? number;
                    new_constant counter = new new_constant();
                    Entity entity = (Entity)context.InputParameters["Target"];

                    string correntYear = DateTime.Now.ToString("yy");

                    lock (blok)
                    {
                        using (var orgContext = new OrganizationServiceContext(service))
                        {
                            var getCounterValue = (from c in orgContext.CreateQuery<new_constant>()
                                                   select c).FirstOrDefault();

                            switch (entity.LogicalName)
                            {
                                case new_purchase_order.EntityLogicalName:
                                    number = getCounterValue.new_purchase_order;
                                    counter.new_purchase_order = ++number;
                                    if (entity.Attributes.Contains("new_name") == true)
                                        entity["new_name"] = $"{number}/{correntYear}";
                                    else
                                        entity.Attributes.Add("new_name", $"{number}/{correntYear}");
                                    break;
                                case new_purchase_order_change.EntityLogicalName:
                                    number = getCounterValue.new_purchase_order_change;
                                    counter.new_purchase_order_change = ++number;;
                                    if (entity.Attributes.Contains("new_name") == true)
                                        entity["new_name"] = $"{number}/{correntYear}";
                                    else
                                        entity.Attributes.Add("new_name", $"{number}/{correntYear}");
                                    break;
                                case new_purchase_deal.EntityLogicalName:
                                    number = getCounterValue.new_purchase_deal;
                                    counter.new_purchase_deal = ++number;
                                    if (entity.Attributes.Contains("new_name") == true)
                                        entity["new_name"] = $"{number}/{correntYear}";
                                    else
                                        entity.Attributes.Add("new_name", $"{number}/{correntYear}");
                                    break;
                                case new_purchase_task.EntityLogicalName:
                                    number = getCounterValue.new_purchase_deal;
                                    counter.new_purchase_task = ++number;
                                    if (entity.Attributes.Contains("new_name") == true)
                                        entity["new_name"] = $"{number}/{correntYear}";
                                    else
                                        entity.Attributes.Add("new_name", $"{number}/{correntYear}");
                                    break;
                                default:
                                    return;
                            }

                            counter.Id = getCounterValue.Id;
                            service.Update(counter);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
Exemple #36
0
        private ApplicationPath GetIdeaApplicationPath(OrganizationServiceContext context, Entity idea)
        {
            idea.AssertEntityName("adx_idea");

            var httpContext = HttpContext.Current;

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

            var partialUrl = idea.GetAttributeValue <string>("adx_partialurl");

            if (string.IsNullOrEmpty(partialUrl))
            {
                return(null);
            }

            var ideaForumEntityReference = idea.GetAttributeValue <EntityReference>("adx_ideaforumid");

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

            var forum = context.CreateQuery("adx_ideaforum").FirstOrDefault(e => e.GetAttributeValue <EntityReference>("adx_ideaforumid").Id == ideaForumEntityReference.Id);

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

            var forumPartialUrl = forum.GetAttributeValue <string>("adx_partialurl");

            if (string.IsNullOrEmpty(forumPartialUrl))
            {
                return(null);
            }

            var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            var routeData          = RouteTable.Routes.GetRouteData(httpContextWrapper);

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

            var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, routeData));

            // If multi-language is enabled, return URL using in approriate multi-language URL format.
            var    contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
            string url = string.Empty;

            if (contextLanguageInfo.IsCrmMultiLanguageEnabled && ContextLanguageInfo.DisplayLanguageCodeInUrl)
            {
                url = string.Format("{0}{1}", httpContext.Request.Url.GetLeftPart(UriPartial.Authority), urlHelper.Action("Ideas", "Ideas", new { ideaForumPartialUrl = forumPartialUrl, ideaPartialUrl = partialUrl, area = "Ideas" }));
                url = contextLanguageInfo.FormatUrlWithLanguage(false, contextLanguageInfo.ContextLanguage.Code, new Uri(url));
            }
            else
            {
                url = urlHelper.Action("Ideas", "Ideas", new { ideaForumPartialUrl = forumPartialUrl, ideaPartialUrl = partialUrl, area = "Ideas" });
            }

            return(url == null ? null : ApplicationPath.FromAbsolutePath(url));
        }
        public void When_Creating_Using_Organization_Context_Record_Should_Be_Created()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);
                ctx.SaveChanges();
            }

            Assert.NotNull(service.Retrieve(Account.EntityLogicalName, account.Id, new ColumnSet(true)));
        }
        public void EarlyBoundCreateApplicationAndPermitSuccess3()
        {
            OrganizationServiceContext orgContext = new OrganizationServiceContext(OrganizationServiceProxy);

            EarlyBoundCreateApplication(orgContext, defra_ApplicationType.NewApplication);
        }
        public bool CreateQuoteDetail(ExcelProxyQuotedetail quotedetail, EntityReference product)
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {
                var newquoteDetail = new QuoteDetail()
                {
                    ProductId = product,
                    new_SKU = quotedetail.SKU,
                    new_manufacturingname = findVendor(quotedetail.Vendor),
                    IsPriceOverridden = true,
                    Quantity = Convert.ToInt32(quotedetail.quantity),
                    PricePerUnit = new Money(Convert.ToDecimal(quotedetail.priceperunit)),
                    new_usdprice = Convert.ToDecimal(quotedetail.new_usdprice),
                    new_totalpurchaseusd = Convert.ToDouble(quotedetail.new_totalpurchaseusd),
                    new_koef = Convert.ToDecimal(quotedetail.new_koef),
                    QuoteId = mainEntityId,
                    new_sellingusd = Convert.ToDouble(quotedetail.new_sellingusd),
                    new_generalsellingusd = Convert.ToDouble(quotedetail.new_generalsellingusd),
                    new_exchangerate = Convert.ToDouble(quotedetail.exchangeRates),
                    UoMId = (from i in orgContext.CreateQuery<UoM>()
                             where i.Name == "Базовая единица"
                             select new EntityReference
                             {
                                 Id = i.Id,
                                 LogicalName = i.LogicalName,
                                 Name = i.Name
                             }).FirstOrDefault()
                };

                try
                {
                    service.Create(newquoteDetail);
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
            return true;
        }
Exemple #40
0
        private void MapRelationshipAttributesToEntity(Entity source, ICrmService crm, OrganizationServiceContext context)
        {
            foreach (var property in GetProperties(this))
            {
                var attribute = EntityRelationshipAttribute(property);
                var value     = property.GetValue(this);

                if (attribute == null || value == null)
                {
                    continue;
                }

                foreach (var relatedModel in EnumerableRelationshipModels(value))
                {
                    var shouldMap = ShouldMapRelationship(property.Name, relatedModel, crm);
                    if (!shouldMap)
                    {
                        continue;
                    }

                    var target = relatedModel.ToEntity(crm, context);
                    crm.AddLink(source, new Relationship(attribute.Name), target, context);
                }
            }
        }
 private EntityReference findVendor(string name)
 {
     using (var orgContext = new OrganizationServiceContext(service))
     {
         EntityReference vendor = (from q in orgContext.CreateQuery<new_manufacturer>()
                                   where q.new_name == name
                                   select new EntityReference
                                   {
                                       Id = q.Id,
                                       Name = q.new_name,
                                       LogicalName = q.LogicalName
                                   }).FirstOrDefault();
         if (vendor == null)
         {
             // Create vendor
             var newid = service.Create(new new_manufacturer
             {
                 new_name = name
             });
             return new EntityReference
             {
                 Id = newid,
                 Name = name,
                 LogicalName = new_manufacturer.EntityLogicalName
             };
         }
         else
         {
             return vendor;
         }
     }
 }
Exemple #42
0
 protected virtual void ExecuteInternal(string folder, OrganizationServiceContext ctx, bool backupFiles)
 {
 }
Exemple #43
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                // Service implements IOrganizationService interface
                if (service.IsReady)
                {
                    #region Sample Code
                    /////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    //Create Query Expression.
                    var query = new QueryExpression()
                    {
                        EntityName   = "role",
                        ColumnSet    = new ColumnSet("name"),
                        LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName    = Role.EntityLogicalName,
                                LinkFromAttributeName = "roleid",
                                LinkToEntityName      = SystemUserRoles.EntityLogicalName,
                                LinkToAttributeName   = "roleid",
                                LinkCriteria          = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "systemuserid",
                                            Operator      = ConditionOperator.Equal,
                                            Values        = { userId }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    // Obtain results from the query expression.
                    EntityCollection ec = service.RetrieveMultiple(query);

                    // Display results.
                    for (int i = 0; i < ec.Entities.Count; i++)
                    {
                        Console.WriteLine("Query Expression Retrieved: {0}", ((Role)ec.Entities[i]).Name);
                    }

                    #endregion
                    #region Retrieve records from an intersect table via Fetch

                    // Setup Fetch XML.
                    StringBuilder linkFetch = new StringBuilder();
                    linkFetch.Append("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">");
                    linkFetch.Append("<entity name=\"role\">");
                    linkFetch.Append("<attribute name=\"name\"/>");
                    linkFetch.Append("<link-entity name=\"systemuserroles\" from=\"roleid\" to=\"roleid\" visible=\"false\" intersect=\"true\">");
                    linkFetch.Append("<filter type=\"and\">");
                    linkFetch.Append("<condition attribute=\"systemuserid\" operator=\"eq\" value=\"" + userId + "\"/>");
                    linkFetch.Append("</filter>");
                    linkFetch.Append("</link-entity>");
                    linkFetch.Append("</entity>");
                    linkFetch.Append("</fetch>");

                    // Build fetch request and obtain results.
                    var efr = new RetrieveMultipleRequest()
                    {
                        Query = new FetchExpression(linkFetch.ToString())
                    };
                    EntityCollection entityResults = ((RetrieveMultipleResponse)service.Execute(efr)).EntityCollection;

                    // Display results.
                    foreach (var e in entityResults.Entities)
                    {
                        Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]);
                    }

                    #endregion
                    #region Retrieve records from an intersect table via LINQ

                    // Obtain the Organization Context.
                    OrganizationServiceContext context = new OrganizationServiceContext(service);

                    // Create Linq Query.
                    var roles = (from r in context.CreateQuery <Role>()
                                 join s in context.CreateQuery <SystemUserRoles>() on r.RoleId equals s.RoleId
                                 where s.SystemUserId == userId
                                 orderby r.RoleId
                                 select r.Name);

                    // Display results.
                    foreach (var role in roles)
                    {
                        Console.WriteLine("Linq Retrieved: {0}", role);
                    }
                    #endregion Demonstrate
                    #region Clean up
                    // Provides option to delete the ChangeTracking solution
                    CleanUpSample(service);
                    #endregion Clean up
                    //////////////////////////////////////////////
                    #endregion Sample Code
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
 /// <summary>
 /// Class initialization
 /// </summary>
 /// <param name="source">Entity</param>
 /// <param name="context">Organization Service Context</param>
 public NoteReplication(Entity source, OrganizationServiceContext context) : base(source, context, "annotation")
 {
 }
        protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security)
        {
            if (!IsRequestMethod(context.Request, "GET"))
            {
                throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
            }

            var children = GetChildren(serviceContext, entity, entityMetadata)
                           .Where(child => security.TryAssert(serviceContext, child, CrmEntityRight.Read))
                           .ToList();

            children.Sort(new EntitySiteMapDisplayOrderComparer());

            var entityMetadataCache = new Dictionary <string, CmsEntityMetadata>();

            var childInfos = children.Select(e =>
            {
                var info = new ExtendedSiteMapChildInfo
                {
                    Title             = GetChildTitle(e),
                    EntityUri         = VirtualPathUtility.ToAbsolute(CmsEntityRouteHandler.GetAppRelativePath(portalScopeId, e.ToEntityReference())),
                    HasPermission     = security.TryAssert(serviceContext, e, CrmEntityRight.Change),
                    Id                = e.Id,
                    LogicalName       = e.LogicalName,
                    HiddenFromSiteMap = e.Attributes.Contains("adx_hiddenfromsitemap") && e.GetAttributeValue <bool?>("adx_hiddenfromsitemap").GetValueOrDefault(),
                    Url               = e.Contains("adx_partialurl") ? e.GetAttributeValue <string>("adx_partialurl") : null
                };

                CmsEntityMetadata childEntityMetadata;

                if (TryGetEntityMetadata(serviceContext, e.LogicalName, entityMetadataCache, out childEntityMetadata))
                {
                    if (childEntityMetadata.HasAttribute("adx_displayorder"))
                    {
                        info.DisplayOrder             = e.Attributes.Contains("adx_displayorder") ? e.GetAttributeValue <int?>("adx_displayorder") : null;
                        info.DisplayOrderPropertyName = "adx_displayorder";
                    }
                }

                return(info);
            }).ToArray();

            var childJson = SerializeChildInfos(childInfos);

            WriteResponse(context.Response, new JObject
            {
                { "d", new JRaw(childJson) }
            });
        }
        private bool FindAndDeactivateEntity(DateTime date)
        {
            using (var orgContext = new OrganizationServiceContext(this.service))
            {
                var currencyFromCrm = (from i in orgContext.CreateQuery<sl_ExchangeRate>()
                                       where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate)
                                       && i.statecode == sl_ExchangeRateState.Active
                                       select i).ToList();

                if (currencyFromCrm.Count == 0)
                {
                    return true;
                }

                // деактивация устаревших курсов State = Close

                foreach (var item in currencyFromCrm)
                {
                    SetStateRequest deactivateRequest = new SetStateRequest()
                    {
                        EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id),
                        State = new OptionSetValue(1),
                        Status = new OptionSetValue(-1)
                    };
                    orgContext.Execute(deactivateRequest);
                }
                return true;
            }
        }
Exemple #47
0
        protected Entity SelectAlert(OrganizationServiceContext serviceContext, EntityReference user)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            var metadataRequest = new RetrieveEntityRequest
            {
                LogicalName   = RecordReference.LogicalName,
                EntityFilters = EntityFilters.Attributes
            };

            var metadataResponse = (RetrieveEntityResponse)serviceContext.Execute(metadataRequest);

            var primaryIdFieldName = metadataResponse.EntityMetadata.PrimaryIdAttribute;

            var fetchXmlString = string.Format(@"
					<fetch mapping=""logical"" distinct=""true"">
						<entity name=""adx_alertsubscription"">
							<attribute name=""activityid""/>
							<attribute name=""subject""/>
							<attribute name=""createdon""/>
							<link-entity name=""activityparty"" from=""activityid"" to=""activityid"" alias=""aa"">
								<filter type=""and"">
									<condition attribute=""partyid"" operator=""eq"" />
								</filter>
							</link-entity>
							<link-entity name=""{0}"" from=""{1}"" to=""regardingobjectid"" alias=""ab"">
								<filter type=""and"">
									<condition attribute=""{2}"" operator=""eq"" />
								</filter>
							</link-entity>
						</entity>
					</fetch>"                    , RecordReference.LogicalName, primaryIdFieldName, primaryIdFieldName);

            var fetchXml = XDocument.Parse(fetchXmlString);

            var recordIdAttribute = fetchXml.XPathSelectElement(string.Format("//condition[@attribute='{0}']", primaryIdFieldName));

            if (recordIdAttribute == null)
            {
                throw new InvalidOperationException("Unable to select the regarding record filter element.");
            }

            recordIdAttribute.SetAttributeValue("value", RecordReference.Id.ToString());

            var contactIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='partyid']");

            if (contactIdAttribute == null)
            {
                throw new InvalidOperationException("Unable to select the contact filter element.");
            }

            contactIdAttribute.SetAttributeValue("value", user.Id.ToString());

            var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
            {
                Query = new FetchExpression(fetchXml.ToString())
            });

            return(response.EntityCollection.Entities.FirstOrDefault());
        }
        public override IEnumerable <Tuple <Entity, EntityReference> > GetTreeParents(OrganizationServiceContext serviceContext, EntityReference website)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }
            if (website == null)
            {
                throw new ArgumentNullException("website");
            }

            try
            {
                return((from post in serviceContext.CreateQuery("adx_blogpost")
                        join blog in serviceContext.CreateQuery("adx_blog") on post.GetAttributeValue <EntityReference>("adx_blogid") equals new EntityReference("adx_blog", blog.GetAttributeValue <Guid>("adx_blogid"))
                        where blog.GetAttributeValue <EntityReference>("adx_websiteid") == website
                        select post)
                       .ToArray()
                       .Select(e => new Tuple <Entity, EntityReference>(e, e.GetAttributeValue <EntityReference>("adx_blogid"))));
            }
            catch (FaultException <OrganizationServiceFault> )
            {
                return(new Tuple <Entity, EntityReference>[] {});
            }
        }
Exemple #49
0
        private Entity CreateAlertEntity(EntityReference user, OrganizationServiceContext serviceContext)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (user.LogicalName != "contact")
            {
                throw new ArgumentException(string.Format("Value must have logical name '{0}'", user.LogicalName), "user");
            }

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));


            var existingAlert = SelectAlert(serviceContext, user);

            if (existingAlert != null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, Alert Exists", user.LogicalName, user.Id));

                return(null);
            }

            var metadataRequest = new RetrieveEntityRequest
            {
                LogicalName   = RecordReference.LogicalName,
                EntityFilters = EntityFilters.Attributes
            };

            var metadataResponse = (RetrieveEntityResponse)serviceContext.Execute(metadataRequest);

            var primaryIdFieldName = metadataResponse.EntityMetadata.PrimaryIdAttribute;

            var primaryNameFieldName = metadataResponse.EntityMetadata.PrimaryNameAttribute;

            var record = serviceContext.CreateQuery(RecordReference.LogicalName).FirstOrDefault(
                r => r.GetAttributeValue <Guid>(primaryIdFieldName) == RecordReference.Id);

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

            var alert = new Entity("adx_alertsubscription");

            alert["regardingobjectid"] = RecordReference;

            //assign the contact to the customer s list
            var activityparty = new Entity("activityparty");

            activityparty["partyid"] = user;

            var particpant = new EntityCollection(new List <Entity> {
                activityparty
            });

            alert["customers"] = particpant;

            alert["subject"] = string.Format(ResourceManager.GetString("Subscription_Added_Alert_Message"), contact.GetAttributeValue <string>("fullname"),
                                             record.GetAttributeValue <string>(primaryNameFieldName));
            return(alert);
        }
        public void When_Creating_Using_Organization_Context_Without_Saving_Changes_Record_Should_Not_Be_Created()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var account = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                ctx.AddObject(account);

                var retrievedAccount = ctx.CreateQuery<Account>().SingleOrDefault(acc => acc.Id == account.Id);
                Assert.Null(retrievedAccount);
            }
        }
 public abstract Entity GetEntity(OrganizationServiceContext serviceContext, Guid id, EntityReference website);
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            try
            {
                try
                {
                    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                    var contexto = new OrganizationServiceContext(service);

                    string json = string.Empty;
                    if (context.InputParameters.Contains("OpportunityClose") &&
                        context.InputParameters["OpportunityClose"] is Entity)
                    {
                        Entity oppClose = (Entity)context.InputParameters["OpportunityClose"];
                        var opp = new OpportunityLocal();
                        var aco = new AccountLocal();
                        opp.accountlocal = aco;
                        opp.productopportunitylocal = new List<ProductOpportunityLocal>();
                        if (oppClose.Attributes.Contains("opportunityid"))
                        {
                            //Pega a referência da oportunidade que está sendo fechada
                            var oppRef = (EntityReference)oppClose["opportunityid"];
                            //Recupera todos os campos da oportunidade
                            var opportunityWin = service.Retrieve(oppRef.LogicalName, oppRef.Id, new ColumnSet(true));
                            //Atribuir os valores da oportunidade
                            opp.SetOpportunityLocal(opportunityWin);

                            if (opportunityWin.Attributes.ContainsKey("parentaccountid"))
                            {
                                //Pega a referência da conta
                                var acoRef = (EntityReference)opportunityWin["parentaccountid"];
                                //Recupera produtos da oportunidade
                                var opportunityWinAccount = service.Retrieve("account", acoRef.Id, new ColumnSet(true));
                                //Atribuir os valores da conta
                                aco.SetAccountLocal(opportunityWinAccount);

                                //Montar Oportunidade
                                opp.accountlocal = aco;
                            }

                            QueryExpression opportunityProductsQuery = new QueryExpression
                            {
                                EntityName = OpportunityProduct.EntityLogicalName,
                                ColumnSet = new ColumnSet(true),
                                Criteria = new FilterExpression
                                {
                                    Conditions =
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "opportunityid",
                                        Operator = ConditionOperator.Equal,
                                        Values = { oppRef.Id }
                                    }
                                }
                                }
                            };

                            DataCollection<Entity> opportunityProducts = service.RetrieveMultiple(opportunityProductsQuery).Entities;
                            foreach (Entity entity in opportunityProducts)
                            {
                                OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
                                var pop = new ProductOpportunityLocal();
                                pop.SetProductOpportunityLocal(opportunityProduct);
                                opp.productopportunitylocal.Add(pop);
                            }
                        }

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OpportunityLocal));
                            serializer.WriteObject(memoryStream, opp);
                            json = Encoding.UTF8.GetString(memoryStream.ToArray());
                        }

                        string URI = "http://posttestserver.com/post.php?dir=xiaoxiao";

                        using (WebClient wc = new WebClient())
                        {
                            string responseJson = string.Empty;
                            wc.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
                            wc.Headers[HttpRequestHeader.Accept] = "application/json; charset=utf-8";

                            string HtmlResult = wc.UploadString(URI, json);
                        }
                    }
                }

                catch (WebException exception)
                {
                    string str = string.Empty;
                    if (exception.Response != null)
                    {
                        using (StreamReader reader =
                            new StreamReader(exception.Response.GetResponseStream()))
                        {
                            str = reader.ReadToEnd();
                        }
                        exception.Response.Close();
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                            "The timeout elapsed while attempting to issue the request.", exception);
                    }
                    throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                        "A Web exception occurred while attempting to issue the request. {0}: {1}",
                        exception.Message, str), exception);
                }
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }
        }
 public abstract IEnumerable <Entity> GetEntityChildren(OrganizationServiceContext serviceContext, Entity entity, EntityReference website);
        public EntityReference ProductFromSpec(ExcelProxyProduct product, EntityReference priceName)
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {
                var finder = (from c in orgContext.CreateQuery<Product>()
                              where c.ProductNumber == product.SKU
                              select c).FirstOrDefault();

                if (finder != null)
                {
                    var entityProduct = new Product()
                    {
                        Id = finder.Id,
                        ProductNumber = product.SKU,
                        Name = product.Product,
                        DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>()
                                                where i.Name == "Единица измерения по умолчанию"
                                                select new EntityReference
                                                {
                                                    Id = i.Id,
                                                    LogicalName = i.LogicalName,
                                                    Name = i.Name
                                                }).FirstOrDefault(),

                        DefaultUoMId = (from i in orgContext.CreateQuery<UoM>()
                                        where i.Name == "Базовая единица"
                                        select new EntityReference
                                        {
                                            Id = i.Id,
                                            LogicalName = i.LogicalName,
                                            Name = i.Name
                                        }).FirstOrDefault(),
                        new_manufacturingname = findVendor(product.Vendor)
                    };

                    try
                    {
                        service.Update(entityProduct);
                        return new EntityReference
                        {
                            Id = entityProduct.Id,
                            Name = entityProduct.Name,
                            LogicalName = entityProduct.LogicalName
                        };
                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return CreateProduct(product, priceName);
                }
            }
        }
 public abstract IEnumerable <Tuple <Entity, EntityReference> > GetTreeParents(OrganizationServiceContext serviceContext, EntityReference website);
        public void When_updating_a_not_existing_entity_using_organization_context_exception_should_be_thrown()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var existingAccount = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                Assert.Throws<SaveChangesException>(() => ctx.SaveChanges());
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory   = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service          = serviceFactory.CreateOrganizationService(executionContext.InitiatingUserId);
            OrganizationServiceContext  sContext         = new OrganizationServiceContext(service);
            ITracingService             Trace            = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            Trace.Trace("CommentSetAttributePlugin Execute Method - Start");

            try
            {
                //*********************************************
                //Message: Create
                //Primary Entity: kli_comment
                //Filtering Attribute:
                //Pre Operation

                //Message: Update
                //Primary Entity: kli_comment
                //Filtering Attribute:
                //Pre Operation
                //*********************************************

                if (executionContext.Stage == 20 && executionContext.PrimaryEntityName == "kli_comment")
                {
                    Entity entComment = (Entity)executionContext.InputParameters["Target"];

                    if (executionContext.MessageName.ToLower() == "create")
                    {
                        // Set Custom CreatedBy and ModifiedBy
                        if (!entComment.Attributes.Contains("kli_modifiedbyid") || entComment.Attributes["kli_modifiedbyid"] == null)
                        {
                            entComment.Attributes["kli_modifiedbyid"]             = entComment.GetAttributeValue <EntityReference>("modifiedby").Id.ToString();
                            entComment.Attributes["kli_modifiedby"]               = GetSystemUserName(entComment.GetAttributeValue <EntityReference>("modifiedby").Id, sContext, service);
                            entComment.Attributes["kli_modifiedbyobjecttypecode"] = 8;


                            entComment.Attributes["kli_createdbyid"]             = entComment.GetAttributeValue <EntityReference>("modifiedby").Id.ToString();
                            entComment.Attributes["kli_createdby"]               = entComment.Attributes["kli_modifiedby"];
                            entComment.Attributes["kli_createdbyobjecttypecode"] = 8;

                            Trace.Trace("CommentSetAttributePlugin Update CreatedBy & ModifiedBy");
                        }
                    }
                    else
                    {
                        // Set Custom ModifiedBy
                        if (!entComment.Attributes.Contains("kli_modifiedbyid") || entComment.Attributes["kli_modifiedbyid"] == null)
                        {
                            entComment.Attributes["kli_modifiedbyid"]             = entComment.GetAttributeValue <EntityReference>("modifiedby").Id.ToString();
                            entComment.Attributes["kli_modifiedby"]               = GetSystemUserName(entComment.GetAttributeValue <EntityReference>("modifiedby").Id, sContext, service);
                            entComment.Attributes["kli_modifiedbyobjecttypecode"] = 8;

                            Trace.Trace("CommentSetAttributePlugin Update ModifiedBy");
                        }
                    }

                    // Set First 96 chars of comment to Name filed
                    if (entComment.Attributes.Contains("kli_plaintextcomment") && entComment.Attributes["kli_plaintextcomment"] != null)
                    {
                        string strComment = entComment.Attributes["kli_plaintextcomment"].ToString().Replace("\n", " ");
                        entComment.Attributes["kli_name"] = strComment.Length > 96 ? strComment.Substring(0, 96) + "..." : strComment;

                        Trace.Trace("CommentSetAttributePlugin Update Name");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
            Trace.Trace("CommentSetAttributePlugin Execute Method - End");
        }
        public EntityReference CreateProduct(ExcelProxyProduct product, EntityReference priceName)
        {
            using (var orgContext = new OrganizationServiceContext(service))
            {

                Product entityProduct = new Product()
                {
                    Id = Guid.NewGuid(),
                    ProductNumber = product.SKU,
                    Name = product.Product,
                    DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>()
                                            where i.Name == "Единица измерения по умолчанию"
                                            //where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF")
                                            select new EntityReference
                                            {
                                                Id = i.Id,
                                                LogicalName = i.LogicalName,
                                                Name = i.Name
                                            }).FirstOrDefault(),

                    DefaultUoMId = (from i in orgContext.CreateQuery<UoM>()
                                    where i.Name == "Базовая единица"
                                    //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666")
                                    select new EntityReference
                                    {
                                        Id = i.Id,
                                        LogicalName = i.LogicalName,
                                        Name = i.Name
                                    }).FirstOrDefault(),
                     new_manufacturingname = findVendor(product.Vendor)
                };

                try
                {
                    ///////////////////////////////////////
                    Guid idNewProduct = service.Create(entityProduct);

                    var productPriceLevel = new ProductPriceLevel()
                    {
                        PriceLevelId = priceName /*(from i in orgContext.CreateQuery<PriceLevel>()
                                        where i.Name == "Default Sales USD" //Default Sales USD
                                        select new EntityReference
                                        {
                                            LogicalName = PriceLevel.EntityLogicalName,
                                            Id = i.Id,
                                            Name = i.Name
                                        }).FirstOrDefault()*/,
                        UoMId = (from i in orgContext.CreateQuery<UoM>()
                                 where i.Name == "Базовая единица"
                                 select new EntityReference
                                 {
                                     Id = i.Id,
                                     LogicalName = i.LogicalName,
                                     Name = i.Name
                                 }).FirstOrDefault(),
                        ProductId = new EntityReference
                        {
                            Id = idNewProduct,
                            LogicalName = Product.EntityLogicalName,
                            Name = product.Product
                        }
                    };

                    var idProductPriceLevel = service.Create(productPriceLevel);

                    var updateNewProduct = new Product()
                    {
                        Id = idNewProduct,
                        PriceLevelId = priceName/*(from i in orgContext.CreateQuery<PriceLevel>()
                                        where i.Name == "Default Sales USD "
                                        select new EntityReference
                                        {
                                            LogicalName = PriceLevel.EntityLogicalName,
                                            Id = i.Id,
                                            Name = i.Name
                                        }).FirstOrDefault()*/
                    };
                    service.Update(updateNewProduct);

                    return new EntityReference
                    {
                        Id = idNewProduct,
                        Name = entityProduct.Name,
                        LogicalName = entityProduct.LogicalName
                    };
                    ///////////////////////////////////////

                }
                catch
                {
                    return null;
                }

            }
        }
        public void When_updating_an_entity_using_organization_context_changes_should_be_saved()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var existingAccount = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" };

            context.Initialize(new List<Entity>()
            {
                existingAccount
            });

            var service = context.GetFakedOrganizationService();

            using (var ctx = new OrganizationServiceContext(service))
            {
                existingAccount.Name = "Super Great Customer Name Updated!";

                ctx.Attach(existingAccount);
                ctx.UpdateObject(existingAccount);
                ctx.SaveChanges();
            }

            //Make other account wasn't updated
            var account = context.CreateQuery<Account>().Where(e => e.Id == existingAccount.Id).FirstOrDefault();
            Assert.Equal(account.Name, "Super Great Customer Name Updated!");
        }
Exemple #60
-1
        /// <summary>
        /// Demonstrates how to programmatically execute a workflow.
        /// </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();

                    OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);

                    CreateRequiredRecords();

                    //<snippetExecuteWorkflow1>
                    // Create an ExecuteWorkflow request.
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        WorkflowId = _workflowId,
                        EntityId = _leadId
                    };
                    Console.Write("Created ExecuteWorkflow request, ");

                    // Execute the workflow.
                    ExecuteWorkflowResponse response =
                        (ExecuteWorkflowResponse)_serviceProxy.Execute(request);
                    Console.WriteLine("and sent request to service.");

                    //</snippetExecuteWorkflow1>

                    #region Check success

                    ColumnSet cols = new ColumnSet("statecode");
                    QueryByAttribute retrieveOpQuery = new QueryByAttribute();
                    retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName;
                    retrieveOpQuery.ColumnSet = cols;
                    retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id);

                    // Wait for the asyncoperation to complete.
                    // (wait no longer than 1 minute)
                    for (int i = 0; i < 60; i++)
                    {
                        System.Threading.Thread.Sleep(1000);

                        EntityCollection retrieveOpResults =
                            _serviceProxy.RetrieveMultiple(retrieveOpQuery);

                        if (retrieveOpResults.Entities.Count() > 0)
                        {
                            AsyncOperation op =
                                (AsyncOperation)retrieveOpResults.Entities[0];
                            if (op.StateCode == AsyncOperationState.Completed)
                            {
                                _asyncOperationId = op.AsyncOperationId.Value;
                                Console.WriteLine("AsyncOperation completed successfully.");
                                break;
                            }
                        }

                        if (i == 59)
                        {
                            throw new TimeoutException("AsyncOperation failed to complete in under one minute.");
                        }
                    }

                    // Retrieve the task that was created by the workflow.
                    cols = new ColumnSet("activityid");
                    QueryByAttribute retrieveActivityQuery = new QueryByAttribute();
                    retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName;
                    retrieveActivityQuery.ColumnSet = cols;
                    retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade");
                    
                    EntityCollection results = 
                        _serviceProxy.RetrieveMultiple(retrieveActivityQuery);

                    if (results.Entities.Count() == 0)
                    {
                        throw new InvalidOperationException("Phone call activity was not successfully created");
                    }
                    else
                    {
                        Console.WriteLine("Phone call activity successfully created from workflow.");
                    }

                    #endregion Check success

                    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;
            }
        }