Exemplo n.º 1
0
        public static EntityCollection GetRelated(Entity PrimaryEntity, string RelatedEntityName, string ForeignKeyField, CrmConnection connection = null, bool CacheResults = true)
        {
            if (CacheResults)
            {
                using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
                {
                    IQueryable <Entity> query = from entity in service.CreateQuery(RelatedEntityName)
                                                where (Guid)entity[ForeignKeyField] == PrimaryEntity.Id
                                                select entity;

                    EntityCollection col = new EntityCollection(query.ToList());
                    col.EntityName = RelatedEntityName;
                    return(col);
                }
            }
            else
            {
                OrganizationService srv = new OrganizationService(connection ?? XrmConnection.Connection);
                using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv))
                {
                    IQueryable <Entity> query = from entity in service.CreateQuery(RelatedEntityName)
                                                where (Guid)entity[ForeignKeyField] == PrimaryEntity.Id
                                                select entity;

                    EntityCollection col = new EntityCollection(query.ToList());
                    col.EntityName = RelatedEntityName;
                    return(col);
                }
            }
        }
Exemplo n.º 2
0
 public static void UpdateEntity(Entity entity, CrmConnection connection = null)
 {
     using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
     {
         service.Update(entity);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Method that occurs when validation is performed on the server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void LocationServerValidate(object sender, ServerValidateEventArgs args)
        {
            var location = args.Value;

            if (string.IsNullOrWhiteSpace(location))
            {
                args.IsValid = false;

                return;
            }

            var context = new CrmOrganizationServiceContext();

            try
            {
                args.IsValid = Validate(context, location);
            }
            catch (Exception e)
            {
                args.IsValid = false;

                var validator = sender as CustomValidator;

                if (validator != null)
                {
                    validator.ErrorMessage = string.Format(ResourceManager.GetString("Geolocation_Query_Could_Not_Be_Completed"), BingMapRestUrl, e.Message);
                }
            }
        }
Exemplo n.º 4
0
        private static int GetImportStatus(CrmOrganizationServiceContext serviceContext, Guid importId)
        {
            var importEntity   = serviceContext.Retrieve("import", importId, new ColumnSet(new[] { "statuscode" }));
            var attributeValue = importEntity.GetAttributeValue <OptionSetValue>("statuscode");

            return((attributeValue == null) ? 0 : attributeValue.Value);
        }
Exemplo n.º 5
0
        public static Profile GetProfile(string ProfileName)
        {
            FilterExpression filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition(new ConditionExpression("appl_name", ConditionOperator.Equal, ProfileName));
            EntityCollection col = XrmCore.RetrieveByFilter("appl_profiledefinition", filter);

            if (col.Entities.Count != 1)
            {
                throw new Exception(string.Format("There are {0} profiles with the name {1}. 1 was expected", col.Entities.Count, ProfileName));
            }

            Guid ProfileDefinitionId = col.Entities.First().GetAttributeValue <Guid>("appl_profiledefinitionid");

            using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(XrmConnection.Connection))
            {
                IQueryable <Entity> query = from field in service.CreateQuery("appl_profilefield")
                                            join related in service.CreateQuery("appl_profilefield_appl_profiledefinitio") on field["appl_profilefieldid"] equals related["appl_profilefieldid"]
                                            join profiledef in service.CreateQuery("appl_profiledefinition") on related["appl_profiledefinitionid"] equals profiledef["appl_profiledefinitionid"]
                                            where (string)profiledef["appl_name"] == ProfileName
                                            select field;

                return(Profile.Factory(new EntityCollection(query.ToList()), ProfileDefinitionId));
            }
        }
Exemplo n.º 6
0
        private static void LoadSprava()
        {
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Дела_юр.xlsx");

            for (int i = 37; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newSprava = new new_spravastr()
                {
                    new_businessnumber   = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    new_nameid           = FindClient(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    new_partnercustomer  = FindAccount(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    new_typeofbusiness   = EntityForm(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    new_type_of_business = CheckType(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    new_priority         = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    new_state            = FindState(dataFromXmlx.Tables[0].Rows[i][6].ToString()),
                    new_creationdate     = FindDate(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    new_liquidated       = FindBit(dataFromXmlx.Tables[0].Rows[i][8].ToString()),
                    new_gai                    = FindGos(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    new_datedtp                = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString()),
                    new_Dateagreement          = FindDate(dataFromXmlx.Tables[0].Rows[i][11].ToString()),
                    new_date_of_birth          = FindDate(dataFromXmlx.Tables[0].Rows[i][12].ToString()),
                    new_date_death             = FindDate(dataFromXmlx.Tables[0].Rows[i][13].ToString()),
                    new_pledge                 = dataFromXmlx.Tables[0].Rows[i][14].ToString(),
                    new_property1              = dataFromXmlx.Tables[0].Rows[i][15].ToString(),
                    new_property2              = dataFromXmlx.Tables[0].Rows[i][16].ToString(),
                    new_taxnumber              = dataFromXmlx.Tables[0].Rows[i][17].ToString(),
                    new_code                   = dataFromXmlx.Tables[0].Rows[i][18].ToString(),
                    new_placedtp               = dataFromXmlx.Tables[0].Rows[i][19].ToString(),
                    new_locality               = dataFromXmlx.Tables[0].Rows[i][20].ToString(),
                    new_home                   = dataFromXmlx.Tables[0].Rows[i][21].ToString(),
                    new_Place_of_work_1        = dataFromXmlx.Tables[0].Rows[i][22].ToString(),
                    new_Place_of_work_2        = dataFromXmlx.Tables[0].Rows[i][23].ToString(),
                    new_Companyname            = dataFromXmlx.Tables[0].Rows[i][24].ToString(),
                    new_insurancecompany       = dataFromXmlx.Tables[0].Rows[i][25].ToString(),
                    new_taxaddress             = dataFromXmlx.Tables[0].Rows[i][26].ToString(),
                    new_heir1                  = FindClient(dataFromXmlx.Tables[0].Rows[i][27].ToString()),
                    new_heir2                  = FindClient(dataFromXmlx.Tables[0].Rows[i][28].ToString()),
                    new_heir3                  = FindClient(dataFromXmlx.Tables[0].Rows[i][29].ToString()),
                    new_Credit_agreement       = dataFromXmlx.Tables[0].Rows[i][30].ToString(),
                    new_Social_security_number = dataFromXmlx.Tables[0].Rows[i][31].ToString(),
                    new_litigationnumber       = dataFromXmlx.Tables[0].Rows[i][32].ToString(),
                    new_guarantor1             = FindClient(dataFromXmlx.Tables[0].Rows[i][33].ToString()),
                    new_guarantor2             = FindClient(dataFromXmlx.Tables[0].Rows[i][34].ToString()),
                    new_guarantor3             = FindClient(dataFromXmlx.Tables[0].Rows[i][35].ToString()),
                    new_amount_loan            = ToDouble(dataFromXmlx.Tables[0].Rows[i][36].ToString()),
                    new_spouse                 = FindClient(dataFromXmlx.Tables[0].Rows[i][37].ToString()),
                    new_accident1              = FindClient(dataFromXmlx.Tables[0].Rows[i][38].ToString()),
                    new_accident2              = FindClient(dataFromXmlx.Tables[0].Rows[i][39].ToString()),
                    new_accident3              = FindClient(dataFromXmlx.Tables[0].Rows[i][40].ToString()),
                    new_accident4              = FindClient(dataFromXmlx.Tables[0].Rows[i][41].ToString()),
                    new_institution            = FindGos(dataFromXmlx.Tables[0].Rows[i][42].ToString()),
                    new_amount                 = ToDouble(dataFromXmlx.Tables[0].Rows[i][43].ToString())
                };
                service.Create(newSprava);
                Console.WriteLine("{0} Обработан и создан: {1}", i, dataFromXmlx.Tables[0].Rows[i][0].ToString());
            }
        }
Exemplo n.º 7
0
 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));
         }
     }
 }
Exemplo n.º 8
0
        private void Delete()
        {
            Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to the Organization {0}.", this.OrganizationUrl));
            string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout);
            var    connection       = CrmConnection.Parse(connectionString);

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var deleteDataMapId = DeleteDataMap(serviceContext, this.Name);
                    if (deleteDataMapId == Guid.Empty)
                    {
                        Log.LogWarning(string.Format(CultureInfo.CurrentCulture, "No Data Map with name {0} was found in Organization with Url {1}.", this.Name, this.OrganizationUrl));
                    }
                    else
                    {
                        Log.LogMessage(string.Format(CultureInfo.CurrentCulture, "Successfully deleted Data Map {0} from Organization with Url {1}.", this.Name, this.OrganizationUrl));
                    }
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                     CultureInfo.CurrentCulture,
                                     "An error occurred while deleting Data Map {0} from Organization with Url {1}. [{2}]",
                                     this.Name,
                                     this.OrganizationUrl,
                                     exception.Message));
                }
            }
        }
