예제 #1
1
        public Program()
        {
            m_service = new MockCrmService();

            // test data for simple fetch
            Entity de = new Entity();
            de.LogicalName = "mydynamic";
            de["prop1"] = "foo";
            Guid deID = m_service.Create( de );

            // test data for filters
            de = new Entity();
            de.LogicalName = "contact";
            de[ "address1_name" ] = "Dan";
            de[ "address1_city" ] = "Bethesda";
            Guid deID2 = m_service.Create( de );

            // data for testing links
            Guid guid = Guid.NewGuid();
            de = new Entity();
            de.LogicalName = "subject";
            de[ "subjectid" ] = guid;
            Guid deID3 = m_service.Create( de );

            de = new Entity();
            de.LogicalName = "subject";
            de[ "subjectid" ] = guid;
            de[ "title" ] = "child";
            de[ "parentsubject" ] = new EntityReference( "subject", deID3 );
            Guid deID4 = m_service.Create( de );
        }
예제 #2
1
        /// <summary>
        /// Code to create account task for new accounts
        /// </summary>
        /// <param name="service">crm service</param>
        /// <param name="accountEntity">entity of the newly created account</param>
        public void CreateAccountTask(IOrganizationService service, Entity accountEntity)
        {
            try
            {

                //create new task for account set in 2 weeks in the future
                Microsoft.Xrm.Sdk.Entity contactAccountTask = new Entity("task");
                contactAccountTask["subject"] = "Check new account is happy";
                contactAccountTask["description"] =
                "Make contact with new customer. See if they are happy with service and resolve any issues.";
                contactAccountTask["scheduledstart"] = DateTime.Now.AddDays(14);
                contactAccountTask["scheduledend"] = DateTime.Now.AddDays(14);
                Microsoft.Xrm.Sdk.EntityReference entRef = new EntityReference("account", accountEntity.Id);
                contactAccountTask["regardingobjectid"] = entRef;

                // Create the task and this should be linked to the new account record
                service.Create(contactAccountTask);

            }

            catch (FaultException ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }
        }
예제 #3
1
        private EntityCollection GenerateRandomAccountCollection()
        {
            var collection = new List<Entity>();
            for (var i = 0; i < 10; i++)
            {
                var rgn = new Random((int)DateTime.Now.Ticks);
                var entity = new Entity("account");
                entity["accountid"] = entity.Id = Guid.NewGuid();
                entity["address1_addressid"] = Guid.NewGuid();
                entity["modifiedon"] = DateTime.Now;
                entity["lastusedincampaign"] = DateTime.Now;
                entity["donotfax"] = rgn.NextBoolean();
                entity["new_verybignumber"] = rgn.NextInt64();
                entity["exchangerate"] = rgn.NextDecimal();
                entity["address1_latitude"] = rgn.NextDouble();
                entity["numberofemployees"] = rgn.NextInt32();
                entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid());
                entity["revenue"] = new Money(rgn.NextDecimal());
                entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid());
                entity["industrycode"] = new OptionSetValue(rgn.NextInt32());
                entity["name"] = rgn.NextString(15);
                entity["description"] = rgn.NextString(300);
                entity["statecode"] = new OptionSetValue(rgn.NextInt32());
                entity["statuscode"] = new OptionSetValue(rgn.NextInt32());
                collection.Add(entity);
            }

            return new EntityCollection(collection);
        }
예제 #4
0
파일: Program.cs 프로젝트: BISmb/Projects
        static void Main(string[] args)
        {
            //IOrganizationService service = XrmConnection.Connect(connectionDetails);
            XrmConnection connection = new XrmConnection();


            Console.WriteLine("Connected to CRM. Press enter to continue...");
            Console.ReadLine();

            RoleManager rm = new RoleManager(connection.service, connection.caller);

            Console.Write("User (Guid) to test:");
            //Guid userToTestGuid = new Guid(Console.ReadLine());
            Guid userToTestGuid = new Guid("1065A1BE-6BA3-E611-A161-000C29C78F2E");
            EntityReference testUser = new EntityReference("systemuser", userToTestGuid);

            Console.Write("User (Guid) to copy from:");
            //Guid userToCopyGuid = new Guid(Console.ReadLine());
            Guid userToCopyGuid = new Guid("84429B63-C273-E611-A14E-EACD0C285D01");
            EntityReference copyFromUser = new EntityReference("systemuser", userToCopyGuid);

            EntityCollection teams = rm.RetrieveUserTeams(copyFromUser);
            EntityCollection roles = rm.RetrieveUserRoles(copyFromUser);

            List <Entity> rolesList = new List<Entity>(roles.Entities);
            List<Entity> teamsList = new List<Entity>(teams.Entities);

            rm.AssignBusinessUnit(testUser, copyFromUser);
            rm.AddRolesToPrincipal(rolesList, testUser, rolesList);
        }
예제 #5
0
        public Boolean generateRiskFactorsForTemplate(EntityReference riskTemplate, Guid fundingCaseRiskAssessmentId)
        {
            try
            {
                //
                QueryExpression qe = new QueryExpression("gcbase_risktemplateriskfactor");
                qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplate.Id);
                qe.ColumnSet.AddColumns("gcbase_name", "gcbase_riskfactor", "gcbase_risktemplate");
                var riskFactors = _service.RetrieveMultiple(qe).Entities;

                foreach (var item in riskFactors)
                {
                    Entity riskFactorValue = new Entity("gcbase_riskfactorvalue");
                    riskFactorValue["gcbase_name"] = item.GetAttributeValue<EntityReference>("gcbase_riskfactor").Name;
                    riskFactorValue["gcbase_riskfactor"] = new EntityReference("gcbase_riskfactor", item.GetAttributeValue<EntityReference>("gcbase_riskfactor").Id);
                    riskFactorValue["gcbase_risktemplateriskfactor"] = new EntityReference("gcbase_risktemplateriskfactor", item.Id);
                    riskFactorValue["gcbase_fundingcaseriskassessment"] = new EntityReference("gcbase_fundingcaseriskassessment", fundingCaseRiskAssessmentId);
                    _service.Create(riskFactorValue);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
예제 #6
0
        public HttpResponseMessage Post(Guid taskId)
        {
            CrmConnection connection = CrmConnection.Parse(Strings.urlCreds);
            var ctx = new CrmServiceContext(new OrganizationService(connection));

            var taskReference = new EntityReference("task", taskId);

            try
            {
                var req = new SetStateRequest();
                req.State = new OptionSetValue(1);
                req.Status = new OptionSetValue(5);
                req.EntityMoniker = taskReference;

                var res = (SetStateResponse)ctx.Execute(req);
            }
            catch (Exception e)
            {
                return this.Request.CreateResponse(
                    HttpStatusCode.InternalServerError, e);
            }

            return this.Request.CreateResponse(
                HttpStatusCode.Created);
        }
        public void When_Executing_Assign_Request_New_Owner_Should_Be_Assigned()
        {
            var oldOwner = new EntityReference("systemuser", Guid.NewGuid());
            var newOwner = new EntityReference("systemuser", Guid.NewGuid());

            var account = new Account
            {
                Id = Guid.NewGuid(),
                OwnerId = oldOwner
            };

            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            context.Initialize(new [] { account });

            var assignRequest = new AssignRequest
            {
                Target = account.ToEntityReference(),
                Assignee = newOwner
            };
            service.Execute(assignRequest);

            Assert.Equal(newOwner, account.OwnerId);
        }
예제 #8
0
        public static bsv_cuentas GetCuenta(
            CajaDeAhorro sqlCuenta, 
            string nroCuenta,
            EntityReference modulo,
            EntityReference moneda,
            EntityReference sucursal,
            //EntityReference operacion,
            EntityReference tipoOperacion,
            EntityReference canalVenta,
            EntityReference estadoCuenta)
        {
            var cuenta = new bsv_cuentas();

            MapCuenta(
                sqlCuenta,
                nroCuenta,
                modulo,
                moneda,
                sucursal,
                tipoOperacion,
                canalVenta,
                estadoCuenta,
                cuenta);

            return cuenta;
        }
        public void Test_Includes_Mismatch()
        {
            Guid id1 = Guid.NewGuid();
            Guid id2 = Guid.NewGuid();

            string propertyName1 = "Property1";
            string propertyName2 = "Property2";

            string type1 = "Type1";
            string type2 = "Type2";

            EntityReference reference = new EntityReference();
            reference.Entity1ID = id1;
            reference.Entity2ID = id2;
            reference.Type1Name = type1;
            reference.Type2Name = type2;
            reference.Property1Name = propertyName1;
            reference.Property2Name = propertyName2;

            bool includes = reference.Includes(id1, propertyName2);

            Assert.IsFalse(includes, "Returned true when it should have returned false");

            includes = reference.Includes(id2, propertyName1);

            Assert.IsFalse(includes, "Returned true when it should have returned false");
        }
        public static Contact GetContact(PersonaFisica personaFisica, EntityReference domicilioPais, EntityReference actividadLaboral, EntityReference banca, EntityReference pais, EntityReference localidad, EntityReference sucursal, EntityReference segmento, EntityReference provincia, EntityReference profesion)
        {
            var contact = new Contact();

            MapContact(personaFisica, domicilioPais, actividadLaboral, banca, pais, localidad, sucursal, segmento, provincia, profesion, contact);

            return contact;
        }
예제 #11
0
 public static void IfReferenceTypeIsWrong(EntityReference id, string typeName)
 {
     if (id.LogicalName != typeName)
     {
         throw new InvalidPluginExecutionException(
             $"EntityReference of type {id.LogicalName} was used in the context where {typeName} is expected.");
     }
 }
        public static Account GetAccount(PersonaJuridica personaJuridica, EntityReference pais, EntityReference sucursal, EntityReference canalVenta, EntityReference segmento, EntityReference domicilioPais, EntityReference localidad, EntityReference provincia, EntityReference banca, EntityReference actividad)
        {
            var account = new Account();

            MapAccount(personaJuridica, account, pais, sucursal, canalVenta, segmento, domicilioPais, localidad, provincia, banca, actividad);

            return account;
        }
예제 #13
0
 private static string GetStringFromEntityReference(EntityReference reference)
 {
     string result = string.Empty;
     if (reference != null)
     {
         result = string.Format("{0}|{1}|{2}", reference.LogicalName, reference.Id, reference.Name);
     }
     return result;
 }
예제 #14
0
        public static object ToDbType(EntityReference val)
        {
            if (val == null)
            {
                return DBNull.Value;
            }

            return val.Id;
        }
예제 #15
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); ;
            }



        }
예제 #16
0
 public User(string username, string password, IEnumerable<string> roles, EntityReference company)
 {
     if (username == null) throw new ArgumentNullException("username");
     if (username.Count() < 3) throw new ArgumentException("UserName must be at least 3 characters long", "username");
     ValidatePassword(password);
     Username = username;
     Password = password;
     _roles = roles.ToList();
     Company = company;
 }
        public static IQueryable<Chart> SecurityFilter(this IQueryable<Chart> charts, EntityReference company, IEnumerable<string> roles)
        {
            if (charts == null) throw new ArgumentNullException("charts");

            if (roles != null && roles.Contains(Roles.SiteAdministrator))
                return charts;
            if (company == null)
                throw new ArgumentNullException("company");
            return charts.Where(x => x.Company.Id == company.Id);
        }
