private bool UpdateCrmAssembly(AssemblyItem assemblyItem, CrmConnection connection)
        {
            _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);

            try
            {
                string outputFileName = _selectedProject.Properties.Item("OutputFileName").Value.ToString();
                string path = GetOutputPath() + outputFileName;

                //Build the project
                SolutionBuild solutionBuild = _dte.Solution.SolutionBuild;
                solutionBuild.BuildProject(_dte.Solution.SolutionBuild.ActiveConfiguration.Name, _selectedProject.UniqueName, true);

                if (solutionBuild.LastBuildInfo > 0)
                    return false;

                //Make sure Major and Minor versions match
                Version assemblyVersion = Version.Parse(_selectedProject.Properties.Item("AssemblyVersion").Value.ToString());
                if (assemblyItem.Version.Major != assemblyVersion.Major ||
                    assemblyItem.Version.Minor != assemblyVersion.Minor)
                {
                    _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Major & Minor Versions Require Redeployment", Logger.MessageType.Error);
                    return false;
                }

                //Make sure assembly names match
                string assemblyName = _selectedProject.Properties.Item("AssemblyName").Value.ToString();
                if (assemblyName.ToUpper() != assemblyItem.Name.ToUpper())
                {
                    _logger.WriteToOutputWindow("Error Updating Assembly In CRM: Changes To Assembly Name Require Redeployment", Logger.MessageType.Error);
                    return false;
                }

                //Update CRM
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    Entity crmAssembly = new Entity("pluginassembly") { Id = assemblyItem.AssemblyId };
                    crmAssembly["content"] = Convert.ToBase64String(File.ReadAllBytes(path));

                    orgService.Update(crmAssembly);
                }

                //Update assembly name and version numbers
                assemblyItem.Version = assemblyVersion;
                assemblyItem.Name = _selectedProject.Properties.Item("AssemblyName").Value.ToString();
                assemblyItem.DisplayName = assemblyItem.Name + " (" + assemblyVersion + ")";
                assemblyItem.DisplayName += (assemblyItem.IsWorkflowActivity) ? " [Workflow]" : " [Plug-in]";

                return true;
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return false;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Updating Assembly In CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return false;
            }
            finally
            {
                _dte.StatusBar.Clear();
                _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
            }
        }
示例#2
0
 public virtual void Connect()
 {
     string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2};",
                                                Url, Username, Password);
     crmConnection = CrmConnection.Parse(CrmConnectionString);
     service = new OrganizationService(crmConnection);
 }
        public void CreateServiceContext_CrmConnection_ShouldReturnInstanceOfCrmServiceContext()
        {
            // Must have connectionString with the name "Xrm" in the config file.
            var connection = new CrmConnection("Xrm");

            var context = m_factory.CreateServiceContext(connection);

            Assert.That(context, Is.Not.Null);
            Assert.That(context, Is.InstanceOf<ICrmServiceContext>());
        }
示例#4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            var myConnection = new CrmConnection("Xrm");
            using (var myService = new OrganizationService(myConnection))
            using (var myContext = new Xrm.XRMServiceContext(myService))
            {
                var accounts = myContext.bro_managetemplateSet.ToList();
            }
        }
    }
 private void GetConnection(Action<MyDynamicsServiceContext> action)
 {
     _logger.Info("Connecting to CRM...", this);
      var connection = new CrmConnection("CRMServiceConnection");
      using (var org = new OrganizationService(connection))
      {
     try
     {
        var context = new MyDynamicsServiceContext(org);
        action(context);
     }
     catch (Exception ex)
     {
        //Log the exception, then let the business layer handle the error scenario
        _logger.Error("There was a problem connecting to CRM", ex, this);
        throw ex;
     }
      }
 }
示例#6
0
        private void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid reportId)
        {
            try
            {
                _dte.StatusBar.Text = "Deploying report...";
                _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);

                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    Entity report = new Entity("report")
                    {
                        Id = reportId
                    };
                    if (!File.Exists(projectItem.FileNames[1]))
                    {
                        return;
                    }

                    report["bodytext"] = File.ReadAllText(projectItem.FileNames[1]);

                    UpdateRequest request = new UpdateRequest {
                        Target = report
                    };
                    orgService.Execute(request);
                    _logger.WriteToOutputWindow("Deployed Report", Logger.MessageType.Info);
                }
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
            }

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
        }
示例#7
0
 /// <summary>
 /// reads config data from CLI
 /// </summary>
 public static void GetConfig()
 {
     Console.Write("Enter the RabbitMQ endpoint: ");
     _brokerEndpoint = Console.ReadLine();
     Console.Write("Enter the RabbitMQ username: "******"Enter the RabbitMQ password: "******"Enter the RabbitMQ queue name: ");
     _queue = Console.ReadLine();
     Console.Write("Enter the CRM connection string: ");
     _targetOrg = ReadPassword();
     try
     {
         _targetConn = CrmConnection.Parse(_targetOrg);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Could not parse destination connection string: {0}", ex.Message);
         return;
     }
 }
示例#8
0
        public IDeploymentService GetDeploymentService()
        {
            CrmConnection connection = null;

            try
            {
                connection = _CrmConnectionProvider.GetDeploymentServiceConnection();
                connection.UserTokenExpiryWindow = new TimeSpan(0, 3, 0);
                if (connection.Timeout == null)
                {
                    // Set a sensible timeout - 6 minutes.
                    connection.Timeout = new TimeSpan(0, 6, 0);
                }
                // var service = new OrganizationService(connection);
                var service = new DeploymentService(connection);
                return(service);
            }
            catch (Exception ex)
            {
                throw new FailedToConnectToCrmException(connection, ex);
            }
        }
示例#9
0
        private static IClientSideOrganizationService CreateService(CrmServiceInfo info)
        {
            var url = info.CrmServerUrl + "/" + info.CrmOrganization;

            if (info.CrmServerUrl.Contains("crm.dynamics.com"))
            {
                const string onlinePrefix = "https://";
                url = onlinePrefix + info.CrmOrganization + "." + info.CrmServerUrl.Substring(onlinePrefix.Length);
            }

            var client = new CrmConnection
            {
                CallerId           = info.ImpersonationUserId == Guid.Empty ? null : new Guid?(info.ImpersonationUserId),
                ClientCredentials  = GetCredentials(info),
                ProxyTypesAssembly = info.EnableProxyTypes ? GetEarlyBoundProxyAssembly(info) : null,
                ProxyTypesEnabled  = info.EnableProxyTypes,
                ServiceUri         = new Uri(url),
                Timeout            = info.Timeout.Ticks == 0 ? null : new TimeSpan?(info.Timeout),
            };

            return(new ClientSideOrganizationService(new OrganizationService(client)));
        }