Exemplo n.º 9
0
 public CrmDataSourceView(CrmDataSource owner, string name, HttpContext context)
     : base(owner, name)
 {
     _cancelSelectOnNullParameter = true;
     _owner          = owner;
     _context        = context;
     _crmDataContext = OrganizationServiceContextFactory.Create(_owner.CrmDataContextName);
 }
Exemplo n.º 10
0
        public void UpdateStatus(ServiceRequest serviceRequest)
        {
            var idOfUpdatedItem = serviceRequest.SRID;

            //Login and connect to the server and create the context
            var connection = ConnectToDatabase();
            var service    = new OrganizationService(connection);
            var context    = new CrmOrganizationServiceContext(connection);

            //Gather the components for the "Retrieve" function
            ColumnSet set = new ColumnSet();

            set.AllColumns = true;
            Guid incidentGuid = GetGUIDByName(idOfUpdatedItem, service);

            //Retrieves the record that will be updated
            var incident = service.Retrieve("incident", incidentGuid, set);

            EventLog.saveMessage("Update Status of SRID:" + serviceRequest.SRID);

            try
            {
                // Actual UPDATE of the record.

                incident["description"]         = serviceRequest.LongDescription;
                incident["statuscode"]          = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"]           = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson,service));
                incident["new_statushistory"] = serviceRequest.CommentsMatricia;
                incident["casetypecode"]      = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["new_caseasignedto"] = serviceRequest.AssignedPerson;
                //incident["followupby"] = serviceRequest.DueDate;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"]        = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"]  = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);

                //Assign a case!


                service.Update(incident);

                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target   = new EntityReference(incident.LogicalName, incidentGuid);
                service.Execute(assignRequest);
            }
            catch (Exception)
            {
                EventLog.saveMessage("This record is unavailable for update right now!" + serviceRequest.SRID);
                return;
            }
        }