예제 #18
0
        public EntityReference GetDefaultUomScheduleReference()
        {
            UoMSchedule defaultUomSchedule = (from uoms in XrmContext.UoMScheduleSet
                                              where uoms.Name == defaultUomScheduleName
                                              select uoms).FirstOrDefault();
            var defaultUomScheduleReference = new EntityReference(defaultUomSchedule.LogicalName,
                                                                  defaultUomSchedule.UoMScheduleId.Value);

            return defaultUomScheduleReference;
        }
예제 #19
0
        public ServiceContextBase(IOrganizationService service)
        {
            LogHelper = new LogHelper(Console.WriteLine);
            AdminOrganizationService = service;
            OrganizationService = service;

            var response = (WhoAmIResponse)service.Execute(new WhoAmIRequest());
            UserId = response.UserId;
            InitiatingUserId = response.UserId;
            BusinessUnitRef = new EntityReference(BusinessUnitDefinition.EntityName, response.BusinessUnitId);
        }
예제 #20
0
        /// <summary>
        /// Checks if the "Est. Close Date" is greater than 10 days. If it is,
        /// send an email to the administrator so that s/he can verify close date
        /// with the owner of the opportunity.
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory =
                    executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service =
                    serviceFactory.CreateOrganizationService(context.UserId);

            // Get opportunity entity
            Entity opportunity = service.Retrieve("opportunity", 
                this.inputOpportunity.Get(executionContext).Id, new ColumnSet("estimatedclosedate"));

            // Calulate 10 days from today
            DateTime todayPlusTen = DateTime.UtcNow.AddDays(10.0);

            // Check "Est. Close Date"
            if (opportunity.Contains("estimatedclosedate"))
            {
                DateTime estCloseDate = (DateTime)opportunity["estimatedclosedate"];
                if (DateTime.Compare(estCloseDate, todayPlusTen) > 0)
                {
                    // Need system user id for activity party
                    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                    WhoAmIResponse systemUser = 
                        (WhoAmIResponse)service.Execute(systemUserRequest);

                    // Create an activity party for the email
                    Entity[] activityParty = new Entity[1];
                    activityParty[0] = new Entity("activityparty");
                    activityParty[0]["partyid"] = 
                        new EntityReference("systemuser", systemUser.UserId);

                    // Create an email message
                    Entity email = new Entity("email");
                    email.LogicalName = "email";
                    email["subject"] = 
                        "Warning: Close date has been extended more than 10 days.";
                    email["description"] = "Verify close date is correct.";
                    email["to"] = activityParty;
                    email["from"] = activityParty;
                    email["regardingobjectid"] = opportunity.ToEntityReference();
                    Guid emailId = service.Create(email);

                    // Send email
                    SendEmailRequest sendEmailRequest = new SendEmailRequest();
                    sendEmailRequest.EmailId = emailId;
                    sendEmailRequest.IssueSend = true;
                    sendEmailRequest.TrackingToken = "";
                    SendEmailResponse sendEmailResponse = 
                        (SendEmailResponse)service.Execute(sendEmailRequest);
                }
            }
        }
예제 #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityScanResult"/> class.
 /// </summary>
 /// <param name="entityReference">
 /// The entity reference.
 /// </param>
 internal EntityScanResult(EntityReference entityReference)
     : base(entityReference, null)
 {
     this.collection = new ChunkedCollection<object>();
     this.valueSink = v =>
         {
             lock (this.collection.SyncRoot)
             {
                 this.collection.Add(v);
             }
         };
 }
예제 #22
0
        public MacQueryTests()
        {
            _given = () =>
                     	{
                     		companyA = new EntityReference("companies/123", "CompanyDescription");
                     		companyAChart = new Chart() {Company = companyA};
                     		companyB = new EntityReference("companies/456", "CompanyDescription");
                     		companyBChart = new Chart() {Company = companyB};

                     		_session.Store(companyAChart);
                     		_session.Store(companyBChart);
                     	};
        }
예제 #23
0
        public void AddRulesFromUser(Entity sourceUser, List<Entity> users, BackgroundWorker worker = null)
        {
            // Retrieving user filter metadata
            var emd = (RetrieveEntityResponse)
                service.Execute(new RetrieveEntityRequest
                {
                    EntityFilters = EntityFilters.Attributes,
                    LogicalName = "userquery"
                });

            if (worker != null && worker.WorkerReportsProgress)
            {
                worker.ReportProgress(0, "Loading source user synchronization filters...");
            }

            // Retrieve filters for source user
            var rules = GetRules(new[] { 16, 256 }, new List<Entity> { new Entity("systemuser") { Id = sourceUser.Id } });

            foreach (var targetUser in users)
            {
                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Removing filters from user " + targetUser.GetAttributeValue<string>("fullname") + "...");
                }

                // Remove existing rules
                RemoveAllRulesForUser(targetUser.Id);

                //ApplyRulesToUser(new EntityReferenceCollection(rules.Entities.Where(e=>e.GetAttributeValue<EntityReference>("parentqueryid") != null).Select(e=>e.GetAttributeValue<EntityReference>("parentqueryid")).ToList()), targetUserId);

                if (worker != null && worker.WorkerReportsProgress)
                {
                    worker.ReportProgress(0, "Adding filters to user " + targetUser.GetAttributeValue<string>("fullname") + "...");
                }

                // Add source rules to target user
                foreach (var rule in rules.Entities)
                {
                    rule.Id = Guid.Empty;
                    rule.Attributes.Remove("userqueryid");
                    rule["ownerid"] = new EntityReference("systemuser", targetUser.Id);
                    foreach (var amd in emd.EntityMetadata.Attributes.Where(a => a.IsValidForCreate.Value == false))
                    {
                        rule.Attributes.Remove(amd.LogicalName);
                    }

                    service.Create(rule);
                }
            }
        }
        public void EntityReference_Constructor_Has_Correctly_Initialized_State()
        {
            // Arrange
            const string id = "abc/123";
            const string description = "entityDescription";
            // Act
            EntityReference entityReference = new EntityReference(id, description);

            // Assert
            entityReference.ShouldBeEquivalentTo(new
                                        {
                                            Id = id,
                                            Description = description,
                                        });
        }
        protected DocModel Loadhelper()
        {
            DocModel doc = new DocModel();
            doc.Subject = _subject;
            doc.EntityName = _target.LogicalName;
            var preImage = LoadPreImage();
            var ownerid = new EntityReference();

            if (preImage != null && preImage.GetAttributeValue<EntityReference>("ownerid") != null)
                doc.OwnerId = preImage.GetAttributeValue<EntityReference>("ownerid");
            if (_target != null && _target.GetAttributeValue<EntityReference>("ownerid") != null)
                doc.OwnerId = _target.GetAttributeValue<EntityReference>("ownerid");
            doc.RegardingId = _target.ToEntityReference();

            return doc;
        }
예제 #26
0
        public static MsCrmResultObject GetArticleCategoryInfo(Guid categoryId, SqlDataAccess sda)
        {
            MsCrmResultObject returnValue = new MsCrmResultObject();
            try
            {
                #region | SQL QUERY |
                string query = @"SELECT DISTINCT
                                    E.new_articlecategoryId AS Id
                                    ,E.new_name Name
                                    ,E.new_portalId PortalId
                                    ,E.new_portalIdName PortalIdName
                                    ,E.new_imageurl AS ImageUrl
                                FROM
                                new_articlecategory AS E (NOLOCK)
                                WHERE
                                    E.new_articlecategoryId = '{0}'
                                    AND
                                    E.statuscode=1 --Active";
                #endregion

                DataTable dt = sda.getDataTable(string.Format(query, categoryId));
                if (dt != null && dt.Rows.Count > 0)
                {
                    EntityReference er = new EntityReference()
                    {
                        Id = (Guid)dt.Rows[0]["Id"],
                        Name = dt.Rows[0]["Name"].ToString(),
                        LogicalName = dt.Rows[0]["ImageUrl"] != DBNull.Value ? dt.Rows[0]["ImageUrl"].ToString() : "no_image_available.png"
                    };

                    returnValue.Success = true;
                    returnValue.ReturnObject = er;
                }
                else
                {
                    returnValue.Success = false;
                    returnValue.Result = "M024";
                }
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result = ex.Message;
            }
            return returnValue;
        }
예제 #27
0
 public static void MapCuenta(
     CajaDeAhorro sqlCuenta, 
     string nroCuenta, 
     EntityReference modulo,
     EntityReference moneda,
     EntityReference sucursal,
     //EntityReference operacion,
     EntityReference tipoOperacion,
     EntityReference canalVenta,
     EntityReference estadoCuenta, 
     bsv_cuentas crmCuenta)
 {
     crmCuenta.bsv_cuenta_empresa = sqlCuenta. EmpresaId ? 1: 0;
     crmCuenta.bsv_numero_de_cuenta = nroCuenta;
     crmCuenta.bsv_operacion_mdoulo = modulo;
     crmCuenta.bsv_operacion_moneda = moneda;
     crmCuenta.bsv_operacion_papel= sqlCuenta.PapelId;
     crmCuenta.bsv_operacion_sucursal = sucursal;
     crmCuenta.bsv_operacion_operacion = sqlCuenta.Operacion;
     crmCuenta.bsv_operacion_suboperacion = sqlCuenta. SubOperacion;
     crmCuenta.bsv_operacion_tipo_operacion = tipoOperacion;
     //crmCuenta.bsv_ = sqlCuenta. PaisId;
     //crmCuenta.bsv_ = sqlCuenta. TipoDocumentoId;
     //crmCuenta.bsv_ = sqlCuenta. NumeroDocumento;
     crmCuenta.bsv_canal_venta = canalVenta;
     //crmCuenta.bsv_ = sqlCuenta. OficialId;
     //crmCuenta.bsv_ = sqlCuenta. TipoCuenta;
     crmCuenta.bsv_estado_cuenta = estadoCuenta;
     //crmCuenta.bsv_embargos = sqlCuenta.Embargos;
     crmCuenta.bsv_cbu = sqlCuenta. Cbu;
     //crmCuenta.bsv_ = sqlCuenta. CodigoProducto;
     //crmCuenta.bsv_pa = sqlCuenta. PaqueteId;
     //crmCuenta.bsv_resumen_online = sqlCuenta. MarcaResumenOnline;
     //crmCuenta.bsv_tarjeta_de_debito_relacionada = sqlCuenta. TarjetaDebitoRelacionada;
     crmCuenta.bsv_plan_sueldo = sqlCuenta. PlanSueldo;
     //crmCuenta.bsv_bonificacion = sqlCuenta. Bonificacion;
     //crmCuenta.bsv_ = sqlCuenta. CodigoPromocion;
     crmCuenta.bsv_convenio = sqlCuenta. Convenio.ToString();
     //crmCuenta.bsv_tenencia_debitos_en_cuenta = sqlCuenta. TenenciaDebitoCuenta;
     crmCuenta.bsv_cantidad_debitos_en_cuenta = sqlCuenta. CantidadDebitoCuenta;
     //crmCuenta.bsv_mora = sqlCuenta. Mora;
     //crmCuenta.bsv_fecha_saldo_deudor = sqlCuenta. FechaSaldoDeudor;
     crmCuenta.bsv_tasa_interes_asociada = sqlCuenta. TasaInteresAsociada;
     //crmCuenta.bsv_comisionada = sqlCuenta. Comisionada;
     //crmCuenta.bsv_sobregiro = sqlCuenta. Sobregiro;
 }
