Exemplo n.º 1
0
        /// <summary>
        /// Converts to the specified <see cref="DateTime"/> to the <see cref="CrmDateTime"/>.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        /// <returns></returns>
        public static CrmDateTime ToCrmDateTime(DateTime dateTime)
        {
            Assert.ArgumentNotNull(dateTime, "dateTime");
            var crmDateTime = new CrmDateTime();

            crmDateTime.Value = string.Format(CultureInfo.InvariantCulture,
                                              "{0:s}Z",
                                              new object[] { dateTime.ToUniversalTime() });
            return(crmDateTime);
        }
Exemplo n.º 2
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var result = new CrmDateTime();
            var start  = DateTime.Parse(StartDate.Value);

            if (start != DateTime.MinValue)
            {
                result = StartDate;
            }

            if (start != DateTime.MinValue && DaysToSub.Value != 0)
            {
                result.Value = start.Subtract(new TimeSpan(DaysToSub.Value, HoursToSub.Value, MinutesToSub.Value, 0)).ToString();
            }

            Result = result;
            return(ActivityExecutionStatus.Closed);
        }
Exemplo n.º 3
0
        public void PopulaCamposDataAniversario()
        {
            if (!entity.Properties.Contains("birthdate"))
            {
                return;
            }

            CrmDateTime dataAniversarioCrm = (CrmDateTime)entity.Properties["birthdate"];

            if (dataAniversarioCrm.IsNull)
            {
                return;
            }

            DateTime dataAniversario = Convert.ToDateTime(dataAniversarioCrm.Value);

            #region Dia
            PicklistProperty DiaCrm = new PicklistProperty()
            {
                Value = new Picklist(dataAniversario.Day),
                Name  = "new_aniversario_dia"
            };
            if (entity.Properties.Contains("new_aniversario_dia"))
            {
                entity.Properties.Remove("new_aniversario_dia");
            }
            entity.Properties.Add(DiaCrm);
            #endregion

            #region Mes
            PicklistProperty MesCrm = new PicklistProperty()
            {
                Value = new Picklist(dataAniversario.Month),
                Name  = "new_aniversario_mes"
            };
            if (entity.Properties.Contains("new_aniversario_mes"))
            {
                entity.Properties.Remove("new_aniversario_mes");
            }
            entity.Properties.Add(MesCrm);
            #endregion
        }
Exemplo n.º 4
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var result = new CrmDateTime();
            var start  = DateTime.Parse(StartDate.Value);

            if (start != DateTime.MinValue)
            {
                result = StartDate;
            }

            if (start != DateTime.MinValue && DaysToAdd.Value != 0)
            {
                result.Value = start.AddDays(DaysToAdd.Value).AddHours(HoursToAdd.Value).AddMinutes(MinutesToAdd.Value).ToString();
            }

            Result = result;


            return(ActivityExecutionStatus.Closed);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Метод создает новую запись сущности "contact".
        /// </summary>
        /// <param name="contactModel">Объект модели контакта.</param>
        public void AddContactToCrm(ContactEntityModel contactModel)
        {
            // Получаем токен.
            var token = new CrmAuthenticationToken
            {
                AuthenticationType = 0,
                OrganizationName   = "AdventureWorksCycle"
            };

            var connectionString = System.Configuration.ConfigurationManager.
                                   ConnectionStrings["CrmConnection"].ConnectionString;

            // Получаем сервис организации CRM.
            var service = new CrmService
            {
                Url = connectionString,
                CrmAuthenticationTokenValue = token,
                Credentials = System.Net.CredentialCache.DefaultCredentials
            };

            // Создаем новую запись.
            var newContact = new contact
            {
                firstname     = contactModel.ContactFirstName,
                lastname      = contactModel.ContactLastName,
                mobilephone   = contactModel.MobilePhone,
                emailaddress1 = contactModel.Email,
                jobtitle      = contactModel.JobTitle
            };

            if (contactModel.BirthDay.HasValue)
            {
                newContact.birthdate = CrmDateTime.FromUser(contactModel.BirthDay.Value);
            }

            service.Create(newContact);
        }
Exemplo n.º 6
0
 public static DateTime?Convert(CrmDateTime obj)
 {
     return(obj.IsNull == false ? (DateTime?)obj.UserTime : null);
 }