Exemplo n.º 11
0
 public static Guid CreateEntity(Entity entity, CrmConnection connection = null)
 {
     using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
     {
         Guid id = service.Create(entity);
         entity.Id = id;
         return(id);
     }
 }
Exemplo n.º 12
0
        public List <Account> GetAllByName(string name)
        {
            using (var context = new CrmOrganizationServiceContext(_service))
            {
                var accs = context.CreateQuery <Account>().Where(x => x.Name.Contains(name)).ToList();

                return(accs);
            }
        }
Exemplo n.º 13
0
        private static OrganizationServiceContext CreateContext(string connectionStringName)
        {
            var context = new CrmOrganizationServiceContext(new CrmConnection(connectionStringName))
            {
                MergeOption = MergeOption.NoTracking
            };

            return(context);
        }
Exemplo n.º 14
0
        public void PublishInCRM(ServiceRequest serviceRequest)
        {
            //Connects to the database and Logs the User In
            var connection = ConnectToDatabase();
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            //const int hour = 60;

            EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID);

            //Creating the new Case
            Entity incident = new Entity("incident");

            try
            {
                //Filling the Data for the new case
                incident["createdon"] = serviceRequest.RegistrationDate;
                incident["description"] = serviceRequest.LongDescription;
                incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service));
                incident["new_caseasignedto"] = serviceRequest.AssignedPerson;
                incident["new_statushistory"] = serviceRequest.CommentsMatricia;
                incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["followupby"] = serviceRequest.DueDate;
                incident["new_supportrequestid"] = serviceRequest.SRID;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"] = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);

                
                //Adding the created case to CRM;
                var incidentGuid = service.Create(incident);

                //Assign a case!
                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid);

                service.Execute(assignRequest);
            }
            catch (Exception)
            {
                EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID); ;
            }



        }
Exemplo n.º 15
0
        private static Guid CreateImportEntity(CrmOrganizationServiceContext serviceContext, string sourceEntityName)
        {
            var import = new Import
            {
                Name     = "Import of " + sourceEntityName,
                ModeCode = new OptionSetValue(0)
            };

            return(serviceContext.Create(import));
        }
Exemplo n.º 16
0
        public static TResponse Execute <TRequest, TResponse>(TRequest request, CrmConnection connection = null)
            where TRequest : OrganizationRequest
            where TResponse : OrganizationResponse
        {
            OrganizationService srv = new OrganizationService(connection ?? XrmConnection.Connection);

            using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv))
            {
                return((TResponse)service.Execute(request));
            }
        }
Exemplo n.º 17
0
 public Account GetByName(string name)
 {
     if (name != null && name.Length > 0)
     {
         using (var context = new CrmOrganizationServiceContext(_service))
         {
             var acc = context.CreateQuery <Account>().Where(x => x.Name == name).FirstOrDefault();
             return(acc);
         }
     }
     return(null);
 }
Exemplo n.º 18
0
        public void PublishInCRM(ServiceRequest serviceRequest)
        {
            //Connects to the database and Logs the User In
            var connection = ConnectToDatabase();
            var service    = new OrganizationService(connection);
            var context    = new CrmOrganizationServiceContext(connection);

            //const int hour = 60;

            EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID);

            //Creating the new Case
            Entity incident = new Entity("incident");

            try
            {
                //Filling the Data for the new case
                incident["createdon"]           = serviceRequest.RegistrationDate;
                incident["description"]         = serviceRequest.LongDescription;
                incident["statuscode"]          = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"]           = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service));
                incident["new_caseasignedto"]    = serviceRequest.AssignedPerson;
                incident["new_statushistory"]    = serviceRequest.CommentsMatricia;
                incident["casetypecode"]         = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["followupby"]           = serviceRequest.DueDate;
                incident["new_supportrequestid"] = serviceRequest.SRID;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"]        = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"]  = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);


                //Adding the created case to CRM;
                var incidentGuid = service.Create(incident);

                //Assign a case!
                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target   = new EntityReference(incident.LogicalName, incidentGuid);

                service.Execute(assignRequest);
            }
            catch (Exception)
            {
                EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID);;
            }
        }
Exemplo n.º 19
0
        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));
                }
            }
        }
Exemplo n.º 20
0
        private static Guid DeleteDataMap(CrmOrganizationServiceContext serviceContext, string dataMapName)
        {
            Entity entity = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue <string>("name") == dataMapName);

            if (entity == null)
            {
                return(Guid.Empty);
            }

            Guid dataMapId = entity.Id;

            serviceContext.Delete("importmap", dataMapId);
            return(dataMapId);
        }
Exemplo n.º 21
0
        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));
                }
            }
        }