示例#10
0
        public void TestApplyAccountAndContact()
        {
            CrmConnection       connectionSource = new CrmConnection("CRM");
            OrganizationService serviceSource    = new OrganizationService(connectionSource);

            CrmConnection       connectionTarget = new CrmConnection("CRM2");
            OrganizationService serviceTarget    = new OrganizationService(connectionTarget);

            CrmChangeTrackingManager mgr = new CrmChangeTrackingManager(serviceSource);

            mgr.ApplyChanges(serviceTarget, new ApplyChangesOptions[]
            {
                new ApplyChangesOptions()
                {
                    EntityName = "account", Columns = new ColumnSet(true)
                },
                new ApplyChangesOptions()
                {
                    EntityName = "contact", Columns = new ColumnSet(true)
                },
            });
        }
示例#11
0
        static void Main(string[] args)
        {
            CrmConnection con = new CrmConnection("CRM");

            IOrganizationService service = new OrganizationService(con);

            //var response = service.Execute(new WhoAmIRequest());

            Entity account = new Entity("account");

            account["name"] = "rishi";

            account["numberofemployees"] = 12345;

            account["accountcategorycode"] = new OptionSetValue(1);

            account["creditlimit"] = new Money((decimal)500000);

            var contact = new Entity("contact")
            {
                Id = Guid.NewGuid()
            };

            account["primarycontactid"] = new EntityReference(contact.LogicalName, contact.Id);

            account["primarycontactid"] = contact.ToEntityReference();

            string name = account["name"].ToString();

            if (account.Contains("name"))
            {
            }
            name = account.GetAttributeValue <string>("name");

            var notfoundstring = account.GetAttributeValue <string>("notfound");

            var notfoundoptionset = account.GetAttributeValue <OptionSetValue>("notfound");
        }
示例#12
0
        public BusinessEntityCollection searchContact(string new_config_allid)
        {
            try
            {
                CrmConnection crmc       = new CrmConnection("Crm");
                CrmService    crmService = crmc.CreateCrmService();

                QueryExpression qe = new QueryExpression("new_config_all")
                {
                    ColumnSet = new ColumnSet(new String[] {
                        "new_config_allid", "new_name", "new_count", "new_current_amount", "new_period", "new_period"
                    }),
                    Criteria = new FilterExpression()
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions     =
                        {
                            new ConditionExpression("new_config_allid", ConditionOperator.Equal, new_config_allid),
                        }
                    }
                };
                RetrieveMultipleResponse retrived = new RetrieveMultipleResponse();

                RetrieveMultipleRequest retrive = new RetrieveMultipleRequest();
                retrive.Query = qe;
                retrive.ReturnDynamicEntities = true;

                BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection;

                return(results);
            }
            catch (SoapException ex)
            {
                logger.Error($"Не удалось осуществить поиск конфига с id {new_config_allid}. Ошибка: {ex.Message}");

                throw new System.ArgumentException($"Не удалось осуществить поиск конфига с id {new_config_allid}. Ошибка: {ex.Message}", "original");
            }
        }
示例#13
0
        private static CrmConnection GetConnection(Uri serviceUri, string domain, string username, string password)
        {
            var credentals = new ClientCredentials();

            if (domain != null)
            {
                credentals.Windows.ClientCredential.Domain   = domain;
                credentals.Windows.ClientCredential.UserName = username;
                credentals.Windows.ClientCredential.Password = password;
            }
            else
            {
                credentals.UserName.UserName = username;
                credentals.UserName.Password = password;
            }

            var connection = new CrmConnection
            {
                ServiceUri        = serviceUri,
                ClientCredentials = credentals,
                ServiceConfigurationInstanceMode = ServiceConfigurationInstanceMode.PerInstance,
                UserTokenExpiryWindow            = TimeSpan.Zero,
            };

            try
            {
                using (var service = new OrganizationService(connection))
                {
                    service.Execute(new WhoAmIRequest());
                }
            }
            catch (Exception e)
            {
                throw new ModelErrorException("Password", "Invalid username or password.", e);
            }

            return(connection);
        }
示例#14
0
        public BusinessEntityCollection searchContact(string contactid)
        {
            try
            {
                CrmConnection crmc       = new CrmConnection("Crm");
                CrmService    crmService = crmc.CreateCrmService();

                QueryExpression qe = new QueryExpression("contact")
                {
                    ColumnSet = new ColumnSet(new String[] {
                        "contactid", "salutation", "lastname", "firstname", "middlename", "mobilephone", "emailaddress1", "address1_name", "address1_line1", "address1_city", "address1_stateorprovince", "address1_country", "new_seria", "new_nomer", "new_giveoutby", "gendercode", "new_nationality", "new_type", "familystatuscode", "birthdate", "new_openles", "new_dategiveout", "ownerid" //" address1_postalcode" //
                    }),
                    Criteria = new FilterExpression()
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions     =
                        {
                            new ConditionExpression("contactid", ConditionOperator.Equal, contactid),
                        }
                    }
                };
                RetrieveMultipleResponse retrived = new RetrieveMultipleResponse();

                RetrieveMultipleRequest retrive = new RetrieveMultipleRequest();
                retrive.Query = qe;
                retrive.ReturnDynamicEntities = true;

                BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection;

                return(results);
            }
            catch (SoapException ex)
            {
                logger.Error($"Не удалось осуществить поиск контакта с id {contactid}. Ошибка: {ex.Message}");

                throw new System.ArgumentException($"Не удалось осуществить поиск контакта с id {contactid}. Ошибка: {ex.Message}", "original");
            }
        }
        /// <summary>
        /// Retrieves the configured <see cref="IOrganizationService"/>.
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="serviceName"></param>
        /// <param name="allowDefaultFallback"></param>
        /// <returns></returns>
        public virtual IOrganizationService CreateService(CrmConnection connection, string serviceName = null, bool allowDefaultFallback = false)
        {
            var section = GetCrmSection();

            var serviceElement = section.Services.GetElementOrDefault(serviceName, allowDefaultFallback);
            var mode           = serviceElement.InstanceMode;
            var name           = serviceElement.Name;

            if (mode == OrganizationServiceInstanceMode.Static)
            {
                // return a single instance

                return(_service ?? (_service = CreateService(serviceElement, connection)));
            }

            if (mode == OrganizationServiceInstanceMode.PerName)
            {
                var key = name ?? GetDefaultContextName();

                if (!_serviceLookup.ContainsKey(key))
                {
                    _serviceLookup[key] = CreateService(serviceElement, connection);
                }

                return(_serviceLookup[key]);
            }

            if (mode == OrganizationServiceInstanceMode.PerRequest && HttpSingleton <IOrganizationService> .Enabled)
            {
                var key = name ?? GetDefaultContextName();

                return(HttpSingleton <IOrganizationService> .GetInstance(key, () => CreateService(serviceElement, connection)));
            }

            var service = CreateService(serviceElement, connection);

            return(service);
        }