Exemplo n.º 7
0
        public string Pay(Reestr r)
        {
            logger.Info("_______pay______");
            logger.Info(r.txn_id);
            logger.Info(r.txn_date);
            logger.Info(r.opportunityID);
            logger.Info(r.sum);
            logger.Info("_______pay______");

            String errormsg = "";

            BusinessEntityCollection opportunity;
            BusinessEntityCollection existing_reestr;

            try
            {
                existing_reestr = searchnew_reestr(r.txn_id);
                foreach (Microsoft.Crm.Sdk.DynamicEntity reestr in existing_reestr.BusinessEntities)
                {
                    errormsg = $"Реестра оплат с именем {r.txn_id} уже существует. new_reestrid: {((Microsoft.Crm.Sdk.Key)((reestr).Properties["new_reestrid"])).Value.ToString()}";
                    logger.Error(errormsg);
                    return(errormsg);
                }
            }
            catch (Exception ex)
            {
                errormsg = $"Не удалось осуществить поиск Реестра оплат с txn_id={r.txn_id}. Ошибка: {ex.Message}";
                logger.Error(errormsg);
                return(errormsg);
            }


            try
            {
                Opp opp = new Opp();
                opportunity = opp.searchOpportunity(r.opportunityID.ToString());
            }
            catch (Exception ex)
            {
                errormsg = $"Не удалось осуществить поиск договора № {r.opportunityID.ToString()}. Ошибка: {ex.Message}";
                logger.Error(errormsg);
                return(errormsg);
            }


            CrmConnection crmc       = new CrmConnection("Crm");
            CrmService    crmService = crmc.CreateCrmService();

            DynamicEntity new_reestr = new DynamicEntity("new_reestr");

            new_reestr.Name = "new_reestr";


            foreach (Microsoft.Crm.Sdk.DynamicEntity opp in opportunity.BusinessEntities)
            {
                try
                {
                    // new_reestr.Properties.Add(new CrmDateTimeProperty("new_data", CrmTypes.CreateCrmDateTimeFromUser(DateTime.ParseExact(txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                    new_reestr.Properties.Add(new CrmDateTimeProperty("new_data", CrmDateTime.FromUser(DateTime.ParseExact(r.txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }
                catch (Exception ex)
                {
                    errormsg = $"Не удалось конвертировать входное значение txn_date=[{r.txn_date}] в дату. Ошибка: {ex.Message}";
                    logger.Error(errormsg);
                    return(errormsg);
                }
                try
                {
                    new_reestr.Properties.Add(new CrmMoneyProperty("new_summ", new CrmMoney(decimal.Parse(r.sum, CultureInfo.InvariantCulture))));
                }
                catch (Exception ex)
                {
                    errormsg = $"Не удалось конвертировать входное значение sum=[{r.sum}] в decimal. Ошибка: {ex.Message}";
                    logger.Error(errormsg);
                    return(errormsg);
                }

                new_reestr.Properties.Add(new PicklistProperty("new_source", new Picklist(10)));//Интернет - эквайринг
                new_reestr.Properties.Add(new StringProperty("new_name", r.txn_id.ToString()));
                new_reestr.Properties.Add(new StringProperty("new_txn_id", r.txn_id.ToString()));
                new_reestr.Properties.Add(new LookupProperty("new_dogovor", new Lookup("opportunity", ((Microsoft.Crm.Sdk.Key)(((Microsoft.Crm.Sdk.DynamicEntity)opportunity.BusinessEntities[0]).Properties["opportunityid"])).Value)));
                if (opp.Properties.Contains("new_signdate"))
                {
                    new_reestr.Properties.Add(new CrmDateTimeProperty("new_data_dogovor", (CrmDateTime)opp["new_signdate"]));
                }
                if (opp.Properties.Contains("customerid"))
                {
                    Customer customer = (Customer)opp["customerid"];
                    new_reestr.Properties.Add(new LookupProperty("new_customerid", new Lookup(customer.type, customer.Value)));
                }

                if (opp.Properties.Contains("new_programsidcost"))
                {
                    Lookup lu = (Lookup)opp["new_programsidcost"];
                    new_reestr.Properties.Add(new LookupProperty("new_programsid", new Lookup(lu.type, lu.Value)));
                }

                if (opp.Properties.Contains("new_studyplaceid"))
                {
                    Lookup lu = (Lookup)opp["new_studyplaceid"];
                    new_reestr.Properties.Add(new LookupProperty("new_studyplaceid", new Lookup(lu.type, lu.Value)));
                }
                if (opp.Properties.Contains("new_placeofwriteid"))
                {
                    Lookup lu = (Lookup)opp["new_placeofwriteid"];
                    new_reestr.Properties.Add(new LookupProperty("new_placeofwriteid", new Lookup(lu.type, lu.Value)));
                }
                if (opp.Properties.Contains("ownerid"))
                {
                    Owner lu = (Owner)opp["ownerid"];
                    new_reestr.Properties.Add(new LookupProperty("new_ownerid", new Lookup(lu.type, lu.Value)));
                }
                DateTime new_month_income = DateTime.ParseExact(r.txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                new_month_income = new_month_income.AddDays((new_month_income.Day * -1) + 1);
                new_month_income = new_month_income.AddHours((new_month_income.Hour * -1) + 12);
                new_reestr.Properties.Add(new CrmDateTimeProperty("new_month_income", CrmDateTime.FromUser(new_month_income)));
            }
            Guid new_reestrID = Guid.Empty;

            try
            {
                new_reestrID = crmService.Create(new_reestr);
            }
            catch (Exception ex)
            {
                errormsg = $"Не удалось Создать запись реестра оплат для договора № {r.opportunityID.ToString()}. Ошибка: {ex.Message}";
                logger.Error(errormsg);
                return(errormsg);
            }
            return(new_reestrID.ToString());
        }
Exemplo n.º 8
0
    /// <summary>
    /// Set field value
    /// </summary>
    /// <param name="DynamicEntityObject">DynamicEntity</param>
    /// <param name="service">MetadataService</param>
    /// <param name="AttributeType">Type of attribute</param>
    /// <param name="AttributeName">Attribute name</param>
    /// <param name="AttributeValue1">Attribute first value</param>
    /// <param name="AttributeValue2">Attribute first value</param>
    /// <returns></returns>
    public static bool SetFieldValue(this DynamicEntity DynamicEntityObject, MetadataService service, String AttributeType, string AttributeName, String AttributeValue1, String AttributeValue2)
    {
        //bool ret = false;
        string TypeOfAttribute;    // = null;

        try
        {
            //$ when the
            if (DynamicEntityObject.Properties.Contains(AttributeName))
            {
                TypeOfAttribute = DynamicEntityObject.Properties[AttributeName].GetType().Name;
            }
            else
            {
                //TODO: replace this function with meta data service
                TypeOfAttribute = RetrieveAttributeMetadata(service, DynamicEntityObject.Name, AttributeName);
            }


            if (TypeOfAttribute == null || TypeOfAttribute == "PrimaryKey")
            {
                return(false);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Owner" || TypeOfAttribute == "Owner")
            {
                DynamicEntityObject[AttributeName] = new Lookup(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Customer" || TypeOfAttribute == "Customer")
            {
                DynamicEntityObject[AttributeName] = new Customer(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmDateTime" || TypeOfAttribute == "CrmDateTime" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.DateTimeAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new CrmDateTime(AttributeValue1);
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmBoolean" || TypeOfAttribute == "CrmBoolean" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.BooleanAttributeMetadata")
            {
                DynamicEntityObject.Properties[AttributeName] = new CrmBoolean(bool.Parse(AttributeValue1));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.String" || TypeOfAttribute == "String" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.StringAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = (string)AttributeValue1;
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Lookup" || TypeOfAttribute == "Lookup" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.LookupAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new Lookup(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Picklist" || TypeOfAttribute == "Picklist" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.PicklistAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new Picklist(int.Parse(AttributeValue1));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmNumber" || TypeOfAttribute == "CrmNumber" || TypeOfAttribute == "Integer" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.IntegerAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new CrmNumber(int.Parse(AttributeValue1));
                return(true);
            }
        }
        catch (SoapException sopEx)
        {
            throw;
        }

        return(false);
    }
Exemplo n.º 9
0
        public String CreateContact(Guid contact_ID, Contact contact)
        {
            Guid contactid = contact_ID;

            try
            {
                contact cont = new contact();


                CrmConnection crmc       = new CrmConnection("Crm");
                CrmService    crmService = crmc.CreateCrmService();

                if (contact_ID == new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    contactid = crmService.Create(cont);
                }

                // Создаем экземпляр динамческого объекта и указываем его имя
                DynamicEntity myDEUpdate = new DynamicEntity();
                myDEUpdate.Name = "contact";


                // Создаем KeyProperty для хранения GUID’а обновляемой записи
                KeyProperty myContactGuid = new KeyProperty();
                myContactGuid.Name = "contactid";

                // Указываем GUID обновляемой записи
                Key myContactKey = new Key();
                myContactKey.Value  = contactid;
                myContactGuid.Value = myContactKey;
                myDEUpdate.Properties.Add(myContactGuid);



                if (contact.address1_city != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_city", contact.address1_city));
                }

                if (contact.address1_country != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_country", contact.address1_country));
                }

                if (contact.address1_line1 != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_line1", contact.address1_line1));
                }

                if (contact.address1_name != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_name", contact.address1_name));
                }

                if (contact.address1_postalcode != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("address1_postalcode", contact.address1_postalcode));
                }

                if (contact.emailaddress1 != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("emailaddress1", contact.emailaddress1));
                }

                if (contact.firstname != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("firstname", contact.firstname));
                }

                if (contact.lastname != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("lastname", contact.lastname));
                }

                if (contact.middlename != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("middlename", contact.middlename));
                }

                if (contact.mobilephone != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("mobilephone", contact.mobilephone));
                }

                if (contact.salutation != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("salutation", contact.salutation));
                }

                //Кем выдан
                if (contact.new_giveoutby != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby));
                }

                //Номер
                if (contact.new_nomer != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_nomer", contact.new_nomer));
                }

                //Серия
                if (contact.new_seria != null)
                {
                    myDEUpdate.Properties.Add(new StringProperty("new_seria", contact.new_seria));
                }



                //Пол
                if (contact.gendercode != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("gendercode", new Picklist(contact.gendercode)));
                }

                //Гражданство
                if (contact.new_nationality != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("new_nationality", new Picklist(contact.new_nationality)));
                }

                //Тип ФЛ
                if (contact.new_type != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("new_type", new Picklist(contact.new_type)));
                }

                //Семейное положение
                if (contact.familystatuscode != 0)
                {
                    myDEUpdate.Properties.Add(new PicklistProperty("familystatuscode", new Picklist(contact.familystatuscode)));
                }


                //День рождения
                if (contact.birthdate != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }

                //Посетил открытый урок
                if (contact.new_openles != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_openles", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_openles, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }

                //Дата выдачи
                if (contact.new_dategiveout != null)
                {
                    myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_dategiveout", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_dategiveout, "yyyyMMddHHmmss", CultureInfo.InvariantCulture))));
                }


                crmService.Update(myDEUpdate);


                //поиск контакта для переназначения ответственного, если таковой меняется
                Owner ownerID = new Owner();
                if (contact_ID != new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    try
                    {
                        string ln = ""; //фамилия
                        BusinessEntityCollection fcontact = searchContact(contact_ID.ToString());
                        foreach (DynamicEntity cont1 in fcontact.BusinessEntities)
                        {
                            ln = cont1["lastname"].ToString();
                            if (cont1.Properties.Contains("ownerid"))
                            {
                                ownerID = (Owner)cont1["ownerid"];
                            }
                        }

                        logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}");
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"Ошибка: {ex.ToString()}");
                    }
                }

                if (contact.ownerid != new Guid("{00000000-0000-0000-0000-000000000000}"))
                {
                    if (ownerID.Value != contact.ownerid)
                    {
                        TargetOwnedContact target   = new TargetOwnedContact();
                        SecurityPrincipal  assignee = new SecurityPrincipal();
                        assignee.Type        = SecurityPrincipalType.User;
                        assignee.PrincipalId = contact.ownerid;
                        target.EntityId      = contactid;

                        AssignRequest assign = new AssignRequest();
                        assign.Assignee = assignee;
                        assign.Target   = target;
                        AssignResponse res = (AssignResponse)crmService.Execute(assign);
                    }
                }
                return(contactid.ToString());
            }
            catch (SoapException ex)
            {
                logger.Error($"Ошибка: {ex.Detail.InnerText}");
                return(ex.Detail.InnerText);
            }
        }