예제 #28
0
        public void AssignBusinessUnit(EntityReference userToChange, EntityReference userToCopy)
        {
            Entity userToCopy_ent = service.Retrieve("systemuser", userToCopy.Id, new ColumnSet("businessunitid"));

            // Create the request object.
            SetBusinessSystemUserRequest user = new SetBusinessSystemUserRequest();

            // Set the properties of the request object.
            user.BusinessId = ((EntityReference)userToCopy_ent.Attributes["businessunitid"]).Id;
            //SecurityPrincipal assignee = new SecurityPrincipal();
            //assignee.PrincipalId = new Guid("59727AF6-09A0-DB11-BEB5-0013727B635D");
            user.ReassignPrincipal = new EntityReference("systemuser", new Guid("5CDD7FF1-CD73-E611-A14E-EACD0C285D01"));
            user.UserId = userToChange.Id;

            // Execute the request.
            SetBusinessSystemUserResponse assigned = (SetBusinessSystemUserResponse)service.Execute(user);
        }
예제 #29
0
        public void AddRemarksForEntry(Guid entryID,  Annotation data, string Username, string Password)
        {
            Entity note = new Entity("annotation");

            note["objectid"] = new EntityReference("gsc_timeentry", entryID);
            note["subject"] = data.Subject;
            note["notetext"] = data.NoteText;

            string Url = ConfigurationManager.AppSettings["Url"].ToString();
            string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2}",
                                                        Url, Username, Password);
            CrmConnection crmConnection = null;
            crmConnection = CrmConnection.Parse(CrmConnectionString);
            OrganizationService service = new OrganizationService(crmConnection);

            service.Create(note);
        }
예제 #30
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            //Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // Create a column set to define which attributes should be retrieved.
            ColumnSet attributes = new ColumnSet(true);

            Entity currentPriceLevelEntity = new Entity("pricelevel");
            currentPriceLevelEntity = service.Retrieve("pricelevel", CurrentPriceList.Get<EntityReference>(executionContext).Id, attributes);

            // Create New Price List
            Entity newPriceLevel = new Entity("pricelevel");
            newPriceLevel["name"] = NewPriceListName.Get<string>(executionContext);
            newPriceLevel["begindate"] = NewPriceListStartDate.Get<DateTime>(executionContext);
            newPriceLevel["enddate"] = NewPriceListEndDate.Get<DateTime>(executionContext);
            newPriceLevel["transactioncurrencyid"] = currentPriceLevelEntity["transactioncurrencyid"];
            Guid newPriceLevelId = service.Create(newPriceLevel);

            // Get current product price level
            QueryExpression productPriceLevelExpression = new QueryExpression("productpricelevel");

            FilterExpression productPriceLevelFilterExpression = new FilterExpression();
            productPriceLevelFilterExpression.Conditions.Add(new ConditionExpression("pricelevelid", ConditionOperator.Equal, currentPriceLevelEntity["pricelevelid"]));

            productPriceLevelExpression.ColumnSet = new ColumnSet(true);
            productPriceLevelExpression.Criteria = productPriceLevelFilterExpression;

            EntityCollection productPriceLevelList = service.RetrieveMultiple(productPriceLevelExpression);

            // Create new product price level records
            for (int index = 0; productPriceLevelList.Entities != null && index < productPriceLevelList.Entities.Count; index++)
            {
                Entity newProductPriceLevelEntity = new Entity("productpricelevel");
                newProductPriceLevelEntity["pricelevelid"] = new EntityReference("pricelevel", newPriceLevelId);
                newProductPriceLevelEntity["productid"] = productPriceLevelList.Entities[index]["productid"];
                newProductPriceLevelEntity["uomid"] = productPriceLevelList.Entities[index]["uomid"];
                newProductPriceLevelEntity["amount"] = productPriceLevelList.Entities[index]["amount"];
                service.Create(newProductPriceLevelEntity);
            }
        }
예제 #31
0
 public List <EntityReference> GetChildrenList(EntityReference reference)
 {
     return(GetChildrenList(reference.Id));
 }
예제 #32
0
 public Entity GetEntity(EntityReference reference)
 {
     return(GetEntity(reference.Id));
 }