示例#16
0
        //public static ListItem GetQuestion(int QuestionID)
        //{

        //    using (ClientContext ctx = new ClientContext(_serverURL))
        //    {
        //        SecureString passWord = new SecureString();
        //        foreach (char c in _userPasswordAdmin) passWord.AppendChar(c);
        //        ctx.Credentials = new SharePointOnlineCredentials(_userNameAdmin, passWord);


        //        List oList = ctx.Web.Lists.GetByTitle("Question Flow");

        //       ListItem collListItem = oList.GetItemById(QuestionID);
        //        ctx.Load(collListItem);

        //        ctx.ExecuteQuery();

        //            return collListItem;
        //    }

        //}

        public static void SaveNewAnswer(string selectedFlowType, string InputTit, string Desc, bool Usertype, string SubmittedBy, string filename)
        {
            try
            {
                var connection = CrmConnection.Parse("Url=https://kbschatbot.crm4.dynamics.com; [email protected]; Password=Demo1234;");// ; DeviceID=xxx-ws00001; DevicePassword=xxxx");
                OrganizationService _Service = new OrganizationService(connection);

                Entity account = new Entity("account");
                account["name"] = "BotName";
                Guid _AccountId = _Service.Create(account);

                //Create new Case  for the above account
                Entity case1 = new Entity("incident");
                case1["title"]           = InputTit;
                case1["description"]     = Desc;
                case1["caseorigincode"]  = new OptionSetValue(100000001); // "Chatbot";
                case1["new_casetype"]    = new OptionSetValue(100000000); //selectedFlowType;
                case1["new_submittedby"] = SubmittedBy;
                case1["new_anonymous"]   = Usertype;
                if (Usertype == true)
                {
                    case1["new_an"] = new OptionSetValue(100000001);
                }
                else
                {
                    case1["new_an"] = new OptionSetValue(100000000);
                }


                EntityReference primaryContactId = new EntityReference("account", _AccountId);
                case1["customerid"] = primaryContactId;
                Guid _CaseId = _Service.Create(case1);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
示例#17
0
        protected IOrganizationService GetOrgService()
        {
            var connection = ConfigurationManager.ConnectionStrings[ConnectionStringName];

            // In case of missing connection string in configuration,
            // use ConnectionStringName as an explicit connection string
            var connectionString = connection == null ? ConnectionStringName : connection.ConnectionString;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new Exception("The ConnectionStringName property must be either a connection string or a connection string name");
            }

#if FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
            // Connect to the CRM web service using a connection string.
            CrmServiceClient client = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
            return(client);
#else
            CrmConnection       crmConnection = CrmConnection.Parse(connectionString);
            OrganizationService service       = new OrganizationService(crmConnection);
            return(service);
#endif
        }
示例#18
0
        private void SaveConnection()
        {
            var crmConnection = new CrmConnection
            {
                Name     = txtName.Text,
                Url      = txtUrl.Text,
                UserName = txtUserName.Text,
                Password = txtPassword.Text,
                Type     = cboType.Text,
            };

            if (crmConnection.Type != "ClientSecret")
            {
                crmConnection.Password = EncryptDecrypt.EncryptString(crmConnection.Password);
            }
            if (Config.CrmConnections == null)
            {
                Config.CrmConnections = new List <CrmConnection>();
            }
            Config.CrmConnections.Add(crmConnection);
            Config.DefaultCrmConnection = txtName.Text;
            DevKitCrmConfigHelper.SetDevKitCrmConfig(DTE, Config);
        }
        public static IOrganizationService ConnectToCrm(Tracer tracer)
        {
            tracer.Trace("Connecting to CRM");
            _lastConnectedOn = DateTime.Now;

            try
            {
                _sdk = CrmConnection.Connect(ConfigurationManager.AppSettings["crm.sdkurl"],
                                             ConfigurationManager.AppSettings["crm.domain"],
                                             ConfigurationManager.AppSettings["crm.username"],
                                             ConfigurationManager.AppSettings["crm.password"],
                                             ConfigurationManager.AppSettings["crm.org"]);

                tracer.Trace("Connected successfully");
            }
            catch (Exception ex)
            {
                tracer.Trace("Unable to connect to CRM");
                tracer.Trace(ex.ToString());
            }

            return(_sdk);
        }
        protected override void Execute(CodeActivityContext context)
        {
            CrmConnection connection = CrmConnection.Parse(CrmConnectionString.Get(context));


            using (OrganizationService service = new OrganizationService(connection))
            {
                using (CIContext ciContext = new CIContext(service))
                {
                    var query = from s in ciContext.SolutionSet
                                where s.UniqueName == UniqueSolutionName.Get(context)
                                select s;
                    Solution solution = query.FirstOrDefault <Solution>();

                    if (solution == null)
                    {
                        throw new Exception(string.Format("Solution {0} could not be found", UniqueSolutionName));
                    }

                    SolutionDetails.Set(context, solution);
                }
            }
        }
示例#21
0
        public BusinessEntityCollection searchnew_reestr(string txn_id)
        {
            CrmConnection crmc       = new CrmConnection("Crm");
            CrmService    crmService = crmc.CreateCrmService();

            QueryExpression qe = new QueryExpression("new_reestr")
            {
                ColumnSet = new ColumnSet(new String[] { "new_txn_id", "new_reestrid", "new_name" }),
                Criteria  = new FilterExpression()
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions     =
                    {
                        new ConditionExpression("new_txn_id", ConditionOperator.Equal, txn_id),
                        new ConditionExpression("statecode",  ConditionOperator.Equal,      0),
                    }
                }
            };

            try
            {
                RetrieveMultipleResponse retrived = new RetrieveMultipleResponse();

                RetrieveMultipleRequest retrive = new RetrieveMultipleRequest();
                retrive.Query = qe;
                retrive.ReturnDynamicEntities = true;

                BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection;

                return(results);
            }
            catch (SoapException ex)
            {
                logger.Error($"Не удалось осуществить поиск Реестра оплат txn_id = {txn_id}. Ошибка: {ex.Message}");
                throw;
            }
        }
