Example #1
0
        //private void BwGetSolutionRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    if (e.Error != null)
        //    {
        //        string errorMessage = e.Error.Message;
        //        var ex = e.Error.InnerException;
        //        while (ex != null)
        //        {
        //            errorMessage += "\r\nInner Exception: " + ex.Message;
        //            ex = ex.InnerException;
        //        }
        //        MessageBox.Show("An error occured while retrieving publisher prefix: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //    else
        //    {
        //        if (e.Result != null)
        //        {
        //            var entity = e.Result as Entity;
        //            string prefix = entity.GetAttributeValue<AliasedValue>("publisher.customizationprefix") == null ? null : entity.GetAttributeValue<AliasedValue>("publisher.customizationprefix").Value.ToString();
        //            await Logger.WriteLineAsync("Publisher prefix successfully retrieved");
        //            _connectionDetail.PublisherPrefix = prefix;
        //            var settings = projectHelper.GetSettingsAsync().Result;
        //            settings.SelectedConnection.PublisherPrefix = prefix;
        //            settings.Save();
        //            OpenCreateWebResourceFormAsync();
        //        }
        //    }
        //}

        //private void BwGetSolutionDoWork(object sender, DoWorkEventArgs e)
        //{
        //    e.Result = RetrieveSolution();
        //}

        private async Task <Entity> RetrieveSolutionAsync()
        {
            var settings = await SettingsService.Instance.GetSettingsAsync();

            var selectedConnection = settings.SelectedConnection;
            var orgService         = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(selectedConnection);

            QueryExpression query = new QueryExpression
            {
                EntityName = "solution",
                ColumnSet  = new ColumnSet(new string[] { "friendlyname", "uniquename", "publisherid" }),
                Criteria   = new FilterExpression()
            };

            query.Criteria.AddCondition("isvisible", ConditionOperator.Equal, true);
            query.Criteria.AddCondition("solutionid", ConditionOperator.Equal, selectedConnection.SolutionId);

            query.LinkEntities.Add(new LinkEntity("solution", "publisher", "publisherid", "publisherid", JoinOperator.Inner));
            query.LinkEntities[0].Columns.AddColumns("customizationprefix");
            query.LinkEntities[0].EntityAlias = "publisher";

            var response = await orgService.RetrieveMultipleAsync(query);

            return(response.Entities.FirstOrDefault());
        }
        private async Task <Entity> RetrieveSolutionAsync(ConnectionDetail currentDetail)
        {
            if (currentDetail.SolutionId == null)
            {
                return(null);
            }
            WebRequest.GetSystemWebProxy();

            var service = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(currentDetail);

            QueryExpression query = new QueryExpression
            {
                EntityName = "solution",
                ColumnSet  = new ColumnSet(new string[] { "friendlyname", "uniquename", "publisherid" }),
                Criteria   = new FilterExpression()
            };

            query.Criteria.AddCondition("isvisible", ConditionOperator.Equal, true);
            query.Criteria.AddCondition("solutionid", ConditionOperator.Equal, currentDetail.SolutionId);

            query.LinkEntities.Add(new LinkEntity("solution", "publisher", "publisherid", "publisherid", JoinOperator.Inner));
            query.LinkEntities[0].Columns.AddColumns("customizationprefix");
            query.LinkEntities[0].EntityAlias = "publisher";

            var response = service.RetrieveMultiple(query);

            return(response.Entities.FirstOrDefault());
        }
Example #3
0
        /// <summary>
        /// Publishes webresources changes
        /// </summary>
        /// <param name="webresourcesIds">List of webresource IDs to publish</param>
        private async System.Threading.Tasks.Task PublishWebResourcesAsync(IEnumerable <Guid> webresourcesIds)
        {
            var settings = await SettingsService.Instance.GetSettingsAsync();

            var selectedConnection = settings.SelectedConnection;
            var orgService         = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(selectedConnection);

            await Logger.WriteLineWithTimeAsync("Publishing...");

            //await Logger.WriteLineAsync("Publishing...");
            var orgContext = new OrganizationServiceContext(orgService);

            if (webresourcesIds == null)
            {
                throw new ArgumentNullException("webresourcesId");
            }
            if (webresourcesIds.Any())
            {
                var request = GetPublishRequest(webresourcesIds);
                await orgContext.ExecuteAsync(request);
            }
            var count = webresourcesIds.Count();
            await Logger.WriteLineWithTimeAsync(count + " file" + (count == 1 ? " was" : "s were") + " published");

            //await Logger.WriteLineAsync(count + " file" + (count == 1 ? " was" : "s were") + " published");
        }