예제 #33
0
        private string CreateContract(string CustomerNo, string NationalityId, string HourlyPricingId, string CityId, bool Shift, string DistrictId, string SelectedDays, string ContractStartDate, string lat, string lang, string MonthsCount, int VisitCount, string TotalPrice, int HoursCount, string Discount, string MonthelyPrice, int who = 1)
        {
            //Random generator = new Random();
            String r = new Random().Next(0, 1000000).ToString("D6");


            ContractStartDate = ContractStartDate.Replace('/', '-');



            Entity contract = new Entity("new_hindvcontract");

            contract["new_hindivclintname"] = new EntityReference("contact", new Guid(CustomerNo.ToString()));
            contract["new_nationality"]     = new EntityReference("new_country", new Guid(NationalityId));
            contract["new_houlrypricing"]   = new EntityReference("new_hourlypricing", new Guid(HourlyPricingId));
            Entity hourlyPricing = GlobalCode.Service.Retrieve("new_hourlypricing", new Guid(HourlyPricingId), new ColumnSet(true));

            contract["new_visitprice_def"]  = int.Parse(MathNumber.RoundDeciamlToInt(hourlyPricing["new_hourprice"].ToString())) * HoursCount;
            contract["new_visittotalprice"] = Decimal.Parse(hourlyPricing["new_hourprice"].ToString()) * HoursCount;
            int months = int.Parse(MonthsCount);

            contract["new_visitcount_def"] = SelectedDays.Split(',').Count();

            contract["new_monthvisits_def"] = VisitCount;
            if (months != 0)
            {
                contract["new_monthvisits_def"] = (VisitCount * 4);
            }



            if (months != 0)
            {
                contract["new_contractmonth"] = months;
            }
            //else
            // contract["new_contractmonth"] = 13;
            contract["new_totalvisits_def"] = VisitCount;
            if (months != 0)
            {
                contract["new_totalvisits_def"] = VisitCount * 4 * months;
            }
            //hourlyPricing["new_totalvisits"];
            if (who == 1)
            {
                contract["new_contractsource"] = new OptionSetValue(who);
            }
            else
            {
                contract["new_contractsource"] = new OptionSetValue(2);
            }


            contract["new_hindivcount"] = HoursCount;

            contract["new_contractmonth"] = new OptionSetValue(months);


            contract["new_weeklyvisits"] = new OptionSetValue(VisitCount);

            contract["new_discount_def"] = decimal.Parse(Discount);
            // Math.Round((decimal.Parse(a.TotalbeforeDiscount) - (decimal.Parse(a.TotalbeforeDiscount) * decimal.Parse(Discount) / 100)), 2, MidpointRounding.AwayFromZero).ToString().Replace(".00", "");

            contract["new_totalprice_def"]   = int.Parse(Math.Round(decimal.Parse(TotalPrice), 0, MidpointRounding.AwayFromZero).ToString());
            contract["new_new_contractdate"] = DateTime.Now;
            contract["new_city"]             = new EntityReference("new_city", new Guid(CityId));
            contract["new_district"]         = new EntityReference("new_district", new Guid(DistrictId));
            contract["new_shift"]            = Shift == true ? false : true;
            contract["new_contractconfirm"]  = false;
            contract["statuscode"]           = new OptionSetValue(100000004);



            contract["new_contractstartdate"] = DateTime.ParseExact(ContractStartDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            contract["new_customerdays"]      = SelectedDays;
            //  contract["new_selecteddays"] = SelectedDays;
            contract["new_latitude"]    = lat;
            contract["new_longitude"]   = lang;
            contract["new_paymentcode"] = r;
            contract["new_mapurl"]      = "http://maps.google.com/maps?q=" + lat + "," + lang + "&z=15";


            Guid contractId = GlobalCode.Service.Create(contract);



            if (!string.IsNullOrEmpty(contractId.ToString()))
            {
                //Send SMS To confirm

                try
                {
                    string contsql = @"
select new_HIndvContract.new_ContractNumber ,Contact.FirstName from new_HIndvContract,Contact
 where Contact.ContactId =new_HIndvContract.new_HIndivClintname and 
 new_HIndvContract.new_HIndvContractId='@id'";
                    contsql = contsql.Replace("@id", contractId.ToString());
                    System.Data.DataTable dtcontract = CRMAccessDB.SelectQ(contsql).Tables[0];


                    string Sql = @"select    MobilePhone,new_deviceid from Contact where  ContactId='@id'  ";

                    Sql = Sql.Replace("@id", CustomerNo);
                    System.Data.DataTable dt = CRMAccessDB.SelectQ(Sql).Tables[0];


                    //send Notification

                    string result = SendNotifications.SendNotify("," + CustomerNo, "عزيزى العميل /" + dtcontract.Rows[0]["FirstName"].ToString() + "   " + "شكرا لاختياركم شركة ناس سيتم التواصل معكم قريبا لتاكيد الموعد للعقد رقم " + dtcontract.Rows[0]["new_ContractNumber"].ToString());

                    string body = "عزيزى العميل /" + dtcontract.Rows[0]["FirstName"].ToString() + "   " + "شكرا لاختياركم شركة ناس سيتم التواصل معكم قريبا لتاكيد الموعد للعقد رقم " + dtcontract.Rows[0]["new_ContractNumber"].ToString();
                    AppleNotifications.SendPushNotification(dt.Rows[0]["new_deviceid"].ToString(), body, "شركة ناس للاستقدام");


                    //Send To SMS

                    /*  Entity SMS = new Entity("new_smsns");
                     * string UserName = ConfigurationManager.AppSettings["SMSUserName"];
                     * string SMSPassword = ConfigurationManager.AppSettings["SMSPassword"];
                     * string TagName = ConfigurationManager.AppSettings["TagName"];
                     * SMSRef.SMSServiceSoapClient sms = new SMSRef.SMSServiceSoapClient();
                     * string MobileNumber = dt.Rows[0][0].ToString();
                     * string Message = "https://nasmanpower.com/HourlyServiceContract/Maps.aspx?id=" + contractId + "  برجاء تاكيد الموقع باستخدام الرابط المرسل . شكرا لاستخدامكم شركة ناس   ";
                     * string res = sms.SendBulkSMS(UserName, SMSPassword, TagName, MobileNumber, Message);*/
                }
                catch (Exception)
                {
                    return(contractId.ToString());
                }
            }

            return(contractId.ToString());
        }
        public static void UpdateMultipleAttributes(this IOrganizationService service, EntityReference e, Dictionary <string, object> attributes)
        {
            //using this format rather than constructor for CRM2011 compatibility
            var entity = new Entity {
                LogicalName = e.LogicalName, Id = e.Id
            };

            foreach (var kvp in attributes)
            {
                entity[kvp.Key] = kvp.Value;
            }
            service.Update(entity);
        }
예제 #35
0
        /// <summary>
        /// Retrieves the active references from the provided property. This only includes those references currently active and not those in the data store.
        /// </summary>
        /// <param name="entity">The entity containing the property that the references are assigned to.</param>
        /// <param name="propertyName">The name of the property that the references are assigned to.</param>
        /// <param name="returnType">The type of the property that the references are assigned to.</param>
        /// /// <param name="autoBind">A value indicating whether to bind the reference objects to the data store ready for updating.</param>
        /// <returns>A collection of the entity references.</returns>
        public virtual EntityReferenceCollection GetActiveReferences(IEntity entity, string propertyName, Type returnType, bool autoBind)
        {
            EntityReferenceCollection collection = new EntityReferenceCollection(entity);

            using (LogGroup logGroup = LogGroup.Start("Retrieving the reference entities from the specified property on the provided entity.", LogLevel.Debug))
            {
                Type entityType = entity.GetType();

                PropertyInfo property = EntitiesUtilities.GetProperty(entityType, propertyName, returnType);

                if (property == null)
                {
                    LogWriter.Debug("Property: [null]");
                }
                else
                {
                    LogWriter.Debug("Property name: " + property.Name);
                }

                if (property != null)
                {
                    if (EntitiesUtilities.IsReference(entityType, propertyName, returnType))
                    {
                        Type referencedEntityType = EntitiesUtilities.GetReferenceType(entity, propertyName, returnType);

                        string mirrorPropertyName = EntitiesUtilities.GetMirrorPropertyName(entity, property);

                        if (EntitiesUtilities.IsMultipleReference(entity.GetType(), property))
                        {
                            foreach (EntityReference r in GetActiveReferencesFromMultipleReferenceProperty(entity, property, mirrorPropertyName))
                            {
                                if (r != null)
                                {
                                    collection.Add(r);
                                }
                            }
                        }
                        else if (EntitiesUtilities.IsSingleReference(entityType, property))
                        {
                            EntityReference r = GetActiveReferenceFromSingleReferenceProperty(entity, property, mirrorPropertyName);
                            if (r != null)
                            {
                                collection.Add(r);
                            }
                        }
                        else
                        {
                            throw new NotSupportedException("The property type '" + property.PropertyType.ToString() + "' is not supported.");
                        }
                    }
                    else
                    {
                        throw new ArgumentException("The specified property is not a reference.");
                    }

                    LogWriter.Debug("References found: " + collection.Count.ToString());
                }
                else
                {
                    throw new Exception("Cannot find property '" + propertyName + "' on type '" + entity.GetType().ToString() + "'.");
                }

                // Assign the provided entity to each reference so it doesn't need to be loaded again
                foreach (EntityReference reference in collection)
                {
                    if (reference.Entity1ID == entity.ID)
                    {
                        reference.SourceEntity = entity;
                    }
                    else if (reference.Entity2ID == entity.ID)
                    {
                        reference.ReferenceEntity = entity;
                    }
                }

                if (autoBind)
                {
                    BindReferences(collection);
                }
            }

            return(collection);
        }
예제 #36
0
 public static void NotExists(IOrganizationService service, EntityReference entityReference)
 {
     NotExists(service, entityReference, null, null);
 }
예제 #37
0
        //Created By : Jerome Anthony Gerero, Created On : 8/25/2016
        //Modified By : Jessica Casupanan, Modified On : 01/09/2017

        /*Purpose: Create new allocated vehicle record
         * Registration Details:
         * Event/Message:
         *      Pre/Create:
         *      Post/Update: Inventory Id to Allocate = gsc_inventoryidtoallocate
         *      Post/Create:
         * Primary Entity: Vehicle Adjustment/Variance Entry
         */
        public Entity CreateVehicleAdjustmentVarianceEntryDetailRecord(Entity vehicleAdjustmentVarianceEntryEntity)
        {
            _tracingService.Trace("Started CreateVehicleAdjustmentVarianceEntryDetailRecord Method...");

            //Return if Inventory ID to Allocate is null
            if (vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") == null)
            {
                _tracingService.Trace("Inventory ID to Allocate is null.. exiting.");
                return(null);
            }

            Guid inventoryId = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") != null
                ? new Guid(vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate"))
                : Guid.Empty;

            EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending,
                                                                                        new[] { "gsc_status", "gsc_color", "gsc_csno", "gsc_engineno", "gsc_modelcode", "gsc_modelyear", "gsc_optioncode", "gsc_productionno", "gsc_vin", "gsc_productquantityid", "gsc_siteid", "gsc_productid", "gsc_basemodelid" });

            if (inventoryRecords != null && inventoryRecords.Entities.Count > 0)
            {
                Entity inventory = inventoryRecords.Entities[0];

                if (!inventory.FormattedValues["gsc_status"].Equals("Available"))
                {
                    throw new InvalidPluginExecutionException("The inventory for entered vehicle is not available.");
                }

                Entity vehicleAdjustmentVarianceEntryDetail = new Entity("gsc_sls_adjustmentvariancedetail");

                vehicleAdjustmentVarianceEntryDetail["gsc_vehicleadjustmentvarianceentryid"] = new EntityReference(vehicleAdjustmentVarianceEntryEntity.LogicalName, vehicleAdjustmentVarianceEntryEntity.Id);
                vehicleAdjustmentVarianceEntryDetail["gsc_inventoryid"] = new EntityReference(inventory.LogicalName, inventory.Id);
                vehicleAdjustmentVarianceEntryDetail["gsc_modelcode"]   = inventory.Contains("gsc_modelcode")
                    ? inventory.GetAttributeValue <String>("gsc_modelcode")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_modelyear"] = inventory.Contains("gsc_modelyear")
                    ? inventory.GetAttributeValue <String>("gsc_modelyear")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_optioncode"] = inventory.Contains("gsc_optioncode")
                    ? inventory.GetAttributeValue <String>("gsc_optioncode")
                    : String.Empty;
                String color = inventory.Contains("gsc_color")
                    ? inventory.GetAttributeValue <String>("gsc_color")
                    : String.Empty;

                //Retrieve Vehicle Color
                EntityCollection vehicleColorRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_cmn_vehiclecolor", "gsc_vehiclecolorpn", color, _organizationService, null, OrderType.Ascending,
                                                                                               new[] { "gsc_cmn_vehiclecolorid" });

                if (vehicleColorRecords != null && vehicleColorRecords.Entities.Count > 0)
                {
                    Entity vehicleColor = vehicleColorRecords.Entities[0];

                    vehicleAdjustmentVarianceEntryDetail["gsc_vehiclecolorid"] = new EntityReference(vehicleColor.LogicalName, vehicleColor.Id);
                }

                vehicleAdjustmentVarianceEntryDetail["gsc_csno"] = inventory.Contains("gsc_csno")
                    ? inventory.GetAttributeValue <String>("gsc_csno")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_vin"] = inventory.Contains("gsc_vin")
                    ? inventory.GetAttributeValue <String>("gsc_vin")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_productionno"] = inventory.Contains("gsc_productionno")
                    ? inventory.GetAttributeValue <String>("gsc_productionno")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_engineno"] = inventory.Contains("gsc_engineno")
                    ? inventory.GetAttributeValue <String>("gsc_engineno")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetail["gsc_quantity"]      = -1;
                vehicleAdjustmentVarianceEntryDetail["gsc_operation"]     = new OptionSetValue(100000001);
                vehicleAdjustmentVarianceEntryDetail["gsc_recordownerid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid") != null
                    ? new EntityReference("contact", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid").Id)
                    : null;
                vehicleAdjustmentVarianceEntryDetail["gsc_dealerid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid") != null
                    ? new EntityReference("account", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid").Id)
                    : null;
                vehicleAdjustmentVarianceEntryDetail["gsc_branchid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid") != null
                    ? new EntityReference("account", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid").Id)
                    : null;

                Guid productQuantityId = inventory.Contains("gsc_productquantityid")
                    ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id
                    : Guid.Empty;

                //Retrieve Product Quantity record for additional fields
                EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending,
                                                                                                  new[] { "gsc_siteid", "gsc_productid", "gsc_vehiclemodelid", "gsc_allocated", "gsc_available", "gsc_vehiclemodelid" });

                Entity productQuantity = new Entity("gsc_iv_productquantity");
                if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0)
                {
                    productQuantity = productQuantityRecords.Entities[0];

                    vehicleAdjustmentVarianceEntryDetail["gsc_vehiclebasemodelid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_vehiclemodelid") != null
                        ? new EntityReference("gsc_iv_vehiclebasemodel", productQuantity.GetAttributeValue <EntityReference>("gsc_vehiclemodelid").Id)
                        : null;
                    vehicleAdjustmentVarianceEntryDetail["gsc_productid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_productid") != null
                        ? new EntityReference("product", productQuantity.GetAttributeValue <EntityReference>("gsc_productid").Id)
                        : null;
                    vehicleAdjustmentVarianceEntryDetail["gsc_siteid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_siteid") != null
                        ? new EntityReference("gsc_iv_site", productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id)
                        : null;

                    Int32 allocatedCount = productQuantity.Contains("gsc_allocated")
                        ? productQuantity.GetAttributeValue <Int32>("gsc_allocated")
                        : 0;
                    Int32 availableCount = productQuantity.Contains("gsc_available")
                        ? productQuantity.GetAttributeValue <Int32>("gsc_available")
                        : 1;

                    productQuantity["gsc_allocated"] = allocatedCount + 1;

                    if (availableCount != 0)
                    {
                        productQuantity["gsc_available"] = availableCount - 1;
                    }

                    // throw new InvalidPluginExecutionException("test" + (allocatedCount + 1).ToString() + " " + (availableCount - 1).ToString());
                    _organizationService.Update(productQuantity);
                }

                _organizationService.Create(vehicleAdjustmentVarianceEntryDetail);

                //Set Inventory status to 'Allocated'
                inventory["gsc_status"] = new OptionSetValue(100000001);

                _organizationService.Update(inventory);

                InventoryMovementHandler inventoryMovement = new InventoryMovementHandler(_organizationService, _tracingService);
                inventoryMovement.CreateInventoryQuantityAllocated(vehicleAdjustmentVarianceEntryEntity, inventory, productQuantity, vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"),
                                                                   DateTime.UtcNow, vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"], Guid.Empty, 100000001);
            }

            //Clear Inventory ID to Allocate field
            vehicleAdjustmentVarianceEntryEntity["gsc_inventoryidtoallocate"] = String.Empty;
            _organizationService.Update(vehicleAdjustmentVarianceEntryEntity);

            _tracingService.Trace("Ended CreateVehicleAdjustmentVarianceEntryDetailRecord Method...");



            return(vehicleAdjustmentVarianceEntryEntity);
        }
예제 #38
0
 internal OrganizationResponse Execute(OrganizationRequest request, EntityReference userRef, PluginContext pluginContext)
 {
     return(Core.Execute(request, userRef, pluginContext));
 }
예제 #39
0
 public static IRecordPointer <Guid> ToRecordPointer(this EntityReference entityReference)
 {
     return(new RecordPointer <Guid>(
                entityReference.LogicalName,
                entityReference.Id));
 }
 private static bool HasLogicalName(this EntityReference entityReference, params string[] expectedLogicalName)
 {
     return(entityReference != null && expectedLogicalName.Contains(entityReference.LogicalName));
 }
예제 #41
0
 public void NotExists(EntityReference entityReference, string message, params object[] parameters)
 {
     NotExists(Service, entityReference, message, parameters);
 }
예제 #42
0
 public static void NotExists(IOrganizationService service, EntityReference entityReference, string message)
 {
     NotExists(service, entityReference, message, null);
 }
        public static RemoveUserFromRecordTeamResponse RemoveUserFromAccessTeam(this IOrganizationService service, EntityReference record, Guid userId, Guid teamTemplateId, ITracingService trace = null)
        {
            RemoveUserFromRecordTeamRequest teamAddRequest = new RemoveUserFromRecordTeamRequest();

            teamAddRequest.Record         = record;
            teamAddRequest.SystemUserId   = userId;
            teamAddRequest.TeamTemplateId = teamTemplateId;
            return((RemoveUserFromRecordTeamResponse)service.Execute(teamAddRequest));
        }
예제 #44
0
 private void OnPlaceChanged(EntityReference oldValue, EntityReference newValue)
 {
     // синхронизируем с местом
     PlaceCode = newValue != null ? (string)newValue.Id : null;
 }
예제 #45
0
        public void CreateOrUpdateRecovery(Guid createdClaimId, Entity policy)
        {
            try
            {
                ThrowIf.Argument.IsNull(svc, "svc");
                ThrowIf.Argument.IsNull(createdClaimId, "createdClaimId");

                Entity claimRecovery = new Entity("new_claimrecovery");

                var retreievedRecoveryOrder = mappedRow.Attributes.ForClaimOrder(claimOrder)
                                              .Where(c => c.TemplateColumn.ClaimRecoveryOrder != null)
                                              .Select(c => c.TemplateColumn.ClaimRecoveryOrder)
                                              .Distinct();

                foreach (var recoveryOrder in retreievedRecoveryOrder)
                {
                    var recoveryFields = mappedRow.Attributes.ForEntity("new_claimrecovery").ForClaimOrder(claimOrder).ForRecoveryOrder(recoveryOrder);

                    if (recoveryFields.Count() == 0)
                    {
                        return;
                    }

                    var recoveryAmount = recoveryFields.ForAttribute("new_recoveryamount").FirstOrDefault().AsDecimal(); //.Where(c => c.AttributeName == "new_recoveryamount").FirstOrDefault().ConvertedValue;

                    if (recoveryAmount != null && recoveryAmount > 0)
                    {
                        if (recoveryFields.Where(c => c.AttributeName == "new_recoverymethod").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoverymethod"] = recoveryFields.Where(c => c.AttributeName == "new_recoverymethod").Select(c => c.ConvertedValue).FirstOrDefault();
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoverytype").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoverytype"] = recoveryFields.Where(c => c.AttributeName == "new_recoverytype").Select(c => c.ConvertedValue).FirstOrDefault();
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoveryclass").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoveryclass"] = recoveryFields.Where(c => c.AttributeName == "new_recoveryclass").Select(c => c.ConvertedValue).FirstOrDefault();
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoveryamount").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoveryamount"] = recoveryFields.Where(c => c.AttributeName == "new_recoveryamount").FirstOrDefault().ConvertedValue;
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoverydate").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoverydate"] = recoveryFields.Where(c => c.AttributeName == "new_recoverydate").FirstOrDefault().ConvertedValue;
                        }
                        else
                        {
                            claimRecovery["new_recoverydate"] = DateTime.Now;
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoveryreference").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoveryreference"] = recoveryFields.Where(c => c.AttributeName == "new_recoveryreference").FirstOrDefault().ConvertedValue;
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoveryissuingcontact").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoveryissuingcontact"] = recoveryFields.Where(c => c.AttributeName == "new_recoveryissuingcontact").FirstOrDefault().ConvertedValue;
                        }
                        else
                        {
                            claimRecovery["new_recoveryissuingcontact"] = policy.GetAttributeValue <EntityReference>("new_contact");
                        }

                        if (recoveryFields.Where(c => c.AttributeName == "new_recoveryfromcompany").Select(c => c.ConvertedValue).FirstOrDefault() != null)
                        {
                            claimRecovery["new_recoveryfromcompany"] = recoveryFields.Where(c => c.AttributeName == "new_recoveryfromcompany").FirstOrDefault().ConvertedValue;
                        }
                        else
                        {
                            claimRecovery["new_recoveryfromcompany"] = policy.GetAttributeValue <EntityReference>("new_broker");
                        }

                        claimRecovery["new_claim"] = new EntityReference("new_claim", createdClaimId);

                        var createdClaimRecoveryId = svc.Create(claimRecovery);

                        if (createdClaimRecoveryId != null)
                        {
                            var recoveryContact = mappedRow.Attributes.ForClaimOrder(claimOrder).ForRecoveryOrder(recoveryOrder);
                            CreateOrUpdatePartyRecipient(recoveryContact, svc.Retrieve("new_claimrecovery", createdClaimRecoveryId, new ColumnSet(true)));
                        }
                    }
                }

                //return svc.Retrieve("new_claimrecovery", createdClaimRecoveryId, new ColumnSet(true));
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("ClaimRecovery Class", new Exception(ex.Message));
            }
        }