Exemplo n.º 22
0
        private void ImportDataMap()
        {
            if (string.IsNullOrWhiteSpace(this.FilePath))
            {
                this.Log.LogError("Required parameter missing: FilePath");
                return;
            }

            if (!File.Exists(this.FilePath))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find Data Map 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);
            var    mapText          = File.ReadAllText(this.FilePath);

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var request = new ImportMappingsImportMapRequest
                    {
                        MappingsXml = mapText,
                        ReplaceIds  = true
                    };

                    if (this.overwrite)
                    {
                        DeleteDataMap(serviceContext, this.Name);
                    }

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing Data Map {0}", this.Name));
                    serviceContext.Execute(request);
                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported Data Map {0} to organization with Url {1}.", this.Name, this.OrganizationUrl));
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                     CultureInfo.CurrentCulture,
                                     "An error occurred while importing Data Map {0} to Organization with Url {1}. [{2}]",
                                     this.Name,
                                     this.OrganizationUrl,
                                     exception.Message));
                }
            }
        }
Exemplo n.º 23
0
 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));
         }
     }
 }
Exemplo n.º 24
0
        private static EntityReference FindGos(string p)
        {
            //new_gosorgan
            var context = new CrmOrganizationServiceContext(connection);
            var gos     = (from i in context.CreateQuery <new_gosorgan>()
                           where i.new_name == p
                           select i).FirstOrDefault();

            if (gos == null)
            {
                return(null);
            }
            else
            {
                return(gos.ToEntityReference());
            }
        }
Exemplo n.º 25
0
        private static EntityReference ToSpravaEntity(string p)
        {
            var context = new CrmOrganizationServiceContext(connection);
            var sprava  = (from m in context.CreateQuery <new_spravastr>()
                           where m.new_businessnumber == p
                           select m).FirstOrDefault();

            if (sprava == null)
            {
                Console.WriteLine("{0} Ненайден дело", p);
                return(null);
            }
            else
            {
                return(sprava.ToEntityReference());
            }
        }
Exemplo n.º 26
0
        private void AddCartToSupportRequest(ShoppingCart myCart)
        {
            var context = new CrmOrganizationServiceContext(new CrmConnection("Xrm"));

            var supportRequest = new Entity("adx_supportrequest")
            {
                Id = CurrentStepEntityID
            };

            supportRequest.Attributes["adx_shoppingcartid"] = myCart.Entity.ToEntityReference();

            context.Attach(supportRequest);

            context.UpdateObject(supportRequest);

            context.SaveChanges();
        }
Exemplo n.º 27
0
        private static EntityReference FindAccount(string p)
        {
            var context = new CrmOrganizationServiceContext(connection);

            var account = (from i in context.CreateQuery <Account>()
                           where i.Name == p
                           select i).FirstOrDefault();

            if (account == null)
            {
                return(null);
            }
            else
            {
                return(account.ToEntityReference());
            }
        }
 static CommonCrm()
 {
     try
     {
         CommonCrm.crmConnection = new CrmConnection("Crm");
         // "Crm" is a connection string which goes like this in Web.config:
         //<connectionStrings>
         //    <add name="Crm" connectionString="Url=http://orgUrl; Domain=X; Username=Y; Password=Z;" />
         //</connectionStrings>
         CommonCrm.crmService = new OrganizationService(crmConnection);
         CommonCrm.crmContext = new CrmOrganizationServiceContext(crmService);
     }
     catch (Exception ex)
     {
         //Log exception (code removed)
         throw;
     }
 }
Exemplo n.º 29
0
 public static void AddRelated(Entity PrimaryEntity, EntityCollection RelatedEntities, string RelationshipName, CrmConnection connection = null)
 {
     using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
     {
         EntityReferenceCollection col = new EntityReferenceCollection();
         foreach (Entity ent in RelatedEntities.Entities)
         {
             col.Add(ent.ToEntityReference());
         }
         AssociateRequest request = new AssociateRequest()
         {
             Target          = PrimaryEntity.ToEntityReference(),
             RelatedEntities = col,
             Relationship    = new Relationship(RelationshipName)
         };
         AssociateResponse response = (AssociateResponse)service.Execute(request);
     }
 }
Exemplo n.º 30
0
        public static Entity GetWebUserFromLogin(string LoginProvider, string ProviderKey, CrmConnection connection = null)
        {
            using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
            {
                IQueryable <Entity> query = from entity in service.CreateQuery("appl_webuser")
                                            join login in service.CreateQuery("appl_webuserlogin") on
                                            entity["appl_webuserid"] equals login["appl_webuserid"]
                                            where login.GetAttributeValue <string>("appl_loginprovider") == LoginProvider && login.GetAttributeValue <string>("appl_providerkey") == ProviderKey
                                            select entity;

                List <Entity> result = query.ToList();
                if (result.Count > 0)
                {
                    return(result.First());
                }
            }
            return(null);
        }
Exemplo n.º 31
0
        private static IEnumerable <XObject> ToSolutions(IOrganizationService service)
        {
            using (var context = new CrmOrganizationServiceContext(service))
            {
                var solutions = context.CreateQuery("solution")
                                .Where(s => s.GetAttributeValue <bool>("isvisible"))
                                .Select(s => new
                {
                    UniqueName = s.GetAttributeValue <string>("uniquename"),
                    Name       = s.GetAttributeValue <string>("friendlyname"),
                    Version    = s.GetAttributeValue <string>("version"),
                    Publisher  = s.GetAttributeValue <EntityReference>("publisherid"),
                })
                                .ToList();

                return(solutions.Select(s => ToRow(s.UniqueName, s.Name, s.Version, s.Publisher.Name)));
            }
        }