示例#22
0
        public void WriteData(IConnection connection, IDatabaseInterface databaseInterface, IDatastore dataObject, ReportProgressMethod reportProgress)
        {
            this.reportProgress = reportProgress;

            reportProgress(new SimpleProgressReport("Connection to crm"));
            CrmConnection crmConnection = (CrmConnection)connection.GetConnection();

            this.service    = new OrganizationService(crmConnection);
            this.dataObject = dataObject;

            reportProgress(new SimpleProgressReport("Load marketinglist metadata"));
            this.listEntityMetaData = Crm2013Wrapper.Crm2013Wrapper.GetEntityMetadata(service, "list");

            reportProgress(new SimpleProgressReport("Resolve existing marketinglists"));
            JoinResolver listResolver = new JoinResolver(this.service, listEntityMetaData, this.Configuration.ListMapping);

            this.existingLists = listResolver.BuildMassResolverIndex();

            reportProgress(new SimpleProgressReport("Load members metadata"));
            EntityMetadata memberEntityMetaData = Crm2013Wrapper.Crm2013Wrapper.GetEntityMetadata(service, this.Configuration.ListMemberType.ToString().ToLower());

            reportProgress(new SimpleProgressReport("Resolve listmembers"));
            JoinResolver memberResolver = new JoinResolver(this.service, memberEntityMetaData, this.Configuration.ListMemberMapping);

            this.existingMembers = memberResolver.BuildMassResolverIndex();

            switch (this.Configuration.JoinList)
            {
            case MarketinglistJoinType.Manual:
                DoManualMarketingList();
                break;

            case MarketinglistJoinType.Join:
                DoJoinMarketingLists();
                break;
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            CrmConnection connection = CrmConnection.Parse(
                ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);

            using (_orgService = new OrganizationService(connection))
            {
                FetchExpression query1 = new FetchExpression(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
				                                                <entity name='account'>
				                                                  <attribute name='name' />
				                                                  <attribute name='primarycontactid' />
				                                                  <attribute name='telephone1' />
				                                                  <attribute name='accountid' />
				                                                  <order attribute='name' descending='false' /></entity></fetch>"                );

                string query2 = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                <entity name='account'>
                                  <attribute name='name' />
                                  <attribute name='primarycontactid' />
                                  <attribute name='telephone1' />
                                  <attribute name='accountid' />
                                  <order attribute='name' descending='false' /></entity></fetch>";
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            Enum.TryParse(Location, out _location);
            var serviceUrl = new Uri(string.Format(UrlFactory.BaseUrl, Organization, _location, UrlFactory.OrgServiceQueryPath));

            // OAuth authentication
            if (ParameterSetName == "oauth")
            {
                var endpoint = UrlFactory.GetDiscoveryUrl(serviceUrl, ApiType.CustomerEngagement);
                var auth     = new OAuthHelper(endpoint, ClientId, RedirectUri);
                _service = CrmConnection.GetConnection(serviceUrl, auth.AuthResult.AccessToken);
            }
            // Cookie authentication
            else if (ParameterSetName == "webauth")
            {
                Enum.TryParse(AuthenticationType, out Models.AuthenticationType authType);
                var webAuthCookies = WebAuthHelper.GetAuthenticatedCookies(serviceUrl.ToString(), authType);
                _service = CrmConnection.GetConnection(new Uri(serviceUrl, UrlFactory.OrgServiceQueryPath), webAuthCookies);
            }

            WriteObject(_service);
        }
示例#25
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Updating Solution {0} Version: {1}", SolutionName, Version));

            CrmConnection connection = CrmConnection.Parse(connectionString);

            Solution solution = null;

            using (OrganizationService orgService = new OrganizationService(connection))
            {
                using (CIContext context = new CIContext(orgService))
                {
                    var query = from s in context.SolutionSet
                                where s.UniqueName == solutionName
                                select s;

                    solution = query.FirstOrDefault <Solution>();
                }

                if (solution == null)
                {
                    throw new Exception(string.Format("Solution {0} could not be found", SolutionName));
                }
                else
                {
                    Solution update = new Solution();
                    update.Id      = solution.Id;
                    update.Version = version;
                    orgService.Update(update);

                    base.WriteVerbose(string.Format("Solution {0} Update to Version: {1}", SolutionName, Version));
                }
            }
        }
示例#26
0
        public CrmObject GetCrmConnection()
        {
            // Get the Url
            Mp.Prompt("Please enter the Url of the organization. E.g. 'http://www.contoso.com:5555/OrganizationName'\n");
            Url = Mp.Read();

            // Get the Domain
            Mp.Prompt("Please enter the Domain of the user.");
            Domain = Mp.Read();

            // Get the Username
            Mp.Prompt("Please enter the Username");
            Username = Mp.Read();

            // Get the Password
            Mp.Prompt("Please enter the Password");
            Password = Mp.ReadPassword();

            Mp.Prompt("\n\nChecking connection details...\n\n");
            // Check the credentials
            try
            {
                CrmConnection connection = CrmConnection.Parse(
                    "Url=" + Url + "; Domain=" + Domain + "; Username="******"; Password="******"The connection details supplied are not valid. Please enter the correct credentials");
                return(GetCrmConnection());
            }
        }
示例#27
0
        public static bool BulkSave(EntityCollection entities, CrmConnection connection = null)
        {
            OrganizationService srv = new OrganizationService(connection ?? XrmConnection.Connection);

            using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv))
            {
                foreach (Entity e in entities.Entities)
                {
                    if (e.Id.Equals(Guid.Empty))
                    {
                        e.Id = Guid.NewGuid();
                        // service.Attach(e);
                        service.AddObject(e);
                    }
                    else
                    {
                        service.Attach(e);
                        service.UpdateObject(e);
                    }
                }
                SaveChangesResultCollection result = service.SaveChanges(Microsoft.Xrm.Sdk.Client.SaveChangesOptions.None);
                return(!result.HasError);
            }
        }