예제 #46
0
 public void NotExists(EntityReference entityReference)
 {
     NotExists(Service, entityReference);
 }
예제 #47
0
        //Created By : Jerome Anthony Gerero, Created On : 9/2/2016
        //Modified By : Jessica Casupanan, Modified On : 01/10/2017

        /*Purpose: Update Inventory record fields on Vehicle Adjustment/Variance Entry 'Posted' status
         * Registration Details:
         * Event/Message:
         *      Pre-Validate/Delete:
         *      Post/Update: gsc_adjustmentvariancestatus
         *      Post/Create:
         * Primary Entity: Vehicle Adjustment/Variance Entry Detail
         */
        public Entity PostVehicleAdjustmentVarianceEntry(Entity vehicleAdjustmentVarianceEntryEntity)
        {
            _tracingService.Trace("Started PostVehicleAdjustmentVarianceEntry Method...");

            if (!vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Posted"))
            {
                return(null);
            }

            String   transactionNumber = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_vehicleadjustmentvarianceentrypn") ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_vehicleadjustmentvarianceentrypn") : String.Empty;
            DateTime transactionDate   = DateTime.UtcNow;
            InventoryMovementHandler inventoryMovementHandler = new InventoryMovementHandler(_organizationService, _tracingService);

            _tracingService.Trace("Retrieve Vehicle Adjustment/Variance Entry Detail records");
            EntityCollection vehicleAdjustmentVarianceEntryDetailRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_adjustmentvariancedetail", "gsc_vehicleadjustmentvarianceentryid", vehicleAdjustmentVarianceEntryEntity.Id, _organizationService, null, OrderType.Ascending,
                                                                                                                   new[] { "gsc_vehiclebasemodelid", "gsc_vehiclecolorid", "gsc_csno", "gsc_engineno", "gsc_modelcode", "gsc_productid", "gsc_modelyear", "gsc_optioncode", "gsc_productionno", "gsc_siteid", "gsc_vin", "gsc_operation", "gsc_inventoryid", "statecode", "gsc_quantity" });

            if (vehicleAdjustmentVarianceEntryDetailRecords != null && vehicleAdjustmentVarianceEntryDetailRecords.Entities.Count > 0)
            {
                foreach (Entity vehicleAdjustmentVarianceEntryDetail in vehicleAdjustmentVarianceEntryDetailRecords.Entities)
                {
                    Int32 quantity = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_quantity")
                         ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <Int32>("gsc_quantity") : 0;

                    #region Subtract
                    if (vehicleAdjustmentVarianceEntryDetail.FormattedValues["gsc_operation"].Equals("Subtract"))
                    {
                        Guid inventoryId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid") != null
                           ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid").Id
                           : Guid.Empty;

                        _tracingService.Trace("Retrieve Inventory records using value from Inventory field");
                        EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending,
                                                                                                    new[] { "gsc_productquantityid", "gsc_optioncode", "gsc_productid", "gsc_modelcode", "gsc_modelyear", "gsc_siteid",
                                                                                                            "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno" });

                        if (inventoryRecords != null && inventoryRecords.Entities.Count > 0)
                        {
                            Entity inventory = inventoryRecords.Entities[0];

                            Guid productQuantityId = inventory.GetAttributeValue <EntityReference>("gsc_productquantityid") != null
                                ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id
                                : Guid.Empty;

                            _tracingService.Trace("Retrieve Product Quantity record using value from Product Quantity field");
                            EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending,
                                                                                                              new[] { "gsc_allocated", "gsc_onhand", "gsc_available", "gsc_siteid", "gsc_vehiclecolorid", "gsc_vehiclemodelid", "gsc_productid" });

                            if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0)
                            {
                                Entity productQuantity = productQuantityRecords.Entities[0];

                                Int32 allocatedCount = productQuantity.Contains("gsc_allocated")
                                    ? productQuantity.GetAttributeValue <Int32>("gsc_allocated")
                                    : 1;
                                Int32 availableCount = productQuantity.Contains("gsc_available")
                                    ? productQuantity.GetAttributeValue <Int32>("gsc_available")
                                    : 0;
                                Int32 onHandCount = productQuantity.Contains("gsc_onhand")
                                    ? productQuantity.GetAttributeValue <Int32>("gsc_onhand")
                                    : 1;

                                _tracingService.Trace("Adjust Allocated count");
                                if (allocatedCount != 0)
                                {
                                    productQuantity["gsc_allocated"] = allocatedCount - 1;
                                }
                                _tracingService.Trace("Adjust On Hand count");
                                if (onHandCount != 0)
                                {
                                    productQuantity["gsc_onhand"] = onHandCount - 1;
                                }

                                _organizationService.Update(productQuantity);
                                Guid fromSite = productQuantity.Contains("gsc_siteid") ? productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id : Guid.Empty;
                                inventoryMovementHandler.CreateInventoryHistory("Negative Adjustment", null, null, transactionNumber, transactionDate, 1, 0, onHandCount - 1, Guid.Empty, fromSite, fromSite, inventory, productQuantity, true, true);
                                inventoryMovementHandler.CreateInventoryQuantityAllocated(vehicleAdjustmentVarianceEntryEntity, inventory, productQuantity, vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"),
                                                                                          DateTime.UtcNow, "Posted", Guid.Empty, 100000008);

                                _tracingService.Trace("Deactivate record");
                                if (vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <OptionSetValue>("statecode").Value == 0)
                                {
                                    SetStateRequest setStateRequest = new SetStateRequest()
                                    {
                                        EntityMoniker = new EntityReference
                                        {
                                            Id          = inventory.Id,
                                            LogicalName = inventory.LogicalName,
                                        },
                                        State  = new OptionSetValue(1),
                                        Status = new OptionSetValue(2)
                                    };
                                    _organizationService.Execute(setStateRequest);
                                }
                            }
                        }
                    }
                    #endregion

                    #region Add
                    else if (vehicleAdjustmentVarianceEntryDetail.FormattedValues["gsc_operation"].Equals("Add"))
                    {
                        _tracingService.Trace("Get Vehicle Adjustment/Variance Entry Detail fields");
                        Guid vehicleBaseModelId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id
                            : Guid.Empty;

                        String color = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Name
                            : String.Empty;

                        Guid colorId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Id
                            : Guid.Empty;

                        String csNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_csno")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_csno")
                            : String.Empty;
                        String engineNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_engineno")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_engineno")
                            : String.Empty;
                        String modelCode = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_modelcode")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_modelcode")
                            : String.Empty;
                        Guid productId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid").Id
                            : Guid.Empty;

                        String productName = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid").Name
                            : String.Empty;

                        String modelYear = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_modelyear")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_modelyear")
                            : String.Empty;
                        String optionCode = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_optioncode")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_optioncode")
                            : String.Empty;
                        String productionNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_productionno")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_productionno")
                            : String.Empty;
                        Guid siteId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid").Id
                            : Guid.Empty;

                        String siteName = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid").Name
                            : String.Empty;

                        String vin = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_vin")
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_vin")
                            : String.Empty;

                        _tracingService.Trace("Create filter for Product in Product Relationship entity");
                        var productQuantityConditionList = new List <ConditionExpression>
                        {
                            new ConditionExpression("gsc_productid", ConditionOperator.Equal, productId),
                            new ConditionExpression("gsc_siteid", ConditionOperator.Equal, siteId),
                            new ConditionExpression("gsc_vehiclecolorid", ConditionOperator.Equal, colorId)
                        };

                        _tracingService.Trace("Retrieve Product Quantity records");
                        EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByConditions("gsc_iv_productquantity", productQuantityConditionList, _organizationService, null, OrderType.Ascending,
                                                                                                            new[] { "gsc_onhand", "gsc_available", "gsc_siteid", "gsc_vehiclecolorid", "gsc_vehiclemodelid", "gsc_productid", "gsc_allocated", "gsc_sold", "gsc_onorder" });

                        Entity productQuantity;
                        Entity inventory = new Entity("gsc_iv_inventory");

                        Int32 onHandCount = 0;
                        Int32 availableCount;

                        if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0)
                        {
                            _tracingService.Trace("Update existing product quantity record");
                            productQuantity = productQuantityRecords.Entities[0];

                            onHandCount = productQuantity.Contains("gsc_onhand")
                                ? productQuantity.GetAttributeValue <Int32>("gsc_onhand")
                                : 0;
                            availableCount = productQuantity.Contains("gsc_available")
                                ? productQuantity.GetAttributeValue <Int32>("gsc_available")
                                : 0;

                            _tracingService.Trace("Set product quantity count");
                            productQuantity["gsc_onhand"]    = onHandCount + 1;
                            productQuantity["gsc_available"] = availableCount + 1;

                            _organizationService.Update(productQuantity);

                            inventory["gsc_productquantityid"] = new EntityReference("gsc_iv_productquantity", productQuantity.Id);
                        }
                        else
                        {
                            _tracingService.Trace("Create new product quantity product");
                            productQuantity = new Entity("gsc_iv_productquantity");

                            _tracingService.Trace("Set product quantity count");
                            productQuantity["gsc_onhand"]    = 1;
                            productQuantity["gsc_available"] = 1;
                            productQuantity["gsc_allocated"] = 0;
                            productQuantity["gsc_sold"]      = 0;
                            productQuantity["gsc_onorder"]   = 0;

                            _tracingService.Trace("Set site field");
                            if (siteId != Guid.Empty)
                            {
                                productQuantity["gsc_siteid"] = new EntityReference("gsc_iv_site", siteId);
                            }
                            _tracingService.Trace("Set Vehicle Base Model field");
                            if (vehicleBaseModelId != Guid.Empty)
                            {
                                productQuantity["gsc_vehiclemodelid"] = new EntityReference("gsc_iv_vehiclebasemodel", vehicleBaseModelId);
                            }

                            if (colorId != Guid.Empty)
                            {
                                productQuantity["gsc_vehiclecolorid"] = new EntityReference("gsc_cmn_vehiclecolor", colorId);
                            }
                            _tracingService.Trace("Set Product Name field");
                            productQuantity["gsc_productid"]         = new EntityReference("product", productId);
                            productQuantity["gsc_productquantitypn"] = productName;
                            productQuantity["gsc_branchid"]          = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_branchid")
                            ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid")
                            : null;
                            productQuantity["gsc_dealerid"] = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_dealerid")
                                ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid")
                                : null;
                            productQuantity["gsc_recordownerid"] = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_recordownerid")
                                ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid")
                                : null;
                            Guid newProductQuantityId = _organizationService.Create(productQuantity);

                            inventory["gsc_productquantityid"] = new EntityReference("gsc_iv_productquantity", newProductQuantityId);
                        }

                        _tracingService.Trace("Create Inventory record");
                        inventory["gsc_inventorypn"]  = productName + "-" + siteName;
                        inventory["gsc_status"]       = new OptionSetValue(100000000);
                        inventory["gsc_color"]        = color;
                        inventory["gsc_engineno"]     = engineNo;
                        inventory["gsc_csno"]         = csNo;
                        inventory["gsc_productionno"] = productionNo;
                        inventory["gsc_vin"]          = vin;
                        inventory["gsc_modelcode"]    = modelCode;
                        inventory["gsc_optioncode"]   = optionCode;
                        inventory["gsc_modelyear"]    = modelYear;
                        inventory["gsc_siteid"]       = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null
                            ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid")
                            : null;

                        inventory["gsc_branchid"] = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_branchid")
                        ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid")
                        : null;
                        inventory["gsc_dealerid"] = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_dealerid")
                            ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid")
                            : null;
                        inventory["gsc_recordownerid"] = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_recordownerid")
                            ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid")
                            : null;

                        Guid             inventoryId      = _organizationService.Create(inventory);
                        EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending,
                                                                                                    new[] { "gsc_productquantityid", "gsc_modelcode", "gsc_optioncode", "gsc_productid", "gsc_modelyear", "gsc_siteid",
                                                                                                            "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno" });
                        if (inventoryRecords != null && inventoryRecords.Entities.Count > 0)
                        {
                            Entity inventoryE = inventoryRecords.Entities[0];
                            Guid   fromSite   = productQuantity.Contains("gsc_siteid") ? productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id : Guid.Empty;
                            inventoryMovementHandler.CreateInventoryHistory("Positive Adjustment", null, null, transactionNumber, transactionDate, 0, 1, onHandCount + 1, Guid.Empty, fromSite, fromSite, inventoryE, productQuantity, true, true);
                        }
                    }

                    #endregion
                }
            }

            _tracingService.Trace("Ended PostVehicleAdjustmentVarianceEntry Method...");
            return(vehicleAdjustmentVarianceEntryEntity);
        }
        public static void RevokeSharedAccess(this IOrganizationService service, EntityReference target, EntityReference revokee)
        {
            var revoke = new RevokeAccessRequest();

            revoke.Target  = target;
            revoke.Revokee = revokee;
            service.Execute(revoke);
        }