Exemplo n.º 32
0
        public IOrganizationService GetOrganisationService()
        {
            CrmConnection connection = null;
            try
            {

                connection = _CrmConnectionProvider.GetOrganisationServiceConnection();
                connection.UserTokenExpiryWindow = new TimeSpan(0, 3, 0);
                // var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);
                // Optionally disbale caching?
                context.TryAccessCache(cache => cache.Mode = OrganizationServiceCacheMode.Disabled);
                return context;
            }
            catch (Exception ex)
            {
                throw new FailedToConnectToCrmException(connection, ex);
            }
        }
Exemplo n.º 33
0
        private void ImportDataMap()
        {
            if (string.IsNullOrWhiteSpace(this.FilePath))
            {
                this.Log.LogError("Required parameter missing: FilePath");
                return;
            }

            if (!File.Exists(this.FilePath))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find Data Map 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);
            var mapText = File.ReadAllText(this.FilePath);
            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var request = new ImportMappingsImportMapRequest
                    {
                        MappingsXml  = mapText,
                        ReplaceIds = true
                    };

                    if (this.overwrite)
                    {
                        DeleteDataMap(serviceContext, this.Name);
                    }

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing Data Map {0}", this.Name));
                    serviceContext.Execute(request);
                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported Data Map {0} to organization with Url {1}.", this.Name, this.OrganizationUrl));
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "An error occurred while importing Data Map {0} to Organization with Url {1}. [{2}]",
                                    this.Name,
                                    this.OrganizationUrl,
                                    exception.Message));
                }
            }
        }
Exemplo n.º 34
0
 private static EntityReference ToSpravaEntity(string p)
 {
     var context = new CrmOrganizationServiceContext(connection);
     var sprava = (from m in context.CreateQuery<new_spravastr>()
                   where m.new_businessnumber == p
                   select m).FirstOrDefault();
     if (sprava == null)
     {
         Console.WriteLine("{0} Ненайден дело", p);
         return null;
     }
     else
     {
         return sprava.ToEntityReference();
     }
 }
Exemplo n.º 35
0
        private static Guid DeleteDataMap(CrmOrganizationServiceContext serviceContext, string dataMapName)
        {
            Entity entity = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue<string>("name") == dataMapName);
            if (entity == null)
            {
                return Guid.Empty;
            }

            Guid dataMapId = entity.Id;
            serviceContext.Delete("importmap", dataMapId);
            return dataMapId;
        }
Exemplo n.º 36
0
        private static EntityReference FindAccount(string p)
        {
            var context = new CrmOrganizationServiceContext(connection);

            var account = (from i in context.CreateQuery<Account>()
                           where i.Name == p
                           select i).FirstOrDefault();
            if (account == null)
            {
                return null;
            }
            else
            {
                return account.ToEntityReference();
            }
        }
Exemplo n.º 37
0
        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));
                }
            }
        }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            try
            {
                logfilename = string.Format("{0}.log", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                log("BEGIN");
                log("This code is supplied as is without guarantee. The latest code can be download from https://mscrmworkflowrunner.codeplex.com/");
                if (args.Count() != 1)
                {
                    throw new Exception("Invalid argument: config xml file.");
                }

                log(string.Format("Config file: {0}", args[0].ToString()));

                var configxml = new XmlDocument();
                configxml.Load(args[0].ToString());
                var connectionstring = configxml.SelectSingleNode("//config/connectionstring").InnerText;
                var workflownode = configxml.SelectSingleNode("//config/workflow");
                var workflowname = workflownode.Attributes["name"] != null ? workflownode.Attributes["name"].Value : null;
                Guid workflowid = workflownode.Attributes["id"] != null && !string.IsNullOrEmpty(workflownode.Attributes["id"].Value) ? new Guid(workflownode.Attributes["id"].Value) : Guid.Empty;
                var fetchxml = configxml.SelectSingleNode("//config/fetchxml").InnerText;

                var connection = CrmConnection.Parse(connectionstring);

                var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);

                if (workflowid == Guid.Empty)
                {
                    if (workflowname == null)
                    {
                        throw new Exception("Workflow name is required when no workflow id is specified!");
                    }
                    var query = new FetchExpression("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                        "  <entity name='workflow'>" +
                        "    <attribute name='workflowid' />" +
                        "    <attribute name='name' />" +
                        "    <filter type='and'>" +
                        "      <condition attribute='category' operator='eq' value='0' />" +
                        "      <condition attribute='type' operator='eq' value='1' />" +
                        "      <condition attribute='name' operator='eq' value='" + workflowname + "' />" +
                        "    </filter>" +
                        "  </entity>" +
                        "</fetch>");
                    var workflows = service.RetrieveMultiple(query);
                    if (workflows.Entities.Count < 1)
                    {
                        throw new Exception(string.Format("A workflow with the name {0} could not be found!", workflowname));
                    }
                    else if (workflows.Entities.Count > 1)
                    {
                        throw new Exception(string.Format("More than one workflow with the name {0} found!", workflowname));
                    }
                    workflowid = workflows.Entities[0].Id;
                }

                var results = service.RetrieveMultiple(new FetchExpression(fetchxml));

                foreach (var entity in results.Entities)
                {
                    var req = new ExecuteWorkflowRequest()
                    {
                        EntityId = entity.Id,
                        WorkflowId = workflowid
                    };
                    try
                    {
                        service.Execute(req);
                        logsuccess(string.Format("Workflow request complete for entity id {0}", entity.Id.ToString()));
                    }
                    catch (Exception ex)
                    {
                        logerror(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                logerror(ex.Message);
            }
            finally
            {
                log("END");
            }
        }
Exemplo n.º 39
0
 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));
         }
     }
 }