示例#28
0
        static void Main(string[] args)
        {
            var connection = new CrmConnection("Crm");
            var _service   = new OrganizationService(connection);

            var dmsService = new DmsWebService(_service);
            JsonMetadataMapping jsonMapping = null;
            Entity fetchResult = null;

            var document = _service.Retrieve(dot_documents.EntityLogicalName, new Guid("308DF494-0545-E711-80C9-005056B90C62"), new ColumnSet(true));

            if (dmsService.CheckRequiredParametersForIntegration(document, out jsonMapping, out fetchResult))
            {
                dmsService.DmsServiceUploadAnntotations(jsonMapping, fetchResult);
            }


            //3D4E35CA-E692-E711-80CD-005056B90C62
            var anntotation2 = _service.Retrieve(Annotation.EntityLogicalName, new Guid("9577BE91-8F93-E711-80CD-005056B90C62"), new ColumnSet(true));
            var anntotation1 = _service.Retrieve(Annotation.EntityLogicalName, new Guid("A9EBAA09-8E93-E711-80CD-005056B90C62"), new ColumnSet(true));

            //JsonMetadataMapping jsonMapping = new JsonMetadataMapping();
            //Entity fetchResult = null;
            //dmsService.CheckRequiredParametersForRetrieve(anntotation1, out jsonMapping, out fetchResult);

            //var discription = anntotation1.GetAttributeValue<string>("notetext");
            //if (discription != null && discription.Split('^').Length == 2)
            //{
            //    var documentDMSIdBase64EncodedBytes = Convert.FromBase64String(discription.Split('^')[1]);
            //    var documentDMSId = Encoding.UTF8.GetString(documentDMSIdBase64EncodedBytes);
            //    dmsService.DmsServiceUpdateJobe(anntotation2, documentDMSId, jsonMapping, fetchResult);
            //}


            // string documentBody = dmsService.DmsServiceDownloadJobe(anntotation);
        }
        private void UpdateWebResources(string connectionString, List <string> selectedFiles)
        {
            try
            {
                var toBePublishedWebResources = new List <WebResource>();
                OrganizationService orgService;
                var crmConnection = CrmConnection.Parse(connectionString);
                //to escape "another assembly" exception
                crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                using (orgService = new OrganizationService(crmConnection))
                {
                    SetConnectionLabelText(string.Format("Connected to : {0}", crmConnection.ServiceUri), _success);
                    AddLineToOutputWindow(string.Format("Connected to : {0}", crmConnection.ServiceUri));

                    Dictionary <string, WebResource> toBeCreatedList;
                    Dictionary <string, WebResource> toBeUpdatedList;

                    GetWebresources(orgService, selectedFiles, out toBeCreatedList, out toBeUpdatedList);

                    CreateWebresources(toBeCreatedList, orgService, toBePublishedWebResources);

                    UpdateWebresources(toBeUpdatedList, orgService, toBePublishedWebResources);

                    PublishWebResources(orgService, toBePublishedWebResources);
                }
                stopwatch.Stop();
                AddLineToOutputWindow(string.Format("Time : {0}", stopwatch.Elapsed));
            }
            catch (Exception ex)
            {
                AddErrorToOutputWindow(ex.Message);
                AddErrorLineToOutputWindow("Error : " + ex.Message);
            }
        }
示例#30
0
        protected virtual SecurityTokenResponse GetUserTokenResponse(CrmConnection connection, IServiceConfiguration <IDiscoveryService> config)
        {
            var expiryWindow = connection.UserTokenExpiryWindow;

            if (expiryWindow != TimeSpan.Zero)
            {
                var key = connection.GetConnectionId();
                SecurityTokenResponse token;

                // check if the token has expired

                if (!_userTokenLookup.TryGetValue(key, out token) || CheckIfTokenIsExpired(token, expiryWindow))
                {
                    token = CreateUserTokenResponse(connection, config);
                    _userTokenLookup[key] = token;
                }

                return(token);
            }

            var userTokenResponse = CreateUserTokenResponse(connection, config);

            return(userTokenResponse);
        }
示例#31
0
        //public static string ConvertToConnectionString()
        //{

        //}

        public static CrmConnectionAttributes ConvertFromConnectionString(string connectionString)
        {
            CrmConnectionAttributes conAttributes = new CrmConnectionAttributes();

            CrmConnection connection = CrmConnection.Parse(connectionString);
            Uri           serviceUri = connection.ServiceUri;

            conAttributes.Protocol = serviceUri.Scheme;
            conAttributes.Port     = serviceUri.Port.ToString();

            if (connection.ClientCredentials != null && connection.ClientCredentials.Windows != null && connection.ClientCredentials.Windows.ClientCredential != null)
            {
                conAttributes.Domain   = connection.ClientCredentials.Windows.ClientCredential.Domain;
                conAttributes.UserName = connection.ClientCredentials.Windows.ClientCredential.UserName;
                conAttributes.Password = connection.ClientCredentials.Windows.ClientCredential.Password;
            }
            else if (connection.ClientCredentials != null && connection.ClientCredentials.UserName != null)
            {
                conAttributes.UserName = connection.ClientCredentials.UserName.UserName;
                conAttributes.Password = connection.ClientCredentials.UserName.Password;
            }

            return(conAttributes);
        }
示例#32
0
        public void BulkInsertTest2()
        {
            CrmConnection c = new CrmConnection("CRM");
            List <IOrganizationService> services = new List <IOrganizationService>();

            for (int i = 0; i < 4; i++)
            {
                OrganizationService service = new OrganizationService(c);
                services.Add(service);
            }

            CrmBulkServiceManager mgr = new CrmBulkServiceManager(services);

            List <Entity> entityList = new List <Entity>();

            for (int i = 0; i < 480; i++)
            {
                Entity entity = new Entity("account");
                entity["name"] = "account " + DateTime.Now.ToString();
                entityList.Add(entity);
            }

            var results = mgr.BulkInsert(entityList, batchSize: 120);
        }
示例#33
0
        private void DownloadWebResource(Guid webResourceId)
        {
            DisplayStatusMessage("Downloading file");
            string        connString = ((CrmConn)Connections.SelectedItem).ConnectionString;
            CrmConnection connection = CrmConnection.Parse(connString);

            using (OrganizationService orgService = new OrganizationService(connection))
            {
                Entity webResource = orgService.Retrieve("webresource", webResourceId, new ColumnSet("content", "name"));

                var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
                if (dte == null)
                {
                    return;
                }

                string projectName = ((ComboBoxItem)Projects.SelectedItem).Content.ToString();
                foreach (Project project in dte.Solution.Projects)
                {
                    if (project.Name != projectName)
                    {
                        continue;
                    }

                    string[]     name = webResource.GetAttributeValue <string>("name").Split('/');
                    var          path = Path.GetDirectoryName(project.FullName) + "\\" + name[name.Length - 1];
                    FileInfo     file = new FileInfo(path);
                    StreamWriter sw   = file.CreateText();
                    sw.Write(DecodeString(webResource.GetAttributeValue <string>("content")));
                    sw.Close();

                    project.ProjectItems.AddFromFile(path);
                }
            }
            DisplayStatusMessage(String.Empty);
        }
        protected IOrganizationService GetOrgService()
        {
            var connection = ConfigurationManager.ConnectionStrings[ConnectionStringName];

            if (connection == null)
            {
                throw new Exception(string.Format("A connectionstring parameter with name '{0}' must exist", ConnectionStringName));
            }

            if (string.IsNullOrWhiteSpace(connection.ConnectionString))
            {
                throw new Exception("The connectionString property must not be blank");
            }

#if FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365
            // Connect to the CRM web service using a connection string.
            CrmServiceClient client = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connection.ConnectionString);
            return(client);
#else
            CrmConnection       crmConnection = CrmConnection.Parse(connection.ConnectionString);
            OrganizationService service       = new OrganizationService(crmConnection);
            return(service);
