示例#1
0
        static void Main(string[] args)
        {
            var conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(System.Configuration.ConfigurationManager.ConnectionStrings["CodeNow"].ConnectionString);

            Service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
            SolutionStats();
        }
示例#2
0
        private static void SaveToServerBatched(Entity[] entities, string connectionstring)
        {
            var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);

            var _entities = entities.ToList();

            while (_entities.Any())
            {
                var batch = _entities.Take(batchSize);
                batch.ToList().ForEach(b => _entities.Remove(b));

                var upserts = batch.Select(e => new UpsertRequest()
                {
                    Target = e
                });

                var req = new ExecuteMultipleRequest()
                {
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    Requests = new OrganizationRequestCollection()
                };
                req.Requests.AddRange(upserts);

                var resp = (ExecuteMultipleResponse)service.Execute(req);

                var faults = resp.Responses.Where(r => r.Fault != null);

                faults.ToList().ForEach(f => logerror(f.Fault.Message));
            }
        }
        /// <summary>
        /// Background Worker Event DoWork
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Microsoft.Xrm.Tooling.Connector.CrmServiceClient crmServiceClient = null;

            try
            {
                using (Core.Xrm.ToolingConnector toolingConnector = new Core.Xrm.ToolingConnector())
                {
                    Core.Xrm.CrmConnection crmConnection = this.selectedCrmConnection;

                    crmServiceClient = toolingConnector.GetCrmServiceClient(crmConnection.ConnectionString);

                    // Get Crm Solutions
                    this.crmSolutions.Clear();
                    this.crmSolutions = toolingConnector.GetCrmSolutions(crmServiceClient);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);

                if (!Properties.Settings.Default.DisableErrorReports)
                {
                    throw;
                }
            }
            finally
            {
                if (crmServiceClient != null)
                {
                    crmServiceClient.Dispose();
                }
            }
        }
示例#4
0
        private static void SaveN2NToServerSingle(Entity[] entities, string connectionstring)
        {
            var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);

            var req = new RetrieveRelationshipRequest
            {
                Name = entities[0].LogicalName
            };
            var metadata     = (RetrieveRelationshipResponse)service.Execute(req);
            var relationship = (ManyToManyRelationshipMetadata)metadata.RelationshipMetadata;

            foreach (var e in entities)
            {
                var exists = false;
                try
                {
                    var existingEntity = service.Retrieve(e.LogicalName, e.Id, new ColumnSet());
                    if (existingEntity != null)
                    {
                        exists = true;
                    }
                }
                catch { }

                if (!exists)
                {
                    var rc = new EntityReferenceCollection();
                    rc.Add(new EntityReference(relationship.Entity2LogicalName, e.GetAttributeValue <Guid>(relationship.Entity2IntersectAttribute)));
                    service.Associate(relationship.Entity1LogicalName
                                      , e.GetAttributeValue <Guid>(relationship.Entity1IntersectAttribute)
                                      , new Relationship(relationship.SchemaName)
                                      , rc);
                }
            }
        }
示例#5
0
        private IOrganizationService GetService()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var conn    = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(_connectionString);
            var service = conn.OrganizationWebProxyClient ?? conn.OrganizationServiceProxy as IOrganizationService;

            return(service);
        }