예제 #49
0
        protected virtual void SetEntityAttributes(Entity entity, IDictionary values)
        {
            var metadata = _crmDataContext.RetrieveEntity(entity.LogicalName, EntityFilters.Attributes);

            foreach (DictionaryEntry value in values)
            {
                var attributeName = value.Key.ToString().TrimStart('[').TrimEnd(']');

                if (string.Equals(attributeName, "EntityName", StringComparison.InvariantCulture))
                {
                    continue;
                }

                AttributeTypeCode?attributeType;
                try
                {
                    var attribute = metadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeName);

                    if (attribute == null)                     // ignore subgrid, iframe or web resources
                    {
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No value set. Key '{0}' is not a name of an attribute on entity type {1}. This is likely a subgrid, iframe, or web resource.", attributeName, entity.LogicalName);
                        continue;
                    }

                    attributeType = attribute.AttributeType;
                }
                catch (Exception)
                {
                    throw new Exception("{0} could not be found in entity type {1}".FormatWith(attributeName, entity.LogicalName));
                }

                if (!(value.Value is EntityReference) && (
                        attributeType == AttributeTypeCode.Customer ||
                        attributeType == AttributeTypeCode.Lookup ||
                        attributeType == AttributeTypeCode.Owner))
                {
                    Guid id;

                    if (value.Value == null)
                    {
                        entity.SetAttributeValue <EntityReference>(attributeName, null);

                        continue;
                    }

                    if (!Guid.TryParse(value.Value.ToString(), out id))
                    {
                        throw new ArgumentException("value is not of type Guid");
                    }

                    var entityReference = new EntityReference(entity.LogicalName, id);

                    entity.SetAttributeValue <EntityReference>(attributeName, entityReference);
                }
                else if (attributeType == AttributeTypeCode.Status)
                {
                    entity.SetAttributeValue <OptionSetValue>(attributeName, value.Value);
                }
                else if (attributeType == AttributeTypeCode.Picklist)
                {
                    // determine if a multiselect picklist values should be saved
                    var picklistvaluesfield = metadata.Attributes.FirstOrDefault(a => a.LogicalName == string.Format("{0}selectedvalues", attributeName));

                    if (picklistvaluesfield == null)
                    {
                        entity.SetAttributeValue <OptionSetValue>(attributeName, value.Value);
                    }
                    else
                    {
                        entity[picklistvaluesfield.LogicalName] = value.Value;
                    }
                }
                else if (attributeType == AttributeTypeCode.Money)
                {
                    entity.SetAttributeValue <Money>(attributeName, value.Value);
                }
                else
                {
                    entity[attributeName] = value.Value;
                }
            }
        }