Example #4
0
        /// <summary>
        /// Retrieves web resources for selected items
        /// </summary>
        /// <returns>List of web resources</returns>
        private async System.Threading.Tasks.Task <List <Entity> > RetrieveWebResourcesAsync(List <string> webResourceNames = null)
        {
            var settings = await SettingsService.Instance.GetSettingsAsync();

            var connections        = settings.CrmConnections;
            var selectedConnection = settings.SelectedConnection;
            var orgService         = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(selectedConnection);

            await Logger.WriteLineAsync("Retrieving existing web resources", connections.ExtendedLog);

            var filter = "";

            if (webResourceNames != null && webResourceNames.Count > 0)
            {
                filter = "<filter type='or'>";
                foreach (var name in webResourceNames)
                {
                    filter += $"<condition attribute='name' operator='like' value='{name}%' />";
                }
                filter += "</filter>";
            }
            var fetchQuery = String.Format(FetchWebResourcesQueryTemplate, selectedConnection.SolutionId, filter);
            var response   = await orgService.RetrieveMultipleAsync(new FetchExpression(fetchQuery));

            var webResources = response.Entities.ToList();

            return(webResources);
        }
Example #5
0
        static void Main(string[] args)
        {
            var serviceClient = CrmConnectionHelper.GetCrmServiceClient();
            var entity        = serviceClient.Retrieve("opportunity", new Guid("be0d0283-5bf2-e311-945f-6c3be5a8dd64"), new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
            var entity1       = new Entity("opportunity");

            entity1.Attributes["parentaccountid"]    = entity.Attributes["parentaccountid"];
            entity1.Attributes["parentcontactid"]    = entity.Attributes["parentcontactid"];
            entity1.Attributes["name"]               = (string)entity.Attributes["name"] + " - API " + DateTime.Now.ToLongDateString();
            entity1.Attributes["purchasetimeframe"]  = entity.Attributes["purchasetimeframe"];
            entity1.Attributes["budgetamount"]       = entity.Attributes["budgetamount"];
            entity1.Attributes["purchaseprocess"]    = entity.Attributes["purchaseprocess"];
            entity1.Attributes["estimatedclosedate"] = entity.Attributes["estimatedclosedate"];
            entity1.Attributes["confirminterest"]    = entity.Attributes["confirminterest"];

            var config = new WebApiConfiguration()
            {
                ClientId          = " ",
                ClientSecret      = " ",
                CRMApiEndpointUri = "https://orgname.api.crm8.dynamics.com/api/data/v9.1/",
                RedirectUrl       = "https://orgname.crm8.dynamics.com/",
                TenantId          = ""
            };

            CrmApiService.CreateCrmApiServiceInstance(config);

            var id = CrmApiService.Instance.CreateRecord("opportunities", entity1).GetAwaiter().GetResult();
        }
Example #6
0
 /*
  * /// <summary>
  * /// Publisher constructor
  * /// </summary>
  * /// <param name="connection">Connection to CRM that will be used to upload webresources</param>
  * /// <param name="project">Project to upload files from</param>
  * /// <param name="autoPublish">Perform publishing or not</param>
  * /// <param name="ignoreExtensions">Try to upload without extension if item not found with it</param>
  * /// <param name="extendedLog">Print extended uploading process information</param>
  * public Publisher(ConnectionDetail connection, Project project, bool autoPublish, bool ignoreExtensions, bool extendedLog = false): this(connection, autoPublish, ignoreExtensions, extendedLog)
  * {
  *  if(project == null)
  *  {
  *      throw new ArgumentNullException("project");
  *  }
  *  _project = project;
  *  _projectRootPath = Path.GetDirectoryName(_project.FullName);
  * }
  */
 /// <summary>
 /// Publisher constructor
 /// </summary>
 /// <param name="connection">Connection to CRM that will be used to upload webresources</param>
 /// <param name="autoPublish">Perform publishing or not</param>
 /// <param name="ignoreExtensions">Try to upload without extension if item not found with it</param>
 /// <param name="extendedLog">Print extended uploading process information</param>
 private Publisher(ConnectionDetail connection, bool autoPublish, bool ignoreExtensions, bool extendedLog)
 {
     _connectionDetail = connection ?? throw new ArgumentNullException(nameof(connection));
     _autoPublish      = autoPublish;
     _ignoreExtensions = ignoreExtensions;
     _extendedLog      = extendedLog;
     _orgService       = CrmConnectionHelper.GetOrganizationServiceProxy(_connectionDetail);
 }
        private OrganizationDetailCollection RetrieveOrganizations(ConnectionDetail currentDetail)
        {
            WebRequest.GetSystemWebProxy();
            var service = CrmConnectionHelper.GetDiscoveryService(currentDetail);

            var request  = new RetrieveOrganizationsRequest();
            var response = (RetrieveOrganizationsResponse)service.Execute(request);

            return(response.Details);
        }
Example #8
0
        public CreateWebResourceForm(string filePath)
        {
            var settings = ProjectHelper.GetSettings();

            _connectionDetail = settings.SelectedConnection;
            if (_connectionDetail.SolutionId == null)
            {
                throw new ArgumentNullException("SolutionId");
            }
            WebRequest.GetSystemWebProxy();
            _service = CrmConnectionHelper.GetOrganizationServiceProxy(_connectionDetail);

            ProjectItemPath = filePath;
            InitializeComponent();
        }
        private async Task <OrganizationDetail> RetrieveOrganizationAsync(ConnectionDetail currentDetail)
        {
            if (currentDetail.OrganizationId == null)
            {
                return(null);
            }
            WebRequest.GetSystemWebProxy();

            var service = await CrmConnectionHelper.GetDiscoveryServiceAsync(currentDetail);

            var request  = new RetrieveOrganizationsRequest();
            var response = (RetrieveOrganizationsResponse)service.Execute(request);


            return(response.Details.Where(d => d.OrganizationId == new Guid(currentDetail.OrganizationId)).FirstOrDefault());
        }
Example #10
0
        /// <summary>
        /// Uploads web resource
        /// </summary>
        /// <param name="webResource">Web resource to be updated</param>
        /// <param name="content">Content to be set for web resource</param>
        private async System.Threading.Tasks.Task UpdateWebResourceByContentAsync(Entity webResource, string content)
        {
            var settings = await SettingsService.Instance.GetSettingsAsync();

            var connections        = settings.CrmConnections;
            var selectedConnection = settings.SelectedConnection;
            var orgService         = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(selectedConnection);


            var name = webResource.GetAttributeValue <string>("name");

            webResource["content"] = content;
            await orgService.UpdateAsync(webResource);

            await Logger.WriteLineAsync(name + " was successfully uploaded", connections.ExtendedLog);
        }
Example #11
0
        private async void OpenCreateWebResourceFormAsync()
        {
            var settings = await SettingsService.Instance.GetSettingsAsync();

            var project = await projectHelper.GetSelectedProjectAsync();

            var path = await projectHelper.GetSelectedFilePathAsync();

            var dialog = new CreateWebResourceForm(path, settings.SelectedConnection.PublisherPrefix);

            dialog.OnCreate = async(Entity webResource) =>
            {
                var connectionDetail = settings.SelectedConnection;
                if (connectionDetail.SolutionId == null)
                {
                    throw new ArgumentNullException("SolutionId");
                }
                WebRequest.GetSystemWebProxy();
                var service = await CrmConnectionHelper.GetOrganizationServiceProxyAsync(connectionDetail);

                var webresourceName = webResource["name"] as String;
                if (await this.IsResourceExistsAsync(service, webresourceName))
                {
                    MessageBox.Show("Webresource with name '" + webresourceName + "' already exist in CRM.", "Webresource already exists.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    Cursor.Current = Cursors.Arrow;
                    var isMappingRequired = await mappingHelper.IsMappingRequired(project, path, webresourceName);

                    var isMappingFileReadOnly = mappingHelper.IsMappingFileReadOnly(project);
                    if (isMappingRequired && isMappingFileReadOnly)
                    {
                        var message = "Mapping record can't be created. File \"UploaderMapping.config\" is read-only. Do you want to proceed? \r\n\r\n" +
                                      "Schema name of the web resource you are creating is differ from the file name. " +
                                      "Because of that new mapping record has to be created in the file \"UploaderMapping.config\". " +
                                      "Unfortunately the file \"UploaderMapping.config\" is read-only (file might be under a source control), so mapping record cant be created. \r\n\r\n" +
                                      "Press OK to proceed without mapping record creation (You have to do that manually later). Press Cancel to fix problem and try later.";
                        var result = MessageBox.Show(message, "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        if (result == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    if (isMappingRequired && !isMappingFileReadOnly)
                    {
                        mappingHelper.CreateMapping(project, path, webresourceName);
                    }
                    this.CreateWebResource(service, webResource, settings.SelectedConnection.Solution);
                    await Logger.WriteLineAsync("Webresource '" + webresourceName + "' was successfully created");

                    dialog.Close();
                }
                catch (Exception ex)
                {
                    Cursor.Current = Cursors.Arrow;
                    MessageBox.Show("An error occured during web resource creation: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };
            dialog.ShowDialog();
        }