示例#6
0
        public void UpdateExchangeRates(Dictionary <string, decimal> exchangeRates)
        {
            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["Xrm"].ToString();
            var    client  = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connStr);

            using (var ctx = new CrmServiceContext(client))
            {
                // Get the base currency
                var baseCurrencyCode =
                    ctx.TransactionCurrencySet
                    .Join(ctx.OrganizationSet
                          , t => t.TransactionCurrencyId
                          , o => o.BaseCurrencyId.Id
                          , (t, o) => t.ISOCurrencyCode).FirstOrDefault();

                if (baseCurrencyCode == null)
                {
                    _log.Error("Cannot find base currency ISO code.");
                }
                _log.Info($"The base currency ISO code is {baseCurrencyCode}.");

                var baseRate = exchangeRates[baseCurrencyCode];

                // Get all currencies
                var currencies = ctx.TransactionCurrencySet
                                 .Select(t => new TransactionCurrency()
                {
                    TransactionCurrencyId = t.TransactionCurrencyId,
                    ISOCurrencyCode       = t.ISOCurrencyCode
                })
                                 .ToArray();

                // Loop through and update the exchange rates
                foreach (var c in currencies)
                {
                    if (String.Equals(c.ISOCurrencyCode, baseCurrencyCode, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    var rate = exchangeRates[c.ISOCurrencyCode] / baseRate;
                    _log.Info($"Updating {exchangeRates[c.ISOCurrencyCode]}: {rate} to D365.");

                    ctx.Execute(new UpdateRequest()
                    {
                        Target = new TransactionCurrency()
                        {
                            TransactionCurrencyId = c.TransactionCurrencyId,
                            ExchangeRate          = rate
                        }
                    });
                }
            }
        }
示例#7
0
 private static EntityCollection ExecutePagedQuery(Microsoft.Xrm.Tooling.Connector.CrmServiceClient service, QueryExpression query, int page, string pagingCookie = null)
 {
     query.PageInfo = new PagingInfo()
     {
         Count = 1000, PageNumber = page
     };
     if (pagingCookie != null)
     {
         query.PageInfo.PagingCookie = pagingCookie;
     }
     return(service.RetrieveMultiple(query));
 }
        public OrganizationService()
        {
            if (ForcedOrganization != null)
            {
                this.instance = ForcedOrganization;
                return;
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var connectionString = ConnectionString.Value;

            if (connectionString.Contains("ClientSecret"))
            {
                this.instance = new OAuthOrganizationService();
            }
            else
            {
                try
                {
                    var client = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
                    client.OrganizationServiceProxy.EnableProxyTypes(typeof(OrganizationService).Assembly);
                    this.instance = client;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error creating organization service: {ex.Message}");
                    Console.Write("Retrying with user/pwd approach...");
                    try
                    {
                        ClientCredentials clientCredentials = new ClientCredentials();
                        clientCredentials.UserName.UserName = connectionString.GetParameter("Username");
                        clientCredentials.UserName.Password = connectionString.GetParameter("Password");

                        var uri = new Uri($"{connectionString.GetParameter("Url")}/XRMServices/2011/Organization.svc");

                        var proxy = new OrganizationServiceProxy(uri, null, clientCredentials, null);
                        proxy.EnableProxyTypes(typeof(OrganizationService).Assembly);
                        this.instance = proxy;
                        Console.WriteLine("Success.");
                    }
                    catch (Exception ex2)
                    {
                        Console.WriteLine("Error again!");
                        Console.WriteLine(ex.Message);
                        throw ex2;
                    }
                }
            }
        }
示例#9
0
        private static void SaveToServerSingle(Entity[] entities, string connectionstring)
        {
            var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);

            foreach (var e in entities)
            {
                var upsert = new UpsertRequest()
                {
                    Target = e
                };
                var resp    = (UpsertResponse)service.Execute(upsert);
                var created = resp.RecordCreated ? "created" : "updated";
                log($"Record {created}");
            }
        }
示例#10
0
        /// <summary>
        /// Background Worker Event DoWork
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Microsoft.Xrm.Tooling.Connector.CrmServiceClient crmServiceClient = null;

            try
            {
                using (Core.Xrm.ToolingConnector toolingConnector = new Core.Xrm.ToolingConnector())
                {
                    List <Core.Xrm.CrmConnection> crmConnections = Core.Data.StorageExtensions.Load(MainWindow.EncryptionKey);
                    Core.Xrm.CrmConnection        crmConnection  = crmConnections.Find(x => x.Name == this.selectedCrmConnection);

                    crmServiceClient = toolingConnector.GetCrmServiceClient(crmConnection.ConnectionString);

                    // Get Crm Solutions
                    this.crmSolutions.Clear();
                    this.crmSolutions = toolingConnector.GetCrmSolutions(crmServiceClient);

                    foreach (Core.Xrm.CrmSolution solution in this.localSolutions)
                    {
                        if (this.crmSolutions.Exists(x => x.UniqueName == solution.UniqueName))
                        {
                            this.crmSolutions.Find(x => x.UniqueName == solution.UniqueName).LocalVersion = solution.LocalVersion;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);

                if (!Properties.Settings.Default.DisableErrorReports)
                {
                    throw;
                }
            }
            finally
            {
                if (crmServiceClient != null)
                {
                    crmServiceClient.Dispose();
                }
            }
        }
示例#11
0
        public Boolean InitMSCRM()
        {
            string url      = "https://nickdemo.crm.dynamics.com";
            string clientid = "16029716-2271-4876-b661-cd507b9aa811";
            string secret   = "=xBF./9n3NHcLtGRdz:mxHwNWB95C2lt";

            Microsoft.Xrm.Tooling.Connector.CrmServiceClient c = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(new Uri(url + "/XRMServices/2011/Organization.svc"), clientid, secret, false, "");
            service = (IOrganizationService)c;

            try
            {
                WhoAmIRequest  r  = new WhoAmIRequest();
                WhoAmIResponse re = (WhoAmIResponse)service.Execute(r);
            }
            catch (Exception e)
            {
                return(false);
            }
            return(true);
        }
示例#12
0
        private static void FetchParallel()
        {
            count = 0;
            CdsAuthHelper cdsAuthHelper = new CdsAuthHelper();

            using (var proxy = new OrganizationWebProxyClient(cdsAuthHelper.serviceUrl, false))
            {
                // Set Header with the token
                proxy.HeaderToken = cdsAuthHelper.token;

                string fetch = "<fetch mapping='logical' no-lock='true'>";
                fetch += "<entity name='account'>";
                fetch += "<attribute name='name'/>";
                fetch += "<attribute name='accountid'/>";
                fetch += "</entity>";
                fetch += "</fetch>";

                IDictionary <string, QueryBase> queries = new Dictionary <string, QueryBase>();
                queries.Add("result", new FetchExpression(fetch));

                Microsoft.Xrm.Tooling.Connector.CrmServiceClient context = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(proxy);

                var manager = new OrganizationServiceManager(context);

                IDictionary <string, EntityCollection> results = null;

                try
                {
                    results = manager.ParallelProxy.RetrieveMultiple(queries, true);

                    foreach (var result in results)
                    {
                        count += result.Value.Entities.Count;
                    }
                }
                catch (AggregateException ae)
                {
                    // Handle exceptions
                }
            }
        }
示例#13
0
        private static Entity[] GetEntitiesFromServer(string connectionstring, string queryxml)
        {
            var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);

            var resp = (FetchXmlToQueryExpressionResponse)service.Execute(new FetchXmlToQueryExpressionRequest()
            {
                FetchXml = queryxml
            });
            var query = resp.Query;
            int page  = 1;

            var results    = ExecutePagedQuery(service, query, page);
            var resultList = results.Entities.ToList();

            while (results.MoreRecords)
            {
                page++;
                results = ExecutePagedQuery(service, query, page, results.PagingCookie);
                resultList.AddRange(results.Entities.ToList());
            }

            return(resultList.ToArray());
        }
示例#14
0
 public CRMConnector()
 {
     crmSvc     = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(ConfigurationManager.ConnectionStrings["Dynamics"].ConnectionString);
     extractXml = System.Configuration.ConfigurationManager.AppSettings["extractXml"] == "true";
 }