Exemple #1
0
        private static void Upload(OrganizationServiceManager osmSource, OrganizationServiceManager osmDestination)
        {
            var templates = GetTemplates(osmSource);

            Console.WriteLine($"\r\nFound {templates.Count} docx templates to upload");

            Parallel.ForEach(templates,
                             new ParallelOptions {
                MaxDegreeOfParallelism = 5
            },
                             (template =>
            {
                string name = template.GetAttributeValue <string>("name");
                Console.WriteLine($"Uploading {name}");

                try
                {
                    string etc = template.GetAttributeValue <string>("associatedentitytypecode");

                    int?oldEtc = GetEntityTypeCode(osmSource, etc);
                    int?newEtc = GetEntityTypeCode(osmDestination, etc);

                    string fileName = ReRouteEtcViaOpenXML(template, name, etc, oldEtc, newEtc);

                    template["associatedentitytypecode"] = newEtc;
                    template["content"] = Convert.ToBase64String(File.ReadAllBytes(fileName));

                    Guid existingId = TemplateExists(osmDestination, name);
                    if (existingId != null && existingId != Guid.Empty)
                    {
                        template["documenttemplateid"] = existingId;

                        osmDestination.GetProxy().Update(template);
                        Console.WriteLine($"Updated {name}");
                    }
                    else
                    {
                        Guid id = osmDestination.GetProxy().Create(template);
                        Console.WriteLine($"Created {name}");
                    }

                    File.Delete(fileName);     // delete the updated file but keep the original
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    Console.WriteLine($"Failed to upload {name}!");
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.Detail != null ? ex.Detail.TraceText : "");
                    Console.WriteLine(ex.InnerException != null ? ex.InnerException.Message : "");
                }
            }));
        }
        public void Execute()
        {
            var service = ServiceManager.GetProxy();
            var query   = CreateQuery();

            var contactsToUpdate = new List <Entity>();

            EntityCollection results;

            do
            {
                results = service.RetrieveMultiple(query);

                foreach (Entity contact in results.Entities)
                {
                    var resolver = new LayeredEntityAttributeResolver(contact);
                    var fullName = FullNameCalculator.Calculate(resolver);
                    if (fullName != resolver.GetAttributeValue <string>("mspfe_full_name"))
                    {
                        var toUpdate = new Entity("contact", contact.Id);
                        toUpdate["mspfe_full_name"] = fullName;
                        contactsToUpdate.Add(toUpdate);
                    }
                }

                query.PageInfo.PagingCookie = results.PagingCookie;
                query.PageInfo.PageNumber++;
            } while (results.MoreRecords);

            ServiceManager.ParallelProxy.Update(contactsToUpdate);
        }
        /// <summary>
        /// Demonstrates a claims-based, cross-realm connection to Organization.svc using a username, password, and alternate realm
        /// </summary>
        /// <remarks>
        /// Authentication will be handled by federated realm's identity provider. Issued token will be converted to current realm token that CRM will accept.
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicCrossRealmConnectionToCrm()
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("https://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, "username", "password", homeRealm: new Uri("https://myhomerealm.com"));

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates an online-federated connection to Organization.svc using a userprincipalname and password
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicConnectionToCrmOnline()
        {
            var serverUri = XrmServiceUriFactory.CreateOnlineOrganizationServiceUri("myorganization", CrmOnlineRegion.NA);
            var manager   = new OrganizationServiceManager(serverUri, "*****@*****.**", "password");

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates a basic Active Directory connection to Organization.svc using a username, password, and domain
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicADConnectionToCrm()
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("http://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, "username", "password", "mydomain");

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
        /// <summary>
        /// Demonstrates a claims-based connection to Organization.svc using a pre-authenticated instance of AuthenticationCredentials
        /// </summary>
        /// <remarks>
        /// OrganizationServiceManager stores endpoint metadata and security token. Instance can be reused to construct multiple organization service channels (OrganizationServiceProxy)
        /// </remarks>
        public static void BasicPreAuthConnectionToCrm(AuthenticationCredentials preAuthCredentials)
        {
            var serverUri = XrmServiceUriFactory.CreateOrganizationServiceUri("https://mycrmserver:5555/myorganization");
            var manager   = new OrganizationServiceManager(serverUri, preAuthCredentials);

            using (var proxy = manager.GetProxy())
            {
                //Do organization requests...
            }
        }
Exemple #7
0
        public static int?GetEntityTypeCode(OrganizationServiceManager osm, string entity)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest();

            request.LogicalName   = entity;
            request.EntityFilters = EntityFilters.Entity;

            RetrieveEntityResponse response = (RetrieveEntityResponse)osm.GetProxy().Execute(request);
            EntityMetadata         metadata = response.EntityMetadata;

            return(metadata.ObjectTypeCode);
        }
Exemple #8
0
        private static Task <EntityCollection> TestRetrieveMultiple(OrganizationServiceManager osm, int i)
        {
            QueryExpression qe = new QueryExpression("account")
            {
                ColumnSet = new ColumnSet("accountid", "name")
            };

            qe.PageInfo = new PagingInfo()
            {
                Count = i * 100, PageNumber = 1
            };

            // this is the important part - using the OrganizationServiceManager, we'll call GetProxy, this creates a clone of the original connection. this is what allows us to execute stuff in parallel...
            Task <EntityCollection> m = osm.GetProxy().RetrieveMultipleAsync(qe); // the *Async methods are defined inside the OptimizedConnectionExtensions.cs

            return(m);
        }
Exemple #9
0
        private static Guid TemplateExists(OrganizationServiceManager osm, string name)
        {
            Guid result = Guid.Empty;

            QueryExpression qe = new QueryExpression("documenttemplate");

            qe.Criteria.AddCondition("status", ConditionOperator.Equal, false); // only get active templates
            qe.Criteria.AddCondition("name", ConditionOperator.Equal, name);

            var results = osm.GetProxy().RetrieveMultiple(qe);

            if (results != null && results.Entities != null && results.Entities.Count > 0)
            {
                result = results[0].Id;
            }

            return(result);
        }
        private static void Pfe()
        {
            try
            {
                Console.WriteLine("Testing plain pfe");
                var manager = new OrganizationServiceManager(serviceUri);

                Parallel.ForEach(Enumerable.Range(0, 100000), (index) =>
                {
                    var proxy = manager.GetProxy();
                    proxy.EnableProxyTypes();
                    proxy.Execute(new WhoAmIRequest());
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #11
0
        private static List <Entity> GetTemplates(OrganizationServiceManager osm)
        {
            QueryExpression qe = new QueryExpression("documenttemplate")
            {
                ColumnSet = new ColumnSet("content", "name", "associatedentitytypecode", "documenttype", "clientdata")
            };

            qe.Criteria.AddCondition("status", ConditionOperator.Equal, false);   // only get active templates
            qe.Criteria.AddCondition("documenttype", ConditionOperator.Equal, 2); // only word docs
            qe.Criteria.AddCondition("createdbyname", ConditionOperator.NotEqual, "SYSTEM");

            var results = osm.GetProxy().RetrieveMultiple(qe);

            if (results != null && results.Entities != null && results.Entities.Count > 0)
            {
                return(results.Entities.ToList());
            }

            return(new List <Entity>());
        }
Exemple #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting, please wait...");

            var osmSource      = new OrganizationServiceManager(ConfigurationManager.AppSettings["source.org.url"]);
            var osmDestination = new OrganizationServiceManager(ConfigurationManager.AppSettings["destination.org.url"]);

            var response = osmSource.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;

            Console.WriteLine($"Logged into source crm as: {response.UserId}");

            response = osmDestination.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;
            Console.WriteLine($"Logged into destination crm as: {response.UserId}");

            Console.WriteLine("\r\nAre you sure you want to upload all templates to the destination? Y/N");
            string input = (Console.ReadLine() ?? "").ToLower();

            if (input == "y" || input == "yes")
            {
                Upload(osmSource, osmDestination);
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to crm...");

            // this example shows how to use existing user auth (no need to explicitly state user/pass). Take a look at the overloaded methods for explicit user/pass auth
            var osm = new OrganizationServiceManager(ConfigurationManager.AppSettings["crm.sdkurl.org"]);

            // test the connection first
            var response = osm.GetProxy().Execute(new WhoAmIRequest()) as WhoAmIResponse;

            Console.WriteLine(response.UserId);

            // lets look at doing 100 retrieves in parallel properly :)
            Console.WriteLine("starting to execute 100 retrives...");

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Task.Run(() =>
            {
                List <Task> tasks = new List <Task>();

                // loop through and create a bunch of things we want to execute asynchornously
                for (int i = 0; i < 100; i++)
                {
                    Task <EntityCollection> m = TestRetrieveMultiple(osm, i);

                    tasks.Add(m); // add the task to our list
                }

                Task.WaitAll(tasks.ToArray());
            }).Wait();

            sw.Stop();
            Console.WriteLine($"done!, took {sw.ElapsedMilliseconds}ms ({sw.ElapsedMilliseconds / 100m:N2}ms per retrieve)");
        }