Exemplo n.º 40
0
 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));
         }
     }
 }
Exemplo n.º 41
0
        private void CreateImportFileEntity(CrmOrganizationServiceContext serviceContext, string content, Guid importId, Guid dataMapId)
        {
            var importFile = new ImportFile
            {
                Name = Path.GetFileName(this.FilePath),
                Source = this.FilePath,
                Content = content,
                SourceEntityName = this.SourceEntityName,
                TargetEntityName = this.TargetEntityName,
                FileTypeCode = new OptionSetValue(0),
                DataDelimiterCode = new OptionSetValue(1),
                FieldDelimiterCode = new OptionSetValue(2),
                IsFirstRowHeader = new bool?(true),
                EnableDuplicateDetection = new bool?(false),
                ProcessCode = new OptionSetValue(1),
                ImportId = new EntityReference("import", importId),
                ImportMapId = new EntityReference("importmap", dataMapId)
            };

            serviceContext.Create(importFile);
        }
Exemplo n.º 42
0
        public void UpdateAssignedPerson(ServiceRequest serviceRequest)
        {
            var idOfUpdatedItem = serviceRequest.SRID;

            var connection = ConnectToDatabase();
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;

            //Gather the components for the "Retrieve" function
            Guid incidentGuid = GetGUIDByName(idOfUpdatedItem, service);

            //Retrieves the record that will be updated
            var incident = service.Retrieve("incident", incidentGuid, set);
            EventLog.saveMessage("Updating the consultant person of case: " + serviceRequest.SRID + "to " + serviceRequest.AssignedPerson);
            try
            {
                //Assign a case!
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid);

                //sets the new User.
                //incident["ownerid"] = new EntityReference("systemuser", consultantID);
               
                service.Update(incident);
                service.Execute(assignRequest);

            }
            catch (Exception)
            {
                EventLog.saveMessage("Updating the consultant person of case: " + serviceRequest.SRID + "to " + serviceRequest.AssignedPerson + " failed!");

                return;
            }
        }
Exemplo n.º 43
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));
                }
            }
        }
Exemplo n.º 44
0
        private static Guid CreateImportEntity(CrmOrganizationServiceContext serviceContext, string sourceEntityName)
        {
            var import = new Import
            {
                Name = "Import of " + sourceEntityName,
                ModeCode = new OptionSetValue(0)
            };

            return serviceContext.Create(import);
        }
Exemplo n.º 45
0
 private static EntityReference FindGos(string p)
 {
     //new_gosorgan
     var context = new CrmOrganizationServiceContext(connection);
     var gos = (from i in context.CreateQuery<new_gosorgan>()
                where i.new_name == p
                select i).FirstOrDefault();
     if (gos == null)
     {
         return null;
     }
     else
     {
         return gos.ToEntityReference();
     }
 }
Exemplo n.º 46
0
 private void Delete()
 {
     Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to the Organization {0}.", this.OrganizationUrl));
     string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout);
     var connection = CrmConnection.Parse(connectionString);
     using (var serviceContext = new CrmOrganizationServiceContext(connection))
     {
         try
         {
             var deleteDataMapId = DeleteDataMap(serviceContext, this.Name);
             if (deleteDataMapId == Guid.Empty)
             {
                 Log.LogWarning(string.Format(CultureInfo.CurrentCulture, "No Data Map with name {0} was found in Organization with Url {1}.", this.Name, this.OrganizationUrl));
             }
             else
             {
                 Log.LogMessage(string.Format(CultureInfo.CurrentCulture, "Successfully deleted Data Map {0} from Organization with Url {1}.", this.Name, this.OrganizationUrl));
             }
         }
         catch (Exception exception)
         {
             Log.LogError(string.Format(
                             CultureInfo.CurrentCulture,
                             "An error occurred while deleting Data Map {0} from Organization with Url {1}. [{2}]",
                             this.Name,
                             this.OrganizationUrl,
                             exception.Message));
         }
     }
 }
Exemplo n.º 47
0
        private Entity GetVersionEntity(CrmOrganizationServiceContext serviceContext)
        {
            Entity returnEntity = null;
            var queryExpression = new QueryExpression("solution")
                                    {
                                        ColumnSet = new ColumnSet(new[] { "version" })
                                    };
            
            queryExpression.Criteria.AddCondition("uniquename", ConditionOperator.Equal, new object[] { this.Name });
            try
            {
                var entityCollection = serviceContext.RetrieveMultiple(queryExpression);
                if (entityCollection == null || entityCollection.Entities.Count == 0)
                {
                    Log.LogError(string.Format(
                        CultureInfo.CurrentCulture,
                        "Unable to retrieve details of Solution {0} from Organization with Url {1}.",
                        this.Name,
                        this.OrganizationUrl));
                }
                else
                {
                    returnEntity = entityCollection.Entities[0];
                }
            }
            catch (Exception exception)
            {
                Log.LogError(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "An error occurred while retrieving version details of Solution {0} from Organization with Url {1}. [{2}]",
                                    this.Name,
                                    this.OrganizationUrl,
                                    exception.Message));
            }

            return returnEntity;
        }