예제 #50
0
        private Guid CreateCustomerIndividual(Entity prospectInquiryEntity)
        {
            _tracingService.Trace("Started CreateCustomerIndividual method...");

            Entity contact = new Entity("contact");

            contact["firstname"] = prospectInquiryEntity.Contains("firstname")
                ? prospectInquiryEntity.GetAttributeValue <String>("firstname")
                : null;
            contact["middlename"] = prospectInquiryEntity.Contains("middlename")
                ? prospectInquiryEntity.GetAttributeValue <String>("middlename")
                : null;
            contact["lastname"] = prospectInquiryEntity.Contains("lastname")
                ? prospectInquiryEntity.GetAttributeValue <String>("lastname")
                : null;
            contact["mobilephone"] = prospectInquiryEntity.Contains("mobilephone")
                ? prospectInquiryEntity.GetAttributeValue <String>("mobilephone")
                : null;
            contact["telephone1"] = prospectInquiryEntity.Contains("gsc_alternatecontactno")
                ? prospectInquiryEntity.GetAttributeValue <String>("gsc_alternatecontactno")
                : null;
            contact["fax"] = prospectInquiryEntity.Contains("fax")
                ? prospectInquiryEntity.GetAttributeValue <String>("fax")
                : null;
            contact["emailaddress1"] = prospectInquiryEntity.Contains("emailaddress1")
                ? prospectInquiryEntity.GetAttributeValue <String>("emailaddress1")
                : null;
            contact["gendercode"] = prospectInquiryEntity.Contains("gsc_gender")
                ? prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_gender")
                : null;
            contact["familystatuscode"] = prospectInquiryEntity.Contains("gsc_maritalstatus")
                ? prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_maritalstatus")
                : null;
            contact["birthdate"] = prospectInquiryEntity.Contains("gsc_birthday")
                ? prospectInquiryEntity.GetAttributeValue <DateTime>("gsc_birthday")
                : (DateTime?)null;
            contact["gsc_age"] = prospectInquiryEntity.Contains("gsc_age")
                ? Convert.ToInt32(prospectInquiryEntity.GetAttributeValue <String>("gsc_age"))
                : 0;
            contact["gsc_countryid"] = prospectInquiryEntity.Contains("gsc_countryid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_countryid")
                : null;
            contact["gsc_regionid"] = prospectInquiryEntity.Contains("gsc_regionid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_regionid")
                : null;
            contact["gsc_provinceid"] = prospectInquiryEntity.Contains("gsc_provinceid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_provinceid")
                : null;
            contact["gsc_cityid"] = prospectInquiryEntity.Contains("gsc_cityid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_cityid")
                : null;
            contact["address1_line1"] = prospectInquiryEntity.Contains("address1_line1")
                ? prospectInquiryEntity.GetAttributeValue <String>("address1_line1")
                : null;
            contact["address1_postalcode"] = prospectInquiryEntity.Contains("address1_postalcode")
                ? prospectInquiryEntity.GetAttributeValue <String>("address1_postalcode")
                : null;
            contact["gsc_salesexecutiveid"] = prospectInquiryEntity.Contains("gsc_salesexecutiveid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_salesexecutiveid")
                : null;
            contact["gsc_dealerid"] = prospectInquiryEntity.Contains("gsc_dealerid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_dealerid")
                : null;
            contact["gsc_branchid"] = prospectInquiryEntity.Contains("gsc_branchid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_branchid")
                : null;
            contact["gsc_recordownerid"] = prospectInquiryEntity.Contains("gsc_recordownerid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid")
                : null;
            contact["gsc_recordtype"]  = new OptionSetValue(100000001);
            contact["gsc_ispotential"] = true;
            contact["gsc_prospect"]    = true;
            Entity DefaultCustomerTax = GetDefaultTax();

            contact["gsc_taxid"] = new EntityReference(DefaultCustomerTax.LogicalName, DefaultCustomerTax.Id);
            contact["gsc_tin"]   = prospectInquiryEntity.Contains("gsc_tin")
               ? prospectInquiryEntity.GetAttributeValue <String>("gsc_tin")
               : String.Empty;

            _tracingService.Trace("Customer Record Created...");
            _tracingService.Trace("Ended CreateCustomerIndividual method...");

            var contactid = _organizationService.Create(contact);

            return(contactid);
        }
예제 #51
0
        internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request     = MakeRequest <RetrieveMultipleRequest>(orgRequest);
            var queryExpr   = request.Query as QueryExpression;
            var fetchExpr   = request.Query as FetchExpression;
            var queryByAttr = request.Query as QueryByAttribute;

            if (fetchExpr != null)
            {
                queryExpr = XmlHandling.FetchXmlToQueryExpression(fetchExpr.Query);
            }
            else if (queryByAttr != null)
            {
                queryExpr = Utility.QueryByAttributeToQueryExpression(queryByAttr);
            }

            if (queryExpr.EntityName == null)
            {
                throw new FaultException("The 'RetrieveMultiple' method does not support entities of type 'none'");
            }

            FillAliasIfEmpty(queryExpr);
            var collection = new EntityCollection();

            db.PrefillDBWithOnlineData(queryExpr);

            var linkEntities   = new Dictionary <string, IEnumerable <Entity> >();
            var linkToEntities = queryExpr.LinkEntities.GroupBy(x => x.LinkToEntityName);

            foreach (var linkToEntity in linkToEntities)
            {
                linkEntities.Add(linkToEntity.Key, db.GetEntities(linkToEntity.Key));
            }

            var rows = db.GetEntities(queryExpr.EntityName, queryExpr.Criteria.Conditions);


            foreach (var row in rows)
            {
                var entity = row;
                var toAdd  = core.GetStronglyTypedEntity(entity, core.GetEntityMetadata(queryExpr.EntityName), null);

                if (queryExpr.LinkEntities.Count > 0)
                {
                    foreach (var linkEntity in queryExpr.LinkEntities)
                    {
                        var alliasedValues = GetAliasedValuesFromLinkentity(linkEntity, entity, toAdd, db);
                        collection.Entities.AddRange(
                            alliasedValues
                            .Where(e => Utility.MatchesCriteria(e, queryExpr.Criteria)));
                    }
                }
                else if (Utility.MatchesCriteria(toAdd, queryExpr.Criteria))
                {
                    collection.Entities.Add(toAdd);
                }
            }
            var filteredEntities = new EntityCollection();

            filteredEntities.Entities.AddRange(collection.Entities.Where(e => security.HasPermission(e, AccessRights.ReadAccess, userRef)));

            var orders            = queryExpr.Orders;
            var orderedCollection = new EntityCollection();

            // TODO: Check the order that the orders are executed in is correct
            if (orders.Count > 2)
            {
                throw new MockupException("Number of orders are greater than 2, unsupported in crm");
            }
            else if (orders.Count == 1)
            {
                if (orders.First().OrderType == OrderType.Ascending)
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities.OrderBy(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName)));
                }
                else
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities.OrderByDescending(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName)));
                }
            }
            else if (orders.Count == 2)
            {
                if (orders[0].OrderType == OrderType.Ascending && orders[1].OrderType == OrderType.Ascending)
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities
                                                        .OrderBy(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName))
                                                        .ThenBy(x => Utility.GetComparableAttribute(x.Attributes, orders[1].AttributeName)));
                }

                else if (orders[0].OrderType == OrderType.Ascending && orders[1].OrderType == OrderType.Descending)
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities
                                                        .OrderBy(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName))
                                                        .ThenByDescending(x => Utility.GetComparableAttribute(x.Attributes, orders[1].AttributeName)));
                }

                else if (orders[0].OrderType == OrderType.Descending && orders[1].OrderType == OrderType.Ascending)
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities
                                                        .OrderByDescending(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName))
                                                        .ThenBy(x => Utility.GetComparableAttribute(x.Attributes, orders[1].AttributeName)));
                }

                else if (orders[0].OrderType == OrderType.Descending && orders[1].OrderType == OrderType.Descending)
                {
                    orderedCollection.Entities.AddRange(filteredEntities.Entities
                                                        .OrderByDescending(x => Utility.GetComparableAttribute(x.Attributes, orders[0].AttributeName))
                                                        .ThenByDescending(x => Utility.GetComparableAttribute(x.Attributes, orders[1].AttributeName)));
                }
            }

            var colToReturn = new EntityCollection();

            if (orderedCollection.Entities.Count != 0)
            {
                foreach (var entity in orderedCollection.Entities)
                {
                    KeepAttributesAndAliasAttributes(entity, queryExpr.ColumnSet);
                }
                colToReturn = orderedCollection;
            }
            else
            {
                foreach (var entity in filteredEntities.Entities)
                {
                    KeepAttributesAndAliasAttributes(entity, queryExpr.ColumnSet);
                }
                colToReturn = filteredEntities;
            }

#if !(XRM_MOCKUP_2011 || XRM_MOCKUP_2013)
            foreach (var enitity in colToReturn.Entities)
            {
                ExecuteCalculatedFields(enitity);
            }
#endif


            // According to docs, should return -1 if ReturnTotalRecordCount set to false
            colToReturn.TotalRecordCount = queryExpr.PageInfo.ReturnTotalRecordCount ? colToReturn.Entities.Count : -1;

            var resp = new RetrieveMultipleResponse();

            resp.Results["EntityCollection"] = colToReturn;
            return(resp);
        }