Exemplo n.º 10
0
        public void Execute(IPluginExecutionContext context)
        {
            DateTime inicioExecucao = DateTime.Now;

            try
            {
                var prop = context.InputParameters.Properties;
                if (prop.Contains("Target") && prop["Target"] is DynamicEntity)
                {
                    PluginHelper.LogEmArquivo(context, "INICIO;", inicioExecucao.ToString(), "");
                    var organizacao = new Organizacao(context.OrganizationName);
                    var entidade    = prop["Target"] as DynamicEntity;

                    FacadeOcorrencia facade = new FacadeOcorrencia(context);
                    facade.Atender();

                    #region inserir resultado do atendimento do contexto

                    #region reincidencia

                    if (facade.Ocorrencia.OcorrenciaPai != null)
                    {
                        if (facade.Ocorrencia.OcorrenciaPai.Id != Guid.Empty)
                        {
                            entidade = PluginHelper.AdicionarPropriedadeEmEntidadeDinamica(entidade, "new_reincidenteid", new Lookup("incident", facade.Ocorrencia.OcorrenciaPai.Id));
                        }

                        if (facade.Ocorrencia.OcorrenciaPai.DataDeCriacao != DateTime.MinValue)
                        {
                            context.SharedVariables.Properties.Add(
                                new PropertyBagEntry("dataCriacaoReincidente", facade.Ocorrencia.OcorrenciaPai.DataDeCriacao.ToString())
                                );
                        }
                    }

                    #endregion

                    #region SLA

                    var sla = new CrmDateTime()
                    {
                        IsNull = true, IsNullSpecified = true
                    };
                    if (facade.Ocorrencia.DataSLA.HasValue)
                    {
                        sla = new CrmDateTime(facade.Ocorrencia.DataSLA.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    entidade = PluginHelper.AdicionarPropriedadeEmEntidadeDinamica(entidade, "followupby", sla);

                    var escalacao = new CrmDateTime()
                    {
                        IsNull = true, IsNullSpecified = true
                    };
                    if (facade.Ocorrencia.DataEscalacao.HasValue)
                    {
                        escalacao = new CrmDateTime(facade.Ocorrencia.DataEscalacao.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    entidade = PluginHelper.AdicionarPropriedadeEmEntidadeDinamica(entidade, "new_data_hora_escalacao", escalacao);

                    #endregion

                    #region  árvore de assunto

                    if (facade.Ocorrencia.EstruturaDeAssunto != null)
                    {
                        foreach (Assunto item in facade.Ocorrencia.EstruturaDeAssunto)
                        {
                            if (item.TipoDeAssunto != TipoDeAssunto.Vazio)
                            {
                                entidade = PluginHelper.AdicionarPropriedadeEmEntidadeDinamica(entidade, item.CampoRelacionadoNaOcorrencia, new Lookup("subject", item.Id));
                            }
                        }
                    }

                    #endregion

                    #region Valor do Serviço

                    if (facade.Ocorrencia.ValorServico.HasValue)
                    {
                        var ValorServicoCRM = new CrmMoney(facade.Ocorrencia.ValorServico.Value);
                        entidade = PluginHelper.AdicionarPropriedadeEmEntidadeDinamica(entidade, "new_valor_servico", ValorServicoCRM);
                    }

                    #endregion

                    #endregion
                    PluginHelper.LogEmArquivo(context, "FIM;", inicioExecucao.ToString(), DateTime.Now.ToString());
                }
            }
            catch (Exception ex)
            {
                PluginHelper.TratarExcecao(ex, TipoDeLog.PluginIncident);
                PluginHelper.LogEmArquivo(context, "ERRO;", inicioExecucao.ToString(), DateTime.Now.ToString());
            }
        }