Exemplo n.º 48
0
        private static void LoadSprava()
        {
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Дела_юр.xlsx");

            for (int i = 37; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newSprava = new new_spravastr()
                {
                    new_businessnumber = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    new_nameid = FindClient(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    new_partnercustomer = FindAccount(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    new_typeofbusiness = EntityForm(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    new_type_of_business = CheckType(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    new_priority = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    new_state = FindState(dataFromXmlx.Tables[0].Rows[i][6].ToString()),
                    new_creationdate = FindDate(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    new_liquidated = FindBit(dataFromXmlx.Tables[0].Rows[i][8].ToString()),
                    new_gai = FindGos(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    new_datedtp = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString()),
                    new_Dateagreement = FindDate(dataFromXmlx.Tables[0].Rows[i][11].ToString()),
                    new_date_of_birth = FindDate(dataFromXmlx.Tables[0].Rows[i][12].ToString()),
                    new_date_death = FindDate(dataFromXmlx.Tables[0].Rows[i][13].ToString()),
                    new_pledge = dataFromXmlx.Tables[0].Rows[i][14].ToString(),
                    new_property1 = dataFromXmlx.Tables[0].Rows[i][15].ToString(),
                    new_property2 = dataFromXmlx.Tables[0].Rows[i][16].ToString(),
                    new_taxnumber = dataFromXmlx.Tables[0].Rows[i][17].ToString(),
                    new_code = dataFromXmlx.Tables[0].Rows[i][18].ToString(),
                    new_placedtp = dataFromXmlx.Tables[0].Rows[i][19].ToString(),
                    new_locality = dataFromXmlx.Tables[0].Rows[i][20].ToString(),
                    new_home = dataFromXmlx.Tables[0].Rows[i][21].ToString(),
                    new_Place_of_work_1 = dataFromXmlx.Tables[0].Rows[i][22].ToString(),
                    new_Place_of_work_2 = dataFromXmlx.Tables[0].Rows[i][23].ToString(),
                    new_Companyname = dataFromXmlx.Tables[0].Rows[i][24].ToString(),
                    new_insurancecompany = dataFromXmlx.Tables[0].Rows[i][25].ToString(),
                    new_taxaddress = dataFromXmlx.Tables[0].Rows[i][26].ToString(),
                    new_heir1 = FindClient(dataFromXmlx.Tables[0].Rows[i][27].ToString()),
                    new_heir2 = FindClient(dataFromXmlx.Tables[0].Rows[i][28].ToString()),
                    new_heir3 = FindClient(dataFromXmlx.Tables[0].Rows[i][29].ToString()),
                    new_Credit_agreement = dataFromXmlx.Tables[0].Rows[i][30].ToString(),
                    new_Social_security_number = dataFromXmlx.Tables[0].Rows[i][31].ToString(),
                    new_litigationnumber = dataFromXmlx.Tables[0].Rows[i][32].ToString(),
                    new_guarantor1 = FindClient(dataFromXmlx.Tables[0].Rows[i][33].ToString()),
                    new_guarantor2 = FindClient(dataFromXmlx.Tables[0].Rows[i][34].ToString()),
                    new_guarantor3 = FindClient(dataFromXmlx.Tables[0].Rows[i][35].ToString()),
                    new_amount_loan = ToDouble(dataFromXmlx.Tables[0].Rows[i][36].ToString()),
                    new_spouse = FindClient(dataFromXmlx.Tables[0].Rows[i][37].ToString()),
                    new_accident1 = FindClient(dataFromXmlx.Tables[0].Rows[i][38].ToString()),
                    new_accident2 = FindClient(dataFromXmlx.Tables[0].Rows[i][39].ToString()),
                    new_accident3 = FindClient(dataFromXmlx.Tables[0].Rows[i][40].ToString()),
                    new_accident4 = FindClient(dataFromXmlx.Tables[0].Rows[i][41].ToString()),
                    new_institution = FindGos(dataFromXmlx.Tables[0].Rows[i][42].ToString()),
                    new_amount = ToDouble(dataFromXmlx.Tables[0].Rows[i][43].ToString())
                };
                service.Create(newSprava);
                Console.WriteLine("{0} Обработан и создан: {1}", i, dataFromXmlx.Tables[0].Rows[i][0].ToString());
            }
        }
Exemplo n.º 49
0
        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));
                }
            }
        }
