Example #1
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            CrmServiceContext           xrm            = new CrmServiceContext(service);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                try
                {
                    Entity       note     = (Entity)context.InputParameters["Target"];//.ToEntity<Annotation>();
                    new_usernote usernote = xrm.new_usernoteSet.Where(p => p.new_NoteId == note.Id.ToString()).FirstOrDefault();
                    if (usernote != null && usernote.new_NoteUserID != null)
                    {
                        //Update ModifiedBy field

                        Guid       UserId = new Guid(usernote.new_NoteUserID);
                        SystemUser user   = xrm.SystemUserSet.Where(p => p.SystemUserId == UserId).FirstOrDefault();
                        note["modifiedby"] = user.ToEntityReference();
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException($"An error occurred in UpdateNote plug-in: {ex.Message}");
                }
            }
        }
Example #2
0
        public static CrmServices GetServices(IOrganizationService service, ITracingService t)
        {
            var xrmContext = new CrmServiceContext(service);


            return(new CrmServices(service, xrmContext, t));
        }
Example #3
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            CrmServiceContext           xrm            = new CrmServiceContext(service);

            if (context.PostEntityImages.Contains("PostNote") && context.PostEntityImages["PostNote"] is Entity)
            {
                new_usernote usernote = context.PostEntityImages["PostNote"].ToEntity <new_usernote>();
                try
                {
                    if (usernote.new_UserFullName != null)
                    {
                        SystemUser user = xrm.SystemUserSet.Where(p => p.FullName == usernote.new_UserFullName).FirstOrDefault();
                        usernote.new_NoteUserID = user.SystemUserId.ToString();
                    }
                    service.Update(usernote);
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException($"An error occurred in UserNote plug-in: {ex.Message}");
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            try
            {
                // The lookup field name in the mcs_artifact entity for the target parent entity that is being deleted
                var targetEntityArtifactLookupFieldName = _unsecureConfig.Trim();

                using (var xrm = new CrmServiceContext(service))
                {
                    var relatedArtifacts = xrm.mcs_artifactSet.Where(x => ((EntityReference)x[targetEntityArtifactLookupFieldName]).Id == context.PrimaryEntityId)
                                           .Select(x => new mcs_artifact()
                    {
                        Id = x.Id
                    });

                    relatedArtifacts.ToList().ForEach(z => service.Delete("mcs_artifact", z.Id));
                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Example #5
0
        public List <Entities> GetEntities()
        {
            var lstEntities = new List <Entities>();


            using (var lServiceContext =
                       new CrmServiceContext(_LoginController.ServerConnection.OrganizationServiceProxy))
            {
                var entityReq = new RetrieveAllEntitiesRequest
                {
                    EntityFilters         = EntityFilters.Entity,
                    RetrieveAsIfPublished = true
                };

                var response = (RetrieveAllEntitiesResponse)lServiceContext.Execute(entityReq);

                lstEntities.AddRange(response.EntityMetadata.Select(currentEntity => new Entities
                {
                    PSchema          = currentEntity.SchemaName,
                    EntitySchemaName = currentEntity.LogicalName,
                    OTC  = currentEntity.ObjectTypeCode ?? 0,
                    Name = currentEntity.DisplayName.UserLocalizedLabel == null
                        ? currentEntity.LogicalName
                        : currentEntity.DisplayName.UserLocalizedLabel.Label
                }));
            }

            return(lstEntities);
        }
        public IEnumerable <myprefix_gu_main> GetRecords()
        {
            var _context = new CrmServiceContext(_serviceProxy);
            var guMains  = (
                from record in _context.myprefix_gu_mainSet
                join relationEntity in _context.new_new_l_myprefix_gu_mainSet on record.myprefix_gu_mainId
                equals relationEntity.myprefix_gu_mainid
                join L in _context.new_lSet on relationEntity.new_lid equals L.new_lId
                where record.new_lookupfield != null && L.new_accountid != null
                where record.CreatedOn > DateTime.Now.AddDays(-20)
                select record).ToList();

            foreach (var item in guMains)
            {
                var recordToDeactivate = GetPassableEntities(item.GetAttributeValue <EntityReference>("new_lookupfield"), item.Id);
                if (recordToDeactivate != null)
                {
                    Entity tempEntity = new Entity(EntityName, recordToDeactivate.Id);

                    //deactivate
                    tempEntity["statecode"]  = new OptionSetValue(1);
                    tempEntity["statuscode"] = new OptionSetValue(2);
                    _service.Update(tempEntity);
                }
            }
            return(guMains.Distinct());
        }
        static void Main(string[] args)
        {
            UpdateOrganizationSettingApp app = new UpdateOrganizationSettingApp();
            Logger   logger   = app.Logger;
            ExitCode exitCode = ExitCode.None;

            try
            {
                logger.Info("Application started.");

                CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

                Options options = new Options();

                Parser.Default.ParseArgumentsStrict(args, options, CommandLineOptions.ArgumentParsingFailed);

                Connection connection = null;

                if (string.IsNullOrWhiteSpace(options.ConnectionString))
                {
                    connection = new Connection(options.AuthorityUrl, options.OrganizationUrl, options.OrganizationUrlSuffix,
                                                options.TenantId, options.ServicePrincipalId, options.ServicePrincipalSecret, options.ConnectionRetries, options.ConnectionTimeout);
                }
                else
                {
                    connection = new Connection(options.ConnectionString, options.ConnectionRetries, options.ConnectionTimeout);
                }

                //TO-DO: this is in experimental mode
                //Console.ReadLine();

                using (CrmServiceContext organizationServiceContext = new CrmServiceContext(connection.OrganizationService))
                    using (CrmService crmService = new CrmService(organizationServiceContext, connection))
                        using (DeploymentService deploymentService = new DeploymentService(organizationServiceContext, crmService))
                        {
                            var organizationSettings = new Organization
                            {
                                BlockAttachments = options.BlockAttachments,
                                EnableAccessToLegacyWebClientUI = options.EnableAccessToLegacyWebClientUI,
                                LegacyFormRendering             = options.LegacyFormRendering,
                                OrganizationName                = options.OrganizationName,
                                SessionTimeoutEnabled           = options.SessionTimeoutEnabled,
                                SessionTimeoutInMinutes         = options.SessionTimeoutInMinutes,
                                SessionTimeoutReminderInMinutes = options.SessionTimeoutReminderInMinutes,
                                SLAPauseStates = options.SLAPauseStates
                            };
                            deploymentService.UpdateOrganizationSettings(organizationSettings);
                            exitCode = ExitCode.Success;
                        }
            }
            catch (Exception ex)
            {
                exitCode = new ExceptionHandlingService(ex).GetExitCode();
            }
            finally
            {
                logger.Info(CultureInfo.InvariantCulture, "Application exited with code: {0}", (int)exitCode);
                Environment.Exit((int)exitCode);
            }
        }
Example #8
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

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

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: GetTeamByName", DateTime.Now.ToLongTimeString());

            using (var crmContext = new CrmServiceContext(service))
            {
                var records = crmContext.TeamSet.Where(r => r.Name == this.teamName.Get(executionContext)).ToList();

                if (records.Count == 1)
                {
                    EntityReference teamReference = new EntityReference(Team.EntityLogicalName, records[0].Id);
                    this.team.Set(executionContext, teamReference);
                }
                else
                {
                    throw new Exception("Team not found or multiple teams with the same name found.");
                }
            }
        }
 private AmendmentDetail GetAmendmentDetails(rscd_Amendment amendment)
 {
     using (var context = new CrmServiceContext(_organizationService))
     {
         return(CurrentBuilder.CreateAmendmentDetails(context, amendment));
     }
 }
Example #10
0
        public void Execute(IServiceProvider serviceProvider)
        {
            className = GetType().Name;

            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service        = serviceFactory.CreateOrganizationService(context.UserId);
            svcContext     = new CrmServiceContext(service);

            preEntityImageAvailable  = false;
            postEntityImageAvailable = false;

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                entity = (Entity)context.InputParameters["Target"];
            }

            if (context.PreEntityImages.Contains(preImageName) && context.PreEntityImages[preImageName] is Entity)
            {
                preEntityImage          = context.PreEntityImages[preImageName];
                preEntityImageAvailable = true;
            }

            if (context.PostEntityImages.Contains(postImageName) && context.PostEntityImages[postImageName] is Entity)
            {
                postEntityImage          = context.PostEntityImages[postImageName];
                postEntityImageAvailable = true;
            }

            ExecutePlugin();
        }
Example #11
0
        private static void LinqEarlyBound()
        {
            count = 0;
            CdsAuthHelper cdsAuthHelper = new CdsAuthHelper();

            using (var proxy = new OrganizationWebProxyClient(cdsAuthHelper.serviceUrl, true))
            {
                // Set Header with the token
                proxy.HeaderToken = cdsAuthHelper.token;

                // Get Crm Service Context (Early bound)
                CrmServiceContext context = new CrmServiceContext(proxy);

                // Retrieve Account records
                var accounts = (from m in context.AccountSet
                                orderby m.AccountId
                                select new
                {
                    m.Name,
                    m.AccountId
                }
                                );

                count = accounts.ToList().Count;
            }
        }
        /// <summary>
        /// Creating the member subscription
        /// </summary>
        /// <param name="organizationService"></param>
        /// <param name="member"></param>
        private void CreateMemberSubscription(IOrganizationService organizationService, Account member)
        {
            CrmServiceContext crmServiceContext = new CrmServiceContext(organizationService);
            //Get Membership Type of the member
            sbma_membershiptype membershipType = GetMembershipTypeOfMember(crmServiceContext, member.sbma_MembershipTypeId.Id);

            if (membershipType == null)
            {
                throw new ArgumentNullException("Error in retrieving membership type");
            }

            //Set the Membershipcription Properties
            sbma_membersubscription membersubscription = new sbma_membersubscription
            {
                //Se the entity reference with Member record
                sbma_MemberId = new EntityReference(member.LogicalName, member.AccountId.Value),
                //Set the entity reference with Membership Type record
                sbma_MembershipTypeId = new EntityReference(membershipType.LogicalName,
                                                            membershipType.sbma_membershiptypeId.Value),
                //Set the subscription due date
                sbma_SubscriptionDueDate = DateTime.Now.AddDays(7.0),
                //Set the Subscription status to pending
                sbma_SubscriptionStatus = new OptionSetValue(
                    (int)sbma_membersubscription_sbma_SubscriptionStatus.Pending)
            };

            //Calling the organization service to create the new member subscription
            organizationService.Create(membersubscription);
        }
        public void MainMethodRelationShip(OrganizationServiceProxy _serviceProxy)
        {
            _serviceProxy.EnableProxyTypes();
            using (CrmServiceContext _context = new CrmServiceContext(_serviceProxy))
            {
                var query_where = (from p1 in _context.new_PinkTestSet
                                   join relP1 in _context.new_new_pinktest_new_pinktest2Set on p1.Id equals relP1.new_pinktestid
                                   join p2 in _context.new_pinktest2Set on relP1.new_pinktest2id equals p2.Id
                                   where !p1.new_LookupPinkTest2.Equals(null) || !p2.new_accountid.Equals(null) //&&
                                                                                                                // p1.new_LookupPinkTest2.Id == p2.Id &&
                                                                                                                //p1.new_accountid.Id == p2.new_accountid.Id &&
                                                                                                                // p1.Id == p2.new_pinktestentityid.Id
                                   select p1).ToList();
                //select new
                //{
                //    contact_name = c.FullName,
                //    account_name = a.Name
                //};

                foreach (var c in query_where)
                {
                    Console.WriteLine(c.new_name);
                }
                Console.ReadLine();
            }
        }
Example #14
0
        public ActionResult Custom(Guid?entityId)
        {
            SpreadSheetModel spreadSheetModel = new SpreadSheetModel();

            if (entityId != null && entityId.HasValue)
            {
                IOrganizationService             orgSerivce = CreateOrganizationService();
                CrmServiceContext                context    = new CrmServiceContext(orgSerivce);
                new_project_initiative_valuation valuation  = null;
                Annotation annotation = GetAnnotation(context, entityId, out valuation);
                spreadSheetModel.IsReadOnly = valuation != null && valuation.StatusCodeEnum == new_project_initiative_valuation_StatusCode.Neaktivnye;
                spreadSheetModel.Body       = SpreadsheetExtension.GetCurrentDocument("SpreadSheetEditor").SaveDocument(DocumentFormat.Xlsx);
                string documentBody = Convert.ToBase64String(spreadSheetModel.Body);
                if (annotation == null)
                {
                    orgSerivce.Create(new Annotation()
                    {
                        ObjectId       = new EntityReference(new_project_initiative_valuation.EntityLogicalName, entityId.Value),
                        ObjectTypeCode = new_project_initiative_valuation.EntityLogicalName,
                        MimeType       = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        FileName       = "[Project Calculation].xlsx",
                        DocumentBody   = documentBody
                    });
                }
                else
                {
                    annotation.DocumentBody = documentBody;
                    context.UpdateObject(annotation);
                    context.SaveChanges();
                }
            }
            return(PartialView("SpreadSheetPartial", spreadSheetModel));
        }
Example #15
0
        static void Main(string[] args)
        {
            ProcessExecutionContextApp app = new ProcessExecutionContextApp();
            Logger   logger   = app.Logger;
            ExitCode exitCode = ExitCode.None;

            try
            {
                logger.Info("Application started.");

                CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

                Options options = new Options();

                Parser.Default.ParseArgumentsStrict(args, options, CommandLineOptions.ArgumentParsingFailed);

                Connection connection = null;

                if (string.IsNullOrWhiteSpace(options.ConnectionString))
                {
                    connection = new Connection(options.AuthorityUrl, options.OrganizationUrl, options.OrganizationUrlSuffix,
                                                options.TenantId, options.ServicePrincipalId, options.ServicePrincipalSecret, options.ConnectionRetries, options.ConnectionTimeout);
                }
                else
                {
                    connection = new Connection(options.ConnectionString, options.ConnectionRetries, options.ConnectionTimeout);
                }

                using (CrmServiceContext organizationServiceContext = new CrmServiceContext(connection.OrganizationService))
                    using (CrmService crmService = new CrmService(organizationServiceContext, connection))
                        using (IExecutionContextService executionContextService = new ExecutionContextService(organizationServiceContext, connection, crmService))
                        {
                            Console.WriteLine("Press any key to start ...");
                            Console.ReadKey();
                            do
                            {
                                while (!Console.KeyAvailable)
                                {
                                    Console.WriteLine("Press ESC to stop");
                                    executionContextService.ProcessExecutionContexts();
                                    // Wait 5 secs until the next call
                                    // TO-DO: the solution must be more robust to ensure that we are not going to face any pitfalls
                                    Thread.Sleep(5000);
                                }
                            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

                            exitCode = ExitCode.Success;
                        }
            }
            catch (Exception ex)
            {
                exitCode = new ExceptionHandlingService(ex).GetExitCode();
            }
            finally
            {
                logger.Info(CultureInfo.InvariantCulture, "Application exited with code: {0}", (int)exitCode);
                Environment.Exit((int)exitCode);
            }
        }
Example #16
0
        /// <summary>
        /// Get Subscription Details
        /// </summary>
        /// <param name="serviceContext"></param>
        /// <param name="memberSubscriptionId"></param>
        /// <returns></returns>
        private sbma_membersubscription GetSubscription(CrmServiceContext serviceContext, Guid memberSubscriptionId)
        {
            var memberSubscription = (from sm in serviceContext.sbma_membersubscriptionSet
                                      where sm.sbma_membersubscriptionId == memberSubscriptionId
                                      select sm).FirstOrDefault();

            return(memberSubscription);
        }
Example #17
0
 public WeatherForecastController(ILogger <WeatherForecastController> logger,
                                  IConfiguration configuration, ICRMService crmService, CrmServiceContext crmServiceContext)
 {
     _logger            = logger;
     _configuration     = configuration;
     _crmService        = crmService;
     _crmServiceContext = crmServiceContext;
 }
Example #18
0
        /// <summary>
        /// Get Subscription fee
        /// </summary>
        /// <param name="crmServiceContext"></param>
        /// <param name="membersubscription"></param>
        /// <returns></returns>
        private decimal GetDuePayment(CrmServiceContext crmServiceContext, sbma_membersubscription membersubscription)
        {
            var membershipType = (from mt in crmServiceContext.sbma_membershiptypeSet
                                  where mt.sbma_membershiptypeId == membersubscription.sbma_MembershipTypeId.Id
                                  select mt).FirstOrDefault();

            return(membershipType.sbma_SubscriptionFee.Value);
        }
Example #19
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            CrmServiceContext           xrm            = new CrmServiceContext(service);

            if (context.PostEntityImages.Contains("PostCall") && context.PostEntityImages["PostCall"] is Entity)
            {
                PhoneCall call = context.PostEntityImages["PostCall"].ToEntity <PhoneCall>();
                if (call.StateCode is PhoneCallState.Completed)
                {
                    try
                    {
                        //call.Description += $"\nPhone call was completed at {call.ActualEnd} \nDue date: {call.ScheduledEnd}";
                        bool CallInTime         = (int)DateTime.Compare((DateTime)call.ScheduledEnd, (DateTime)call.ActualEnd) >= 0;//>=0 in time, <0 not in time
                        CrmEarlyBound.Task task = xrm.TaskSet.Where(p => p.RegardingObjectId.Id == call.RegardingObjectId.Id).ToList().FirstOrDefault();
                        if (task.StateCode is TaskState.Completed)
                        {
                            bool TaskInTime = (int)DateTime.Compare((DateTime)task.ScheduledEnd, (DateTime)task.ActualEnd) >= 0;
                            BL.ActivityInTime(CallInTime, TaskInTime, call.RegardingObjectId.Id, serviceProvider);
                        }
                        //BL.ActivityInTime(call, CallInTime, call.RegardingObjectId.Id, serviceProvider);
                        //get account from call
                        //EntityReference acc = (EntityReference)call.Attributes["regardingobjectid"];
                        //Entity accc = service.Retrieve(acc.LogicalName, acc.Id,  new ColumnSet(true));
                        //Account account = (Account)accc;
                        //ColumnSet columnSet = new ColumnSet(true);
                        //Account account = (Account)service.Retrieve("account", acc.Id, columnSet);
                        //Entity accEnt = (Entity)account;

                        //IEnumerable<Task> relatedTasks = account.Account_Tasks;
                        //Task related = (Task)relatedTasks.First<Task>();

                        /*
                         * List<Task> relatedTasks = xrm.TaskSet.Where(c => c.RegardingObjectId.Id == account.Id).ToList();
                         * Task related = relatedTasks.First();
                         * //throw new InvalidPluginExecutionException(related == null ? "null" : "not null");
                         * if (related.StateCode is TaskState.Completed)//Value cannot be null. Parameter name: source
                         * {
                         *  bool TaskInTime = (int)DateTime.Compare((DateTime)related.ScheduledEnd, (DateTime)related.ActualEnd) >= 0;
                         *  if (CallInTime && TaskInTime)
                         *      account.new_NewClientProccess = Account_new_NewClientProccess.Passedintime;
                         *  else
                         *      account.new_NewClientProccess = Account_new_NewClientProccess.Passednotintime;
                         *  service.Update(call);
                         *  service.Update(account);
                         * }
                         */
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidPluginExecutionException($"An error occurred in Call plug-in: {ex.Message}");
                    }
                }
            }
        }
        /// <summary>
        /// Get membership type details of the new member
        /// </summary>
        /// <param name="crmServiceContext"></param>
        /// <param name="memberid"></param>
        /// <returns></returns>
        public sbma_membershiptype GetMembershipTypeOfMember(CrmServiceContext crmServiceContext,
                                                             Guid membershipTypeId)
        {
            var membershiptype = (from mt in crmServiceContext.sbma_membershiptypeSet.Where
                                      (m => m.sbma_membershiptypeId == membershipTypeId)
                                  select mt).FirstOrDefault();

            return((sbma_membershiptype)membershiptype);
        }
Example #21
0
        public static void ClassInit(TestContext testContext)
        {
            context          = ContextCreator.Create();
            accountTools     = new AccountTools(context);
            opportunityTools = new OpportunityTools(context);

            opportunityTools.DeleteAll();
            accountTools.DeleteAll();
        }
        private rscd_Establishment GetOrCreateEstablishment(CheckingWindow checkingWindow, string id)
        {
            using (var context = new CrmServiceContext(_organizationService))
            {
                var establishmentDto =
                    context.rscd_EstablishmentSet.SingleOrDefault(
                        e => e.rscd_URN == id);
                if (establishmentDto == null)
                {
                    establishmentDto =
                        context.rscd_EstablishmentSet.SingleOrDefault(
                            e => e.rscd_LAEstab == id);
                }

                if (establishmentDto != null)
                {
                    return(establishmentDto);
                }

                School establishment = null;
                try
                {
                    establishment = _establishmentService.GetByURN(checkingWindow, new URN(id));
                }
                catch
                {
                }

                if (establishment == null)
                {
                    establishment = _establishmentService.GetByDFESNumber(checkingWindow, id);
                }

                if (establishment == null)
                {
                    return(null);
                }


                establishmentDto = new rscd_Establishment()
                {
                    rscd_Name               = establishment.SchoolName,
                    rscd_URN                = establishment.Urn.Value,
                    rscd_LAEstab            = establishment.DfesNumber.ToString(),
                    rscd_Schooltype         = establishment.SchoolType,
                    rscd_NumberofAmendments = 0
                };
                context.AddObject(establishmentDto);
                var result = context.SaveChanges();
                if (result.HasError)
                {
                    throw result.FirstOrDefault(e => e.Error != null)?.Error ?? new ApplicationException();
                }

                return(establishmentDto);
            }
        }
        private Amendment GetAmendment(CheckingWindow checkingWindow, Guid amendmentId)
        {
            using (var context = new CrmServiceContext(_organizationService))
            {
                var amendment = context.rscd_AmendmentSet.FirstOrDefault(
                    x => x.Id == amendmentId);

                return(amendment != null?Convert(checkingWindow, amendment) : null);
            }
        }
        public AmendmentOutcome BuildAmendments(Amendment amendment)
        {
            using (var context = new CrmServiceContext(_organizationService))
            {
                AmendmentOutcome outcome;

                var amendmentDto = new rscd_Amendment
                {
                    rscd_Checkingwindow = amendment.CheckingWindow.ToCRMCheckingWindow(),
                    rscd_Amendmenttype  = amendment.AmendmentType.ToCRMAmendmentType(),
                    rscd_Academicyear   = _allocationYear,
                    rscd_URN            = amendment.URN,
                    OwnerId             = _firstLineTeam
                };

                outcome = _outcomeService.ApplyRules(amendmentDto, amendment);

                if (amendment.IsUserConfirmed && outcome.IsComplete && outcome.FurtherQuestions == null)
                {
                    MapAmendmentToDto(amendment, amendmentDto);
                    var amendmentTypeEntity = MapAmendmentTypeToDto(amendment);
                    context.AddObject(amendmentTypeEntity);
                    context.AddObject(amendmentDto);

                    // Save
                    var result = context.SaveChanges();
                    if (result.HasError)
                    {
                        throw result.FirstOrDefault(e => e.Error != null)?.Error ?? new ApplicationException();
                    }

                    if (amendmentDto.rscd_Outcome == rscd_Outcome.Autoapproved ||
                        amendmentDto.rscd_Outcome == rscd_Outcome.Autorejected)
                    {
                        amendmentDto.StateCode        = rscd_AmendmentState.Inactive;
                        amendmentDto.rscd_recorded_by = _autoRecordedUser;
                        _organizationService.Update(amendmentDto);
                    }

                    var relationship = new Relationship(RelationshipKey);
                    _organizationService.Associate(amendmentTypeEntity.LogicalName, amendmentTypeEntity.Id, relationship,
                                                   new EntityReferenceCollection
                    {
                        new EntityReference(amendmentDto.LogicalName, amendmentDto.Id)
                    });

                    outcome.IsAmendmentCreated = true;
                    outcome.NewAmendmentId     = amendmentDto.Id;

                    _logger.LogInformation("Amendment requested - ID: {amendmentId}", amendmentDto.Id);
                }

                return(outcome);
            }
        }
Example #25
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var connectionString =
                ConfigurationManager.ConnectionStrings[Infrastructure.Contants.CrmConnectionStringKey].ToString();
            CrmServiceClient conn = new CrmServiceClient(connectionString);

            // Cast the proxy client to the IOrganizationService interface.
            var orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
            var crmContext = new CrmServiceContext(orgService);
            var manager    = new ApplicationUserManager(new CrmUserStore <ApplicationUser>(crmContext));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
        public IEnumerable <Amendment> GetAmendments(CheckingWindow checkingWindow, string urn)
        {
            using (var context = new CrmServiceContext(_organizationService))
            {
                var amendments = context.rscd_AmendmentSet.Where(a => a.rscd_URN == urn).ToList();

                return(amendments.Where(a => ValidAmendmentForCheckingWindow(checkingWindow, a))
                       .OrderByDescending(o => o.CreatedOn)
                       .Select(x => Convert(checkingWindow, x)));
            }
        }
Example #27
0
        public void UpdateExchangeRates(Dictionary <string, decimal> exchangeRates)
        {
            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["Xrm"].ToString();
            var    client  = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connStr);

            using (var ctx = new CrmServiceContext(client))
            {
                // Get the base currency
                var baseCurrencyCode =
                    ctx.TransactionCurrencySet
                    .Join(ctx.OrganizationSet
                          , t => t.TransactionCurrencyId
                          , o => o.BaseCurrencyId.Id
                          , (t, o) => t.ISOCurrencyCode).FirstOrDefault();

                if (baseCurrencyCode == null)
                {
                    _log.Error("Cannot find base currency ISO code.");
                }
                _log.Info($"The base currency ISO code is {baseCurrencyCode}.");

                var baseRate = exchangeRates[baseCurrencyCode];

                // Get all currencies
                var currencies = ctx.TransactionCurrencySet
                                 .Select(t => new TransactionCurrency()
                {
                    TransactionCurrencyId = t.TransactionCurrencyId,
                    ISOCurrencyCode       = t.ISOCurrencyCode
                })
                                 .ToArray();

                // Loop through and update the exchange rates
                foreach (var c in currencies)
                {
                    if (String.Equals(c.ISOCurrencyCode, baseCurrencyCode, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    var rate = exchangeRates[c.ISOCurrencyCode] / baseRate;
                    _log.Info($"Updating {exchangeRates[c.ISOCurrencyCode]}: {rate} to D365.");

                    ctx.Execute(new UpdateRequest()
                    {
                        Target = new TransactionCurrency()
                        {
                            TransactionCurrencyId = c.TransactionCurrencyId,
                            ExchangeRate          = rate
                        }
                    });
                }
            }
        }
Example #28
0
        private Annotation GetDefaultSettingAnnotation(CrmServiceContext context)
        {
            new_setting setting = context.new_settingSet.FirstOrDefault(e => e.new_key == "ProjectCalculationExcelTemplate");

            if (setting != null)
            {
                context.LoadProperty(setting, "new_setting_Annotations");
                return(setting.new_setting_Annotations == null ? null : setting.new_setting_Annotations.FirstOrDefault());
            }
            return(null);
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("{0}", "CreateCOARevisionNumber Plug-in");

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != caps_CertificateofApproval.EntityLogicalName || context.MessageName != "Create")
                {
                    return;
                }

                if (!entity.Contains("caps_ptr"))
                {
                    throw new Exception("Project is a required field.");
                }
                //Get COA PTR
                var projectTracker = entity.GetAttributeValue <EntityReference>("caps_ptr");


                using (var crmContext = new CrmServiceContext(service))
                {
                    //Check if there are any other COAs for this project in a Draft  or Submitted State
                    var records = crmContext.caps_CertificateofApprovalSet.Where(r => r.caps_PTR.Id == projectTracker.Id &&
                                                                                 r.caps_CertificateofApprovalId != context.PrimaryEntityId &&
                                                                                 r.StatusCode.Value == (int)caps_CertificateofApproval_StatusCode.Registered).ToList();

                    var    revisionNumber = 1;
                    string coaNumber      = "";
                    if (records.Count() > 0)
                    {
                        //Get top value
                        var topRecord = records.OrderByDescending(r => r.caps_RevisionNumber).Take(1).ToList();
                        revisionNumber = topRecord[0].caps_RevisionNumber.Value + 1;
                        coaNumber      = topRecord[0].caps_Name;
                    }
                    else
                    {
                        coaNumber = "062-" + entity.GetAttributeValue <string>("caps_autonumber");
                    }
                    entity["caps_name"]           = coaNumber;
                    entity["caps_revisionnumber"] = revisionNumber;
                }
            }
        }
Example #30
0
        protected override void Execute(CodeActivityContext codeActivityContext)
        {
            className = GetType().Name;

            context         = codeActivityContext;
            workflowContext = context.GetExtension <IWorkflowContext>();
            serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
            tracingService  = context.GetExtension <ITracingService>();
            service         = serviceFactory.CreateOrganizationService(workflowContext.UserId);
            svcContext      = new CrmServiceContext(service);

            this.ExecuteWorkflow();
        }