#endif
        }
        private void ExportSolution(CrmConnection connection)
        {
            if (string.IsNullOrWhiteSpace(this.Extension))
            {
                Log.LogError("Required parameter missing: Extension");
                return;
            }

            string directoryPath = string.IsNullOrEmpty(this.Path)
                ? System.IO.Path.GetDirectoryName(this.BuildEngine.ProjectFileOfTaskNode)
                : this.Path;

            // ReSharper disable once AssignNullToNotNullAttribute
            string solutioneFile = string.Format(CultureInfo.CurrentCulture, "{0}.{1}", System.IO.Path.Combine(directoryPath, this.Name), this.Extension);
            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var exportSolutionRequest = new ExportSolutionRequest
                                                {
                                                    SolutionName = this.Name,
                                                    Managed = this.ExportAsManagedSolution
                                                };

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Exporting Solution {0}. Please wait...", this.Name));
                    var response = serviceContext.Execute(exportSolutionRequest) as ExportSolutionResponse;
                    if (response == null)
                    {
                        Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred in in exporting Solution {0} from organization with Url {1}.", this.Name, this.OrganizationUrl));    
                    }
                    else
                    {
                        byte[] exportSolutionFileContentsBytes = response.ExportSolutionFile;
                        File.WriteAllBytes(solutioneFile, exportSolutionFileContentsBytes);
                        Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully exported Solution {0} from organization with Url {1}.", this.Name, this.OrganizationUrl));    
                    }
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "An error occurred while exporting Solution {0} from Organization with Url {1}. [{2}]",
                                    this.Name,
                                    this.OrganizationUrl,
                                    exception.Message));
                }
            }
        }
        private void ImportSolution(CrmConnection connection)
        {
            if (string.IsNullOrWhiteSpace(this.Extension))
            {
                Log.LogError("Required parameter missing: Extension");
                return;
            }

            string directoryPath = string.IsNullOrEmpty(this.Path)
                ? System.IO.Path.GetDirectoryName(this.BuildEngine.ProjectFileOfTaskNode)
                : this.Path;

            // ReSharper disable once AssignNullToNotNullAttribute
            string solutioneFile = string.Format(CultureInfo.CurrentCulture, "{0}.{1}", System.IO.Path.Combine(directoryPath, this.Name), this.Extension);
            if (!File.Exists(solutioneFile))
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The given Solution file for import does not exist. {0}", solutioneFile));
                return;
            }

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache)
                    {
                        cache.Mode = OrganizationServiceCacheMode.Disabled;
                    });

                    byte[] customizationFile = File.ReadAllBytes(solutioneFile);
                    var request = new ImportSolutionRequest
                    {
                        CustomizationFile = customizationFile,
                        OverwriteUnmanagedCustomizations = this.overwriteCustomizations,
                        PublishWorkflows = this.EnableSdkProcessingSteps
                    };

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing Solution {0}. Please wait...", this.Name));
                    serviceContext.Execute(request);
                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported Solution {0} to organization with Url {1}.", this.Name, this.OrganizationUrl));
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "An error occurred while importing Solution {0} to Organization with Url {1}. [{2}]",
                                    this.Name, 
                                    this.OrganizationUrl,
                                    exception.Message));
                }
            }
        }
 private void SetVersion(CrmConnection connection)
 {
     using (var serviceContext = new CrmOrganizationServiceContext(connection))
     {
         try
         {
             var entity = this.GetVersionEntity(serviceContext);
             if (entity != null)
             {
                 entity["version"] = this.Version;
                 serviceContext.Update(entity);
                 Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully set version of Solution {0} in Organization with Url {1}.", this.Name, this.OrganizationUrl));
             }
         }
         catch (Exception exception)
         {
             Log.LogError(string.Format(
                             CultureInfo.CurrentCulture,
                             "An error occurred while setting version of Solution {0} in Organization with Url {1}. [{2}]",
                             this.Name,
                             this.OrganizationUrl,
                             exception.Message));
         }
     }
 }
 private void GetVersion(CrmConnection connection)
 {
     using (var serviceContext = new CrmOrganizationServiceContext(connection))
     {
         var entity = this.GetVersionEntity(serviceContext);
         if (entity != null)
         {
             this.Version = entity.GetAttributeValue<string>("version");
             entity["version"] = this.Version;
             Log.LogMessage(
                 MessageImportance.Low, 
                 string.Format(CultureInfo.CurrentCulture, "Successfully read version of Solution {0} in Organization with Url {1}.", this.Name, this.OrganizationUrl));
         }
     }
 }
 public OrganizationServiceAdapter(CrmConnection connection)
     : base(connection)
 {
 }
示例#40
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the source connection string: ");
            sourceOrg = Console.ReadLine();
            try
            {
                sourceConn = CrmConnection.Parse(sourceOrg);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Could not parse source connection string: {0}", ex.Message);
                return;
            }

            Console.WriteLine("Enter the destination connection string: ");
            targetOrg = Console.ReadLine();
            try
            {
                targetConn = CrmConnection.Parse(targetOrg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not parse destination connection string: {0}", ex.Message);
                return;
            }

            //export teamtemplates
            using (OrganizationService service = new OrganizationService(sourceConn))
            {
                try
                {
                    //attributes to exclude from the query
                    List<string> IgnoredAttributes = new List<string> { "issystem" };

                    Console.WriteLine("Retrieving entity metadata . . .");
                    RetrieveEntityRequest entityreq = new RetrieveEntityRequest
                    {
                        LogicalName = "teamtemplate",
                        EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
                    };
                    RetrieveEntityResponse entityres = (RetrieveEntityResponse)service.Execute(entityreq);
                    string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                    fetchXml += "<entity name='teamtemplate'>";

                    foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
                    {
                        if (!IgnoredAttributes.Contains(amd.LogicalName))
                        {
                            fetchXml += "<attribute name='" + amd.LogicalName + "' />";
                            //Console.WriteLine(amd.LogicalName);
                        }
                    }
                    fetchXml += "</entity></fetch>";

                    Console.WriteLine("");
                    Console.WriteLine("Exporting data . . .");
                    exported = service.RetrieveMultiple(new FetchExpression(fetchXml));
                }
                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    Console.WriteLine("Could not export data: {0}", ex.Message);
                    return;
                }
            }

            //import teamtemplates
            Console.WriteLine("Importing data . . .");
            using (OrganizationService service = new OrganizationService(targetConn))
            {
                if (exported.Entities.Count > 0)
                {
                    foreach (Entity entity in exported.Entities)
                    {
                        try
                        {
                            //Console.WriteLine("Id - {0}", entity.Id.ToString());

                            //try to update first
                            try
                            {
                                service.Update(entity);
                            }
                            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
                            {
                                //if update fails, then create
                                service.Create(entity);
                            }
                        }
                        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //if everything fails, return error
                            Console.WriteLine("Error: {0} - {1}", entity.Id, entity["teamtemplatename"]);
                        }
                    }
                }
            }
            Console.WriteLine("Import complete");
            Console.WriteLine("");
            Console.WriteLine("Press the enter key to exit");
            Console.ReadLine();
        }
        private void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid webResourceId)
        {
            try
            {
                _dte.StatusBar.Text = "Updating & publishing web resource...";
                _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);

                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    string publishXml = "<importexportxml><webresources>";
                    Entity webResource = new Entity("webresource") { Id = webResourceId };

                    string extension = Path.GetExtension(projectItem.FileNames[1]);
                    string content = extension != null && (extension.ToUpper() != ".TS")
                        ? File.ReadAllText(projectItem.FileNames[1])
                        : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js"));
                    webResource["content"] = EncodeString(content);

                    UpdateRequest request = new UpdateRequest { Target = webResource };
                    orgService.Execute(request);
                    _logger.WriteToOutputWindow("Uploaded Web Resource", Logger.MessageType.Info);

                    publishXml += "<webresource>{" + webResource.Id + "}</webresource>";
                    publishXml += "</webresources></importexportxml>";

                    PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml };

                    orgService.Execute(pubRequest);
                    _logger.WriteToOutputWindow("Published Web Resource", Logger.MessageType.Info);
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
            }

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
        }
 /*CONNECTION AND QUERY*/
 public OrganizationService OurConnect()
 {
     var connection = new CrmConnection(_ConnectionStringName);
     var service = new OrganizationService(connection);
     return service;
 }
 public IOrganizationService GetOrganizationService(string discoveryService, string organization, string username = null, string password = null, string domain = null)
 {
     var app = new CrmConnection(discoveryService, organization, username, password, domain);
     return app.GetOrganizationService();
 }