Exemplo n.º 50
0
 private static int GetImportStatus(CrmOrganizationServiceContext serviceContext, Guid importId)
 {
     var importEntity = serviceContext.Retrieve("import", importId, new ColumnSet(new[] { "statuscode" }));
     var attributeValue = importEntity.GetAttributeValue<OptionSetValue>("statuscode");
     return (attributeValue == null) ? 0 : attributeValue.Value;
 }
        private void UpdateSettings()
        {
            if (string.IsNullOrWhiteSpace(this.OrganizationUrl) || !Uri.IsWellFormedUriString(this.OrganizationUrl, UriKind.Absolute))
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Organization Url is not valid. {0}", this.OrganizationUrl));
                return;
            }

            if (this.Settings == null)
            {
                Log.LogError("Required parameter missing: Settings");
                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);
            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    var request = new RetrieveEntityRequest
                    {
                        EntityFilters = EntityFilters.Attributes,
                        LogicalName = "organization"
                    };

                    var response = serviceContext.Execute(request) as RetrieveEntityResponse;
                    if (response == null)
                    {
                        Log.LogError(string.Format(
                                        CultureInfo.CurrentCulture,
                                        "No response was received while retrieving settings for Organization with Url {0}",
                                        this.OrganizationUrl));
                        return;
                    }

                    var columnSet = new ColumnSet();
                    foreach (var settingItem in this.Settings)
                    {
                        string settingName = settingItem.ItemSpec;
                        columnSet.AddColumn(settingName);
                        var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName);
                        if (setting == null || setting.AttributeType == null)
                        {
                            Log.LogError(string.Format(
                                            CultureInfo.CurrentCulture,
                                            "No meta data for setting {0} was found.",
                                            settingName));
                            return;
                        }
                    }

                    var entityCollection = serviceContext.RetrieveMultiple(
                        new QueryExpression("organization")
                        {
                            ColumnSet = columnSet
                        });

                    if (entityCollection == null || entityCollection.Entities.Count == 0)
                    {
                        Log.LogError(string.Format(
                                        CultureInfo.CurrentCulture,
                                        "No setting was found for one of the settings"));
                        return;
                    }

                    var entity = entityCollection.Entities.First();
                    foreach (var settingItem in this.Settings)
                    {
                        string settingName = settingItem.ItemSpec;
                        string settingValue = settingItem.GetMetadata("value");
                        var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName);
                        if (setting == null || setting.AttributeType == null)
                        {
                            Log.LogError(string.Format(
                                            CultureInfo.CurrentCulture,
                                            "No meta data was found for setting with Name {0} was found.", 
                                            settingName));
                            return;
                        }

                        entity.Attributes[settingName] = ConvertCrmTypeToDotNetType(setting.AttributeType.Value, settingValue);
                    }

                    serviceContext.Update(entity);
                    Log.LogMessage(MessageImportance.High, "The organization settings were updated successfully.");   
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred while update settings for Organization with Url {0}. [{1}]", this.OrganizationUrl, exception.Message));   
                }
            }
        }
Exemplo n.º 52
0
        public void UpdateStatus(ServiceRequest serviceRequest)
        {
            var idOfUpdatedItem = serviceRequest.SRID;

            //Login and connect to the server and create the context
            var connection = ConnectToDatabase();
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            //Gather the components for the "Retrieve" function
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            Guid incidentGuid = GetGUIDByName(idOfUpdatedItem, service);

            //Retrieves the record that will be updated
            var incident = service.Retrieve("incident", incidentGuid, set);

            EventLog.saveMessage("Update Status of SRID:" + serviceRequest.SRID);

            try
            {
                // Actual UPDATE of the record.

                incident["description"] = serviceRequest.LongDescription;
                incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson,service));
                incident["new_statushistory"] = serviceRequest.CommentsMatricia;
                incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["new_caseasignedto"] = serviceRequest.AssignedPerson;
                //incident["followupby"] = serviceRequest.DueDate;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"] = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);

                //Assign a case!
               

                service.Update(incident);

                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid);
                service.Execute(assignRequest);

            }
            catch (Exception)
            {
                EventLog.saveMessage("This record is unavailable for update right now!" + serviceRequest.SRID);
                return;
            }

        }
Exemplo n.º 53
0
        private static EntityReference FindClient(string p)
        {
            if (p == string.Empty)
                return null;

            var context = new CrmOrganizationServiceContext(connection);

            Contact client = null; ;

            var splitP = p.Split();
            switch (splitP.Length)
            {
                case 4:
                    client = (from c in context.CreateQuery<Contact>()
                              where c.FullName == splitP[0] + " " + splitP[3]
                              select c).FirstOrDefault();
                    break;
                case 3:
                    client = (from c in context.CreateQuery<Contact>()
                              where c.FullName == splitP[0] + " " + splitP[2]
                              select c).FirstOrDefault();
                    break;
                case 2:
                    client = (from c in context.CreateQuery<Contact>()
                              where c.FullName == p
                              select c).FirstOrDefault();
                    break;
                case 1:
                    client = (from c in context.CreateQuery<Contact>()
                              where c.LastName == p
                              select c).FirstOrDefault();
                    break;
                default:
                    client = null;
                    break;
            }

            if (client == null)
            {
                if (splitP.Length == 4)
                {
                    client = (from c in context.CreateQuery<Contact>()
                              where c.FullName == splitP[0] + " " + splitP[1] + " " + splitP[3]
                              select c).FirstOrDefault();
                }
                else
                {
                    client = (from c in context.CreateQuery<Contact>()
                              where c.FullName == p
                              select c).FirstOrDefault();
                }
                if (client == null)
                {
                    Console.WriteLine("{0} Ненайден контакт", p);
                    return null;
                }
                return client.ToEntityReference();
            }
            else
            {
                return client.ToEntityReference();
            }
        }