예제 #52
0
        private Guid CreateCorporateCustomer(Entity prospectInquiryEntity)
        {
            _tracingService.Trace("Started CreateCorporateCustomer method...");

            _tracingService.Trace("Creating Corporate Customer ...");
            Entity account = new Entity("account");

            account["gsc_customertype"] = prospectInquiryEntity.Contains("gsc_prospecttype")
                ? new OptionSetValue(prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_prospecttype").Value - 1)
                : null;
            account["gsc_firstname"] = prospectInquiryEntity.Contains("firstname")
                 ? prospectInquiryEntity.GetAttributeValue <String>("firstname")
                 : null;
            account["gsc_middlename"] = prospectInquiryEntity.Contains("middlename")
                ? prospectInquiryEntity.GetAttributeValue <String>("middlename")
                : null;
            account["gsc_lastname"] = prospectInquiryEntity.Contains("lastname")
                ? prospectInquiryEntity.GetAttributeValue <String>("lastname")
                : null;
            account["telephone2"] = prospectInquiryEntity.Contains("mobilephone")
                ? prospectInquiryEntity.GetAttributeValue <String>("mobilephone")
                : null;
            account["telephone3"] = prospectInquiryEntity.Contains("gsc_alternatecontactno")
                ? prospectInquiryEntity.GetAttributeValue <String>("gsc_alternatecontactno")
                : null;
            account["fax"] = prospectInquiryEntity.Contains("fax")
                ? prospectInquiryEntity.GetAttributeValue <String>("fax")
                : null;
            account["emailaddress1"] = prospectInquiryEntity.Contains("emailaddress1")
                ? prospectInquiryEntity.GetAttributeValue <String>("emailaddress1")
                : null;
            account["name"] = prospectInquiryEntity.Contains("companyname")
                ? prospectInquiryEntity.GetAttributeValue <String>("companyname")
                : null;
            account["telephone1"] = prospectInquiryEntity.Contains("telephone1")
                ? prospectInquiryEntity.GetAttributeValue <String>("telephone1")
                : null;
            account["fax"] = prospectInquiryEntity.Contains("fax")
                ? prospectInquiryEntity.GetAttributeValue <String>("fax")
                : null;
            account["websiteurl"] = prospectInquiryEntity.Contains("websiteurl")
                ? prospectInquiryEntity.GetAttributeValue <String>("websiteurl")
                : null;
            account["gsc_countryid"] = prospectInquiryEntity.Contains("gsc_countryid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_countryid")
                : null;
            account["gsc_regionid"] = prospectInquiryEntity.Contains("gsc_regionid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_regionid")
                : null;
            account["gsc_provinceid"] = prospectInquiryEntity.Contains("gsc_provinceid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_provinceid")
                : null;
            account["gsc_cityid"] = prospectInquiryEntity.Contains("gsc_cityid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_cityid")
                : null;
            account["address1_line1"] = prospectInquiryEntity.Contains("address1_line1")
                ? prospectInquiryEntity.GetAttributeValue <String>("address1_line1")
                : null;
            account["address1_postalcode"] = prospectInquiryEntity.Contains("address1_postalcode")
                ? prospectInquiryEntity.GetAttributeValue <String>("address1_postalcode")
                : null;
            account["gsc_salesexecutiveid"] = prospectInquiryEntity.Contains("gsc_salesexecutiveid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_salesexecutiveid")
                : null;
            account["gsc_dealerid"] = prospectInquiryEntity.Contains("gsc_dealerid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_dealerid")
                : null;
            account["gsc_branchid"] = prospectInquiryEntity.Contains("gsc_branchid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_branchid")
                : null;
            account["gsc_recordownerid"] = prospectInquiryEntity.Contains("gsc_recordownerid")
                ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid")
                : null;
            account["gsc_recordtype"]  = new OptionSetValue(100000003);
            account["gsc_ispotential"] = true;
            account["gsc_prospect"]    = true;
            account["gsc_tin"]         = prospectInquiryEntity.Contains("gsc_tin")
               ? prospectInquiryEntity.GetAttributeValue <String>("gsc_tin")
               : String.Empty;
            Entity DefaultCustomerTax = GetDefaultTax();

            account["gsc_taxid"] = new EntityReference(DefaultCustomerTax.LogicalName, DefaultCustomerTax.Id);

            var accountid = _organizationService.Create(account);

            _tracingService.Trace("Corporate Customer Created ...");
            _tracingService.Trace("Ended CreateCorporateCustomer method...");

            return(accountid);
        }
예제 #53
0
        /// <summary>
        /// Retrieves EntityId from the Context
        /// Create,Update,Delete,SetState,Assign,DeliverIncoming
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static Guid GetEntityId(IPluginExecutionContext context, IOrganizationService service)
        {
            switch (context.MessageName)
            {
            case MessageName.Create:
            case MessageName.DeliverIncoming:
                if (context.Stage == MessageProcessingStage.BeforeMainOperationOutsideTransaction)
                {
                    throw new InvalidPluginExecutionException("EntityId is not available in PreCreate");
                }
                else
                {
                    //CreateResponse r;
                    //r.id;
                    if (context.OutputParameters.Contains(ParameterName.Id))
                    {
                        return((Guid)context.OutputParameters[ParameterName.Id]);
                    }

                    //DeliverIncomingEmailResponse r;
                    //r.EmailId;
                    if (context.OutputParameters.Contains(ParameterName.EmailId))
                    {
                        return((Guid)context.OutputParameters[ParameterName.EmailId]);
                    }
                }
                break;

            case MessageName.Update:
                //context.InputParameters.Contains(ParameterName.Target)
                //IMetadataService metadataService = context.CreateMetadataService(false);

                RetrieveEntityRequest rar = new RetrieveEntityRequest();
                rar.LogicalName   = context.PrimaryEntityName;
                rar.EntityFilters = EntityFilters.Attributes;
                RetrieveEntityResponse resp = (RetrieveEntityResponse)service.Execute(rar);
                string keyName = resp.EntityMetadata.PrimaryIdAttribute;

                //UpdateRequest u;
                //TargetUpdateAccount a;
                //a.Account; // This s Dynamic entity
                //u.Target = a;

                // Update
                if (context.InputParameters[ParameterName.Target] is Entity)
                {
                    Guid key = (Guid)((Entity)context.InputParameters[ParameterName.Target]).Attributes[keyName];
                    return(key);
                }
                break;

            case MessageName.Delete:
            case MessageName.Assign:
            case MessageName.GrantAccess:
            case MessageName.Handle:
                if (context.InputParameters[ParameterName.Target] is EntityReference)
                {
                    EntityReference monikerId = (EntityReference)context.InputParameters[ParameterName.Target];
                    return(monikerId.Id);
                }
                break;

            case MessageName.SetState:
            case MessageName.SetStateDynamicEntity:
                //SetStateAccountRequest r;
                //r.EntityId; // Guid === Moniker
                //r.AccountState; // State
                //r.AccountStatus; // Status
                return(((EntityReference)context.InputParameters[ParameterName.EntityMoniker]).Id);

            default:
                if (context.InputParameters.Contains(ParameterName.Target) &&
                    (context.InputParameters[ParameterName.Target] is EntityReference))
                {
                    EntityReference monikerId = (EntityReference)context.InputParameters[ParameterName.Target];
                    return(monikerId.Id);
                }
                //Try by best route else fail
                throw new InvalidPluginExecutionException("GetEntityId could not extract the Guid from Context");
            }
            throw new InvalidPluginExecutionException("GetEntityId could not extract the Guid from Context");
        }
예제 #54
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is EntityReference)
            {
                // Obtain the target entity from the input parameters.
                EntityReference reference = (EntityReference)context.InputParameters["Target"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                try
                {
                    Entity entity = new Entity();
                    entity = service.Retrieve(reference.LogicalName, reference.Id, new ColumnSet(true));// ("ss_application");


                    string fetchXml = @"<fetch distinct='false' mapping='logical' returntotalrecordcount='true' page='1' count='50' no-lock='false'>
                                     <entity name='salesorder'>
                                         <attribute name='entityimage_url'/>
                                         <attribute name='name'/>
                                         <attribute name='statecode'/>
                                         <attribute name='totalamount'/>
                                         <attribute name='salesorderid'/>
                                         <order attribute='name' descending='true'/>
                                         <link-entity name='ss_application' from='ss_applicationid' to='ss_application' alias='bb'>
                                             <filter type='and'>
                                                <condition attribute='ss_applicationid' operator='eq' uitype='ss_application' value='" + entity.Id + @"'/>
                                             </filter>  
                                         </link-entity>
                                     </entity>
                                 </fetch>";

                    EntityCollection appOrders = service.RetrieveMultiple(new FetchExpression(fetchXml));

                    if (appOrders.TotalRecordCount == 0)
                    {
                        Guid   orderId   = Guid.NewGuid();
                        Entity order     = new Entity("salesorder", orderId);
                        Entity orderLine = new Entity("salesorderdetail");

                        if (entity.Contains("ss_applicationid"))
                        {
                            ConditionExpression condition = new ConditionExpression
                            {
                                AttributeName = "name",
                                Operator      = ConditionOperator.Equal
                            };
                            condition.Values.Add("Primary Unit");

                            FilterExpression filter = new FilterExpression();
                            filter.AddCondition(condition);

                            QueryExpression query = new QueryExpression("uom");
                            query.ColumnSet.AddColumn("name");
                            query.Criteria.AddFilter(filter);

                            EntityCollection uomList = service.RetrieveMultiple(query);

                            if (uomList.Entities.Count > 0)
                            {
                                Guid uomId = uomList[0].Id;

                                //@"<Fetch mapping='logical'>
                                //    <entity name='uom'>
                                //        <attribute name='uomid'/>
                                //        <attribute name='name'/>
                                //        <filter type='and'>
                                //            <condition attribute='name' operator='eq' value='Primary Unit'/>
                                //        </filter>
                                //    </entity>
                                //</fetch>";

                                order["name"]                  = ("Order for " + entity.Attributes["ss_name"]);
                                order["ss_application"]        = new EntityReference("ss_application", entity.Id);
                                order["pricelevelid"]          = entity.Attributes["ss_pricelist"];
                                order["customerid"]            = entity.Attributes["ss_customer"];
                                order["ss_destinationaddress"] = entity.Attributes["ss_destinationaddress"];

                                // Create the Order in Microsoft Dynamics CRM.
                                tracingService.Trace("AppOrderPlugin: Creating the Order.");
                                service.Create(order);

                                orderLine["isproductoverridden"] = false;
                                orderLine["productid"]           = entity.Attributes["ss_product"];
                                orderLine["uomid"]        = new EntityReference("uom", uomId); //uoms
                                orderLine["salesorderid"] = new EntityReference("salesorder", orderId);
                                orderLine["quantity"]     = Convert.ToDecimal(1);

                                // Create the Order Line in Microsoft Dynamics CRM.
                                tracingService.Trace("AppOrderPlugin: Creating the Product Order Line.");
                                service.Create(orderLine);

                                if (entity.FormattedValues["ss_applicationtype"].Equals("Package Submission"))
                                {
                                    Entity shippingLine = new Entity("salesorderdetail");
                                    Entity primaryUnit  = new Entity("uom");


                                    shippingLine["isproductoverridden"] = false;
                                    shippingLine["productid"]           = entity.Attributes["ss_shippingspeed"];
                                    shippingLine["uomid"]        = new EntityReference("uom", uomId); //Guid.Parse("46d8b737-2339-4011-984a-5e54126ccdb2") /uoms
                                    shippingLine["salesorderid"] = new EntityReference("salesorder", orderId);
                                    shippingLine["quantity"]     = Convert.ToDecimal(1);;

                                    // Create the Order Line in Microsoft Dynamics CRM.
                                    tracingService.Trace("AppOrderPlugin: Creating the Shipping Speed Order Line.");
                                    service.Create(shippingLine);
                                }

                                //close application
                                if (order.Id == orderId)
                                {
                                    entity["statuscode"] = new OptionSetValue(2);
                                    entity["statecode"]  = new OptionSetValue(1);
                                    service.Update(entity);
                                }
                            }
                            else
                            {
                                throw new InvalidPluginExecutionException("UoM not found");
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("An order already exists for this application");
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
예제 #55
0
 /// <summary>
 /// Adds security roles to a given user or team
 /// </summary>
 /// <param name="priniple">User or Team</param>
 /// <param name="securityRoles">List of security role guids</param>
 public void AddSecurityRolesToPrinciple(EntityReference priniple, params Guid[] securityRoles)
 {
     Core.SetSecurityRoles(priniple, securityRoles);
 }
        public static string GetEntityReferenceUrl(this ConnectionDetail connectiondetail, EntityReference entref)
        {
            if (string.IsNullOrWhiteSpace(entref?.LogicalName) || Guid.Empty.Equals(entref.Id))
            {
                return(string.Empty);
            }
            var url = connectiondetail.GetFullWebApplicationUrl();

            url = string.Concat(url,
                                url.EndsWith("/") ? "" : "/",
                                "main.aspx?etn=",
                                entref.LogicalName,
                                "&pagetype=entityrecord&id=",
                                entref.Id.ToString());
            return(url);
        }
예제 #57
0
 /// <summary>
 /// Checks if a principle has the given access right to an entity
 /// </summary>
 /// <param name="entityRef">Entity to check against</param>
 /// <param name="access">Access to check with</param>
 /// <param name="principleRef">User or team</param>
 /// <returns>If the given principle has permission to 'access' the entity</returns>
 public bool HasPermission(EntityReference entityRef, AccessRights access, EntityReference principleRef)
 {
     return(Core.HasPermission(entityRef, access, principleRef));
 }
예제 #58
0
 /// <summary>
 /// Add entity privileges to the given principle ontop of any existing privileges and security roles
 /// </summary>
 /// <param name="principleRef">EntityReference of a user or team</param>
 /// <param name="privileges">A dictionary of entities where each entity contains a dictionary over access rights and privilege depth</param>
 internal void AddPrivileges(EntityReference principleRef, Dictionary <string, Dictionary <AccessRights, PrivilegeDepth> > privileges)
 {
     Core.AddPrivileges(principleRef, privileges);
 }
예제 #59
0
 public void NotExists(EntityReference entityReference, string message)
 {
     NotExists(Service, entityReference, message);
 }
 public static void Assign(this IOrganizationService service, Entity target, EntityReference assignee)
 {
     Assign(service, target.ToEntityReference(), assignee);
 }