示例#44
0
        /// <summary>
        /// parse supplied crm connection strings to get crmconnection objects
        /// </summary>
        private void ParseConnections()
        {
            LogMessage("INFO","parsing source connection");
            _sourceConn = CrmConnection.Parse(SourceString);

            LogMessage("INFO","parsing target connection");
            _targetConn = CrmConnection.Parse(TargetString);

        }
示例#45
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public XrmServiceContext(CrmConnection connection)
     : base(connection)
 {
 }
        private void UpdateAndPublishMultiple(CrmConnection connection, ProjectItem projectItem, Guid webResourceId)
        {
            try
            {
                ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest
                {
                    Requests = new OrganizationRequestCollection(),
                    Settings = new ExecuteMultipleSettings
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    }
                };

                OrganizationRequestCollection requests = new OrganizationRequestCollection();

                string publishXml = "<importexportxml><webresources>";
                Entity webResource = new Entity("webresource") { Id = webResourceId };

                string extension = Path.GetExtension(projectItem.FileNames[1]);
                string content = extension != null && (extension.ToUpper() != ".TS")
                    ? File.ReadAllText(projectItem.FileNames[1])
                    : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js"));
                webResource["content"] = EncodeString(content);

                UpdateRequest request = new UpdateRequest { Target = webResource };
                requests.Add(request);

                publishXml += "<webresource>{" + webResource.Id + "}</webresource>";
                publishXml += "</webresources></importexportxml>";

                PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml };
                requests.Add(pubRequest);
                emRequest.Requests = requests;

                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    _dte.StatusBar.Text = "Updating & publishing web resource...";
                    _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);

                    ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest);

                    bool wasError = false;
                    foreach (var responseItem in emResponse.Responses)
                    {
                        if (responseItem.Fault == null) continue;

                        _logger.WriteToOutputWindow(
                            "Error Updating And Publishing Web Resources To CRM: " + responseItem.Fault.Message + Environment.NewLine + responseItem.Fault.TraceText,
                            Logger.MessageType.Error);
                        wasError = true;
                    }

                    if (wasError)
                        MessageBox.Show("Error Updating And Publishing Web Resources To CRM. See the Output Window for additional details.");
                    else
                        _logger.WriteToOutputWindow("Updated And Published Web Resource", Logger.MessageType.Info);
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
            }

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
        }
        private static IClientSideOrganizationService CreateService(CrmServiceInfo info)
        {
            var url = info.CrmServerUrl + "/" + info.CrmOrganization;
            if(info.CrmServerUrl.Contains("crm.dynamics.com"))
            {
                const string onlinePrefix = "https://";
                url = onlinePrefix + info.CrmOrganization + "." + info.CrmServerUrl.Substring(onlinePrefix.Length);
            }

            var client = new CrmConnection
            {
                CallerId = info.ImpersonationUserId == Guid.Empty ? null : new Guid?(info.ImpersonationUserId),
                ClientCredentials = GetCredentials(info),
                ProxyTypesAssembly = info.EnableProxyTypes ? GetEarlyBoundProxyAssembly(info) : null,
                ProxyTypesEnabled = info.EnableProxyTypes,
                ServiceUri = new Uri(url),
                Timeout =  info.Timeout.Ticks == 0 ? null : new TimeSpan?(info.Timeout),
            };

            return new ClientSideOrganizationService(new OrganizationService(client));
        }
 public FailedToConnectToCrmException(CrmConnection connection, Exception innerException)
     : base(FailedToConnectErrorMessage, innerException)
 {
 }
示例#49
0
        private void DisplayPluginControl(UserControl plugin)
        {
            try
            {
                var controlType   = (Type)plugin.Tag;
                var pluginControl =
                    (UserControl)PluginManager.CreateInstance(controlType.Assembly.Location, controlType.FullName);

                if (service != null)
                {
                    var clonedService = new OrganizationService(CrmConnection.Parse(currentConnectionDetail.GetOrganizationCrmConnectionString()));
                    ((OrganizationServiceProxy)clonedService.InnerService).SdkClientVersion = currentConnectionDetail.OrganizationVersion;

                    ((IMsCrmToolsPluginUserControl)pluginControl).UpdateConnection(clonedService,
                                                                                   currentConnectionDetail);
                }

                ((IMsCrmToolsPluginUserControl)pluginControl).OnRequestConnection += MainForm_OnRequestConnection;
                ((IMsCrmToolsPluginUserControl)pluginControl).OnCloseTool         += MainForm_OnCloseTool;

                string name = string.Format("{0} ({1})", pluginControl.GetType().GetTitle(),
                                            currentConnectionDetail != null
                        ? currentConnectionDetail.ConnectionName
                        : "Not connected");

                var newTab = new TabPage(name);
                tabControl1.TabPages.Add(newTab);

                pluginControl.Dock   = DockStyle.Fill;
                pluginControl.Width  = newTab.Width;
                pluginControl.Height = newTab.Height;

                newTab.Controls.Add(pluginControl);

                tabControl1.SelectTab(tabControl1.TabPages.Count - 1);

                var pluginInOption =
                    currentOptions.MostUsedList.FirstOrDefault(i => i.Name == pluginControl.GetType().FullName);
                if (pluginInOption == null)
                {
                    pluginInOption = new PluginUseCount {
                        Name = pluginControl.GetType().FullName, Count = 0
                    };
                    currentOptions.MostUsedList.Add(pluginInOption);
                }

                pluginInOption.Count++;

                var p1 = plugin as SmallPluginModel;
                if (p1 != null)
                {
                    p1.UpdateCount(pluginInOption.Count);
                }
                else
                {
                    var p2 = plugin as PluginModel;
                    if (p2 != null)
                    {
                        p2.UpdateCount(pluginInOption.Count);
                    }
                }

                if (currentOptions.LastAdvertisementDisplay == new DateTime() ||
                    currentOptions.LastAdvertisementDisplay > DateTime.Now ||
                    currentOptions.LastAdvertisementDisplay.AddDays(7) < DateTime.Now)
                {
                    bool displayAdvertisement = true;
                    try
                    {
                        var assembly =
                            Assembly.LoadFile(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory +
                                              "\\McTools.StopAdvertisement.dll");
                        if (assembly != null)
                        {
                            Type type = assembly.GetType("McTools.StopAdvertisement.LicenseManager");
                            if (type != null)
                            {
                                MethodInfo methodInfo = type.GetMethod("IsValid");
                                if (methodInfo != null)
                                {
                                    object classInstance = Activator.CreateInstance(type, null);

                                    if ((bool)methodInfo.Invoke(classInstance, null))
                                    {
                                        displayAdvertisement = false;
                                    }
                                }
                            }
                        }
                    }
                    catch (FileNotFoundException)
                    {
                    }

                    if (displayAdvertisement)
                    {
                        var sc = new SupportScreen(currentReleaseNote);
                        sc.ShowDialog(this);
                        currentOptions.LastAdvertisementDisplay = DateTime.Now;
                    }
                }

                currentOptions.Save();
            }
            catch (Exception error)
            {
                MessageBox.Show(this, "An error occured when trying to display this plugin: " + error.Message, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UpdateAndPublishSingle(CrmConnection connection, ProjectItem projectItem, Guid reportId)
        {
            try
            {
                _dte.StatusBar.Text = "Deploying report...";
                _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);

                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    Entity report = new Entity("report") { Id = reportId };
                    if (!File.Exists(projectItem.FileNames[1])) return;

                    report["bodytext"] = File.ReadAllText(projectItem.FileNames[1]);

                    UpdateRequest request = new UpdateRequest { Target = report };
                    orgService.Execute(request);
                    _logger.WriteToOutputWindow("Deployed Report", Logger.MessageType.Info);
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Deploying Report To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
            }

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
        }
 public CrmHelper(string url, string domain, string username, string password)
 {
     crmConnection =
         CrmConnection.Parse(string.Format(DefaultConfiguration.ConnectionFormat, url, domain, username, password));
     crmConnection.Timeout = new TimeSpan(0, 0, DefaultConfiguration.TimeoutExceptionInMinutes, 0);
 }
示例#52
0
        private void ImportData()
        {
            if (!File.Exists(this.FilePath))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find import data file {0}", this.FilePath));
                return;
            }

            Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to Organization {0}.", this.OrganizationUrl));
            string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout);
            var    connection       = CrmConnection.Parse(connectionString);

            string content = File.ReadAllText(this.FilePath);

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var dataMap = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue <string>("name") == this.DataMapName);
                    if (dataMap == null)
                    {
                        Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find data map {0} in the organization with Url {1}", this.DataMapName, this.OrganizationUrl));
                        return;
                    }

                    var importId = CreateImportEntity(serviceContext, this.SourceEntityName);
                    this.CreateImportFileEntity(serviceContext, content, importId, dataMap.Id);

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing data from File {0} to entity {1}", this.FilePath, this.TargetEntityName));
                    serviceContext.Execute(new ParseImportRequest {
                        ImportId = importId
                    });
                    serviceContext.Execute(new TransformImportRequest {
                        ImportId = importId
                    });
                    serviceContext.Execute(new ImportRecordsImportRequest {
                        ImportId = importId
                    });
                    serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache)
                    {
                        cache.Mode = OrganizationServiceCacheMode.Disabled;
                    });

                    int  waitCount       = 0;
                    bool importCompleted = false;
                    do
                    {
                        int statusCode = GetImportStatus(serviceContext, importId);
                        switch (statusCode)
                        {
                        case DataImportStatusSuccess:
                            Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported data file {0} to entity {1}.", this.FilePath, this.TargetEntityName));
                            importCompleted = true;
                            break;

                        case DataImportStatusFailed:
                            Log.LogError(string.Format(CultureInfo.CurrentCulture, "Import of data file {0} to entity {1} failed.", this.FilePath, this.TargetEntityName));
                            importCompleted = true;
                            break;
                        }

                        if (!importCompleted)
                        {
                            Log.LogMessage("Importing...");

                            Thread.Sleep(WaitIntervalInMilliseconds);
                            if (++waitCount > this.timeoutInMinutes)
                            {
                                Log.LogError("Import failed to complete during the maximum allocated time");
                                break;
                            }
                        }
                    }while (!importCompleted);
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                     CultureInfo.CurrentCulture,
                                     "An error occurred while importing Data file {0} to Entity {1} for Organization with Url {2}. [{3}]",
                                     this.FilePath,
                                     this.TargetEntityName,
                                     this.OrganizationUrl,
                                     exception.Message));
                }
            }
        }
示例#53
0
 public ConnectionOsFactory(CrmConnection connection)
 {
     _connection = connection;
 }
        private EntityCollection RetrieveAssembliesFromCrm(CrmConnection connection)
        {
            try
            {
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = "pluginassembly",
                        ColumnSet = new ColumnSet("name", "version"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
						{
							new ConditionExpression
							{
								AttributeName = "ismanaged",
								Operator = ConditionOperator.Equal,
								Values = { false }
							}
						}
                        },
                        LinkEntities =
					{
						new LinkEntity
						{
							Columns = new ColumnSet("isworkflowactivity"),
							LinkFromEntityName = "pluginassembly",
							LinkFromAttributeName = "pluginassemblyid",
							LinkToEntityName = "plugintype",
							LinkToAttributeName = "pluginassemblyid",
							EntityAlias = "plugintype",
							JoinOperator = JoinOperator.LeftOuter
						}
					},
                        Orders =
					    {
						    new OrderExpression
						    {
							    AttributeName = "name",
							    OrderType = OrderType.Ascending
						    }
					    }
                    };

                    return orgService.RetrieveMultiple(query);
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Retrieving Assemblies From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return null;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Retrieving Assemblies From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return null;
            }
        }
 /// <summary>
 /// Constructor. Pass CrmConnection to base.
 /// </summary>
 /// <param name="cnn">CrmConnection</param>
 public OrganizationServiceEx(CrmConnection cnn)
     : base(cnn)
 {
 }