Ejemplo n.º 1
0
        public override int RunJob()
        {
            try
            {
                FileLock(true);
                _deleteParticipantDataTimeout             = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteParticipantDataTimeout"));
                _deleteInputFileErrorsOver1YearOldTimeout = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteOldInputFileErrorsTimeout"));
                int jobReturnCode = ClearUpload();

                InputFileHistory ifh = inputFileHistoryRepository.Find(x => x.Code == _inputFileHistoryCode).First();
                ifh.Status = "Cancelled";
                inputFileHistoryRepository.Update(ifh);

                //unlock the File provider for future uploads
                FileLock(false);

                return(jobReturnCode);
            }
            catch (Exception e)
            {
                if (CurrentStep != null)
                {
                    CurrentStep.Finish(false);
                }
                UnhandledException = e;
                spRunner2.PublishError("Clear Participant Data", 3, e.Message, _inputFileHistoryCode, null, null);
                //Log error to db for debug purposes.

                //unlock the File provider for future uploads
                FileLock(false);
                return(1);
            }
        }
        public override int RunJob()
        {
            try
            {
                FileLock(true);

                _deleteParticipantDataTimeout             = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteParticipantDataTimeout"));
                _deleteInputFileErrorsOver1YearOldTimeout = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteOldInputFileErrorsTimeout"));
                _deleteValidatedParticipantDataTimeout    = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteValidatedParticipantDataTimeout"));
                _copyValidatedParticipantsTimeout         = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("CopyValidatedParticipantsTimeout"));
                int jobReturnCode = ValidatedUpload(_decisionLevel);

                //unlock the File provider for future uploads
                FileLock(false);

                return(jobReturnCode);
            }
            catch (Exception e)
            {
                if (CurrentStep != null)
                {
                    CurrentStep.Finish(false);
                }
                UnhandledException = e;
                spRunner2.PublishError("Copy Valid Records", 3, e.Message, _inputFileHistoryCode, null, null);
                //Log error to db for debug purposes.

                //unlock the File provider for future uploads
                FileLock(false);
                return(1);
            }
        }
 /*
  * Quick Start:
  *  It is preferrable to use an existing ASP.NET MembershipProvider or write one for your application
  *  as it improves security and makes reuse easier. This sample only uses rudimentary validation.
  */
 private bool ValidateUser(string username, string password)
 {
     return /*(username == password) &&*/
            //SimpleServiceLocator.Instance.Get<IUcbManagementInformationRepository<UcbManagementInformation.Server.DataAccess.User>>
            //(DataAccessUtilities.ConvertContext(this.ObjectContext)).Find
            (DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UcbManagementInformation.Server.DataAccess.MCUser> >(this.ObjectContext).Find
                 (u => u.Name == username && u.Password == password).Any());
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Locks or unlocks the file
        /// </summary>
        /// <param name="isLock"></param>
        private void FileLock(bool isLock)
        {
            providerRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ProviderOrganisation> >();
            ProviderOrganisation providerEntry = providerRepository.First(x => x.KeyValue == ProviderKey && x.FileType == _fileType);

            providerEntry.Status = (isLock ? "Locked" : "Unlocked");
            providerRepository.Update(providerEntry);
            providerRepository.SaveChanges();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Constructs a set of DataTableJoin objects representing the joins necessary
        /// for joining the tables in the List.
        /// </summary>
        /// <param name="tableCodeList">A list of Data Table codes to be joined</param>
        /// <returns>A list of DataTableJoin objects representing the joins for the supplied tables.</returns>
        public static List <DataTableJoin> RetreiveTableJoins(List <Guid> tableCodeList)
        {
            List <DataTableJoin> tableJoinList = new List <DataTableJoin>();
            // Holds a DataTableRelationship
            DataTableRelationship Dtr;

            // A DataTableJoin
            DataTableJoin Dtj;

            // A list of DataTableRelationshipJoins
            List <DataTableRelationshipJoin> DtrjList = new List <DataTableRelationshipJoin>();

            // j is the outer loop control variable: It is the index of the
            // current table in the list we are considering when comparing against
            // the rest of the tables.
            foreach (Guid currentTableOuterLoop in tableCodeList)// (int j = 0; j < tableList.Count; j++)
            {
                // i is the inner loop control variable: It is the index of
                // the table being compared against
                foreach (Guid currentTableInnerLoop in tableCodeList) //(int i = 0; i < tableList.Count; i++)
                {
                    // Ensure we don't compare table to itself
                    if (currentTableInnerLoop != currentTableOuterLoop)
                    {
                        // Get DataTableRelationship between tables j and i
                        Dtr = DataAccessUtilities.RepositoryLocator <IDataTableRelationshipRepository>().GetByTableFromAndTableTo(currentTableOuterLoop, currentTableInnerLoop);

                        // Get list of RelationshipJoins if there are Relationships
                        if (Dtr != null)
                        {
                            DtrjList = DataAccessUtilities.RepositoryLocator <IDataTableRelationshipJoinRepository>().GetByDataTableRelationshipCode(Dtr.Code);
                        }

                        // Add all unique RelationshipJoins to list of joins
                        foreach (DataTableRelationshipJoin join in DtrjList)
                        {
                            Dtj = DataAccessUtilities.RepositoryLocator <IDataTableJoinRepository>().GetByCode(join.DataTableJoinCode);

                            // Do not add the new TableJoin to the list if it
                            // already exists in there
                            if (!tableJoinList.Contains(Dtj))
                            {
                                tableJoinList.Add(Dtj);
                            }
                        }
                    } // if (i != j)
                }     // i loop
            }         // j loop



            return(tableJoinList);
        }
        public override int  RunJob()
        {
            try
            {
                FileLock(true);
                //Insert of the file upload history record
                InsertHistoryRecord();

                //set up timeouts for job
                _deleteParticipantDataTimeout         = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("DeleteParticipantDataTimeout"));
                _validateParticipantDuplicatesTimeout = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateParticipantDuplicatesTimeout"));
                _validateAgreementRegionTimeout       = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateAgreementRegionTimeout"));
                _validateParticipantPostCodeTimeout   = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateParticipantPostCodeTimeout"));
                _validateLeaverTimeout                      = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateLeaverTimeout"));
                _validateLeavingDateTimeout                 = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateLeavingDateTimeout"));
                _validateStartDateTimeout                   = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ValidateStartDateTimeout"));
                _participantSelectValidCountTimeout         = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ParticipantSelectValidCountTimeout"));
                _participantSelectErrorCountTimeout         = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ParticipantSelectErrorCountTimeout"));
                _participantSelectWarningCountTimeout       = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ParticipantSelectWarningCountTimeout"));
                _participantSelectInformationalCountTimeout = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("ParticipantSelectInformationalCountTimeout"));
                _loadParticipantMessagesTimeout             = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("LoadParticipantMessagesTimeout"));
                _copyParticipantBulkLoadedFlatTimeout       = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("CopyParticipantBulkLoadedFlatTimeout"));
                Guid historyFileGuid = _inputFileHistoryRow.Code;

                int jobReturnCode = UploadFile();

                //leave locked until a decision has been made
                //FileLock(false);

                return(jobReturnCode);
            }
            catch (Exception e)
            {
                if (CurrentStep != null)
                {
                    CurrentStep.Finish(false);
                }
                UnhandledException = e;
                spRunner2.PublishError("File Upload", 3, e.Message, _inputFileHistoryCode, null, null);
                //Log error to db for debug purposes.

                //unlock the File provider for future uploads
                FileLock(false);
                return(1);
            }
        }
        public CopyToValidJob(Guid code, string providerKey, Guid inputFileHistoryCode, int decisionLevel, string userID, string webPath, DateTime?added, DateTime?started, DateTime?ended, string description)
        {
            Code                  = code;
            ProviderKey           = providerKey;
            AddedTime             = added;
            StartTime             = started;
            EndTime               = ended;
            Description           = description;
            _inputFileHistoryCode = inputFileHistoryCode;
            _decisionLevel        = decisionLevel;
            //Get Connection string from configuration
            _connectionString = ConfigurationManager.ConnectionStrings["MIStagingConnectionString"].ConnectionString;

            uow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation");

            providerRepository         = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ProviderOrganisation> >(uow.ObjectContext);
            inputFileHistoryRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <InputFileHistory> >(uow.ObjectContext);
            inputFileErrorsRepository  = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <InputFileError> >(uow.ObjectContext);
            uploadMonitorRepository    = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UploadMonitor> >(uow.ObjectContext);


            //set private variables
            ProviderOrganisation providerOrganisationItem =
                providerRepository.First(x => x.KeyValue == ProviderKey);

            _providingOrganistaionCode = providerOrganisationItem.Code;
            _fileType = "Participant";

            _userID = userID;
            UserId  = userID;


            JobSteps = new List <JobStep>()
            {
                new JobStep("DeleteValidatedParticipantData", "Copy Valid Participant", this, 1),
                new JobStep("CopyValidatedParticipants", "Copy Valid Participant", this, 2),
                new JobStep("DeleteParticipantData", "Copy Valid Participant", this, 3),
                //new JobStep("DeleteParticipantDataOver4HoursOld","Copy Valid Participant",this,4),
                new JobStep("DeleteInputFileErrorsOver1YearOld", "Copy Valid Participant", this, 4)
            };
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Builds a hierarchical path through the database graph structure, from the
        /// lowest level table up to the highest level table. It is done in the style of a
        /// breadth-first search so each element in the list is higher than or
        /// at an equal level to any previous element only.
        /// </summary>
        /// <param name="startTableName">The lowest level table at which to begin the hierarchy.</param>
        /// <returns>A hierarchical list of tables.</returns>
        private List <string> BuildTableHierarchy(string startTableName)
        {
            // List of table names to be returned.
            List <string> TableList = new List <string>();

            // List to hold immediate joins pending traversal.
            List <DataTableJoin> JoinList = new List <DataTableJoin>();

            // Pointer to index of TableList; points to next table that has not yet been visited
            // (all its predecessors in the list have been visited).
            int index = 1;

            // Add first table, then get all joins to this table
            TableList.Add(startTableName);
            JoinList.AddRange(DataAccessUtilities.RepositoryLocator <IDataTableJoinRepository>().Find(x => x.ToTable == startTableName));

            // This loop continues whilst there are joins to any of the tables at the current level.
            while (JoinList.Count > 0)
            {
                // Add each table that joins to the current tables.
                foreach (DataTableJoin CurrentJoin in JoinList)
                {
                    TableList.Add(CurrentJoin.FromTable);
                }

                JoinList.Clear();

                // Obtain the joins to all tables not yet visited.
                while (index < TableList.Count)
                {
                    string tableForFilter = TableList[index];
                    JoinList.AddRange(CurrentDataModel.DataTableJoins.Where(x => x.ToTable == tableForFilter));
                    //                       DataAccessUtilities.RepositoryLocator<IDataTableJoinRepository>().Find(x => x.ToTable == tableForFilter));
                    index++;
                }
            }

            // Reverse the list, so tables are in descending order
            TableList.Reverse();
            return(TableList);
        }
Ejemplo n.º 9
0
        public override int  RunJob()
        {
            try
            {
                _truncatePostCodeDataTimeout   = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("TruncatePostCodeDataTimeout"));
                _truncateMIPostCodeDataTimeout = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("TruncateMIPostCodeDataTimeout"));
                _populatePostCodesTimeout      = Convert.ToInt32(DataAccessUtilities.GetSystemParameterByName("PopulatePostCodesTimeout"));
                int jobReturnCode = UploadFiles();
                return(jobReturnCode);
            }
            catch (Exception e)
            {
                if (CurrentStep != null)
                {
                    CurrentStep.Finish(false);
                }
                UnhandledException = e;
                //Log error to db for debug purposes.

                return(1);
            }
        }
Ejemplo n.º 10
0
        private i9Message GetSyncData(string LatChanged)
        {
            i9Message response     = new i9Message();
            string    sql          = "";
            int       TableCounter = 0;

            List <string> tables = DataAccessUtilities.SyncTableNames();
            Dictionary <string, string> tableMapping = new Dictionary <string, string>();

            tables.ForEach(delegate(String TableName)
            {
                sql += " SELECT * FROM " + TableName + " WHERE  LastUpdate >= " + SQLUtility.SQLString(LatChanged.Trim()) + "  or  LastUpdate is null " + Environment.NewLine;
                tableMapping.Add("Table" + (TableCounter == 0 ? "" : TableCounter.ToString()), TableName);
                TableCounter++;
            });

            DataSet ds = new SQLAccess().GetDataSet(sql, tableMapping);

            response.MsgBodyDataSet = ds;

            return(response);
        }
        /// <summary>
        /// Copys the uploaded data to a validated area
        /// </summary>
        /// <param name="uploadDecision">The type of data to copy: 'ValidOnly','ValidAndInfo' or 'ValidInfoAndWarning'</param>
        /// <returns></returns>
        public int ValidatedUpload(int maximumErrorLevel)
        {
            using (spRunner.Cn)
            {
                spRunner.Cn.Open();
                spRunner.IsOpen = true;
                using (SqlTransaction transact = spRunner.Cn.BeginTransaction())
                {
                    DeleteValidatedParticipantData(transact);
                    CopyValidatedParticipants(transact);
                    transact.Commit();
                }
                spRunner.Cn.Close();
                spRunner.IsOpen = false;
            }
            //Stamp number of records uploaded and remove lock of database
            using (uow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation"))
            {
                inputFileHistoryRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <InputFileHistory> >(uow.ObjectContext);
                providerRepository         = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ProviderOrganisation> >(uow.ObjectContext);
                InputFileHistory ifh = inputFileHistoryRepository.Find(x => x.Code == _inputFileHistoryCode).First();
                ifh.Status         = "Validated Loaded " + maximumErrorLevel.ToString();
                ifh.UploadDecision = maximumErrorLevel;
                //_inputFileHistoryRow.ValidatedLoadDate = DateTime.Now;
                inputFileHistoryRepository.Update(ifh);

                ProviderOrganisation po = providerRepository.First(x => x.KeyValue == ProviderKey && x.FileType == "Participant");
                po.CurrentValidatedFileCode = _inputFileHistoryCode;
                providerRepository.Update(po);

                uow.Commit();
            }

            DeleteParticipantData();
            //DeleteParticipantDataOver4HoursOld();
            DeleteInputFileErrorsOver1YearOld();
            return(0);
        }
Ejemplo n.º 12
0
        public PostCodeUpdateJob(Guid code, string userID, string webPath, DateTime?added, DateTime?started, DateTime?ended, string data)
        {
            Code            = code;
            AddedTime       = added;
            StartTime       = started;
            EndTime         = ended;
            Data            = data;
            _uniqueFilename = Data.Split('|');
            //Get Connection string from configuration
            _connectionString = ConfigurationManager.ConnectionStrings["MIStagingConnectionString"].ConnectionString;

            //set private variables
            SystemParameterRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <MCSystemParameter> >();

            _userID  = userID;
            UserId   = userID;
            JobSteps = new List <JobStep>()
            {
                new JobStep("DeleteOldFilesFromLoadingArea", "DeleteFromLoadingArea", this, 1),
                //new JobStep("BulkUploadWPC","Bulk Load File",this,2),
                //new JobStep("BulkUploadLA","Bulk Load File",this,3),
                //new JobStep("BulkUploadCty","Bulk Load File",this,4),
                //new JobStep("BulkUploadLEA","Bulk Load File",this,5),
                //new JobStep("BulkUploadRegion","Bulk Load File",this,6),
                //new JobStep("BulkUploadWARD","Bulk Load File",this,7),
                new JobStep("BulkUploadPC", "Bulk Load File", this, 8),
                //new JobStep("UpdateWPC","Bulk Load File",this,9),
                //new JobStep("UpdateLA","Bulk Load File",this,10),
                //new JobStep("UpdateLEA","Bulk Load File",this,11),
                //new JobStep("UpdateRegion","Bulk Load File",this,12),
                //new JobStep("UpdateWARD","Bulk Load File",this,13),
                //new JobStep("UpdateCty","Bulk Load File",this,14),
                //new JobStep("UpdatePC","Bulk Load File",this,15),
                //new JobStep("UpdatePostCodes","Update PostCode",this,16),
                new JobStep("DeletePreviousFromMI", "Copy post codes", this, 17),
                new JobStep("CopyToMI", "Copy post codes", this, 18)
            };
        }
        private UcbManagementInformation.Server.DataAccess.MCUser GetUser(string userName)
        {
            MCUser        userToReturn;
            List <string> roles = new List <string>();
            string        userNameWithoutDomain = userName.Substring(userName.LastIndexOf('\\') + 1);
            //userToReturn = DataAccessUtilities.RepositoryLocator<IUcbManagementInformationRepository<UcbManagementInformation.Server.DataAccess.MCUser>>
            //    (this.ObjectContext).Find(u => u.Name == userNameWithoutDomain).First();


            var StaffMember = DataAccessUtilities.RepositoryLocator <IUcbRepository <Staff> >
                                  (this.ObjectContext).Find(u => u.StaffNumber == userNameWithoutDomain).First();

            userToReturn = new MCUser()
            {
                Forename = StaffMember.FirstName, Surname = StaffMember.LastName, Name = StaffMember.StaffNumber, Code = StaffMember.Code, RowIdentifier = StaffMember.RowIdentifier
            };
            //Populate Roles with the names of all the users roles.
            userToReturn.Roles = DataAccessUtilities.RepositoryLocator <IUcbRepository <StaffAttribute> >(this.ObjectContext).Find(x => x.Application.ApplicationName == "Ucb" && x.StaffCode == StaffMember.Code && x.ApplicationAttribute.IsRole && x.LookupValue == "Yes", "ApplicationAttribute").Select(x => x.ApplicationAttribute.AttributeName).ToList();


            //Populate Roles with the names of all the users roles.
            //userToReturn.Roles = DataAccessUtilities.RepositoryLocator<IMCUserRepository>().GetAllRoleNamesByUserCode(userToReturn.Code);
            return(userToReturn);
        }
Ejemplo n.º 14
0
        public JobBase GetFileUploadJobByCode(Guid code)
        {
            var job = (FileUploadJob)JobQueue.Instance.FindJobByCode(code);

            if (job == null)
            {
                IUcbManagementInformationRepository <UploadJobQueue> uploadJobQueueRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UploadJobQueue> >();
                var uploadjob = uploadJobQueueRepository.Find(x => x.Code == code, "JobSteps").FirstOrDefault();
                if (uploadjob != null)
                {
                    var           descSplit   = uploadjob.JobDescription.Split('|');
                    FileUploadJob jobToReturn = new FileUploadJob()
                    {
                        Code           = uploadjob.Code,
                        ProviderKey    = descSplit[1],
                        Status         = (JobStatus)Enum.Parse(typeof(JobStatus), uploadjob.Status),
                        UniqueFileName = descSplit[3],
                        UserId         = uploadjob.UserId,
                        JobSteps       = new List <MIFileUpload.JobQueue.JobStep>()
                    };
                    foreach (UcbManagementInformation.Server.DataAccess.JobStep step in uploadjob.JobSteps.OrderBy(x => x.StepOrder))
                    {
                        jobToReturn.JobSteps.Add(new MIFileUpload.JobQueue.JobStep(step.StartTime, step.EndTime, (JobStepStatus)Enum.Parse(typeof(JobStepStatus), step.Status))
                        {
                            Code      = step.Code,
                            Category  = step.Category,
                            Name      = step.Name,
                            ParentJob = jobToReturn,
                            Order     = step.StepOrder
                        });
                    }
                    return(jobToReturn);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(job);
            }
        }
Ejemplo n.º 15
0
        public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
        {
            DomainService domainService;

            if (typeof(ReportWizardService) == domainServiceType)
            {
                #region ReportWizardService

                IUnitOfWork uow    = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation");
                IUnitOfWork UcbUow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("Ucb");

                domainService = new ReportWizardService(SimpleServiceLocator.Instance.Get <IReportingServices>(),
                                                        uow, UcbUow,
                                                        DataAccessUtilities.RepositoryLocator <IDataTableRelationshipRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <DataCategory> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IDataTableRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <Report> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <MCUser> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IReportGroupRepository>(uow.ObjectContext),
                                                        //second repository for read
                                                        DataAccessUtilities.RepositoryLocator <IReportGroupRepository>(),
                                                        DataAccessUtilities.RepositoryLocator <IDataItemRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UserReportGroup> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IDataModelRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IDataTableJoinRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IDataTableRelationshipJoinRepository>(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <Filter> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ReportChart> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ReportChartSery> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ReportDataTableJoin> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ReportItem> >(uow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbRepository <ReportCategory> >(UcbUow.ObjectContext),
                                                        DataAccessUtilities.RepositoryLocator <IUcbRepository <StandardReport> >(UcbUow.ObjectContext));

                #endregion
            }

            else if (typeof(AlertService) == domainServiceType)
            {
                IUnitOfWork uow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation");

                domainService = new AlertService(DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <Alert> >(uow.ObjectContext),
                                                 DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <AlertUser> > (uow.ObjectContext), uow);
            }
            else if (typeof(MIUploadService) == domainServiceType)
            {
                IUnitOfWork uow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation");

                domainService = new MIUploadService(uow,
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ProviderOrganisation> >(uow.ObjectContext),
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <InputFileHistory> >(uow.ObjectContext),
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <Alert> >(uow.ObjectContext),
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <AlertUser> >(uow.ObjectContext),
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <MCUser> >(uow.ObjectContext),
                                                    DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UploadJobQueue> >(uow.ObjectContext)
                                                    );
            }
            //else if (typeof(UcbPublishService) == domainServiceType)
            //{
            //    IUnitOfWork UcbUow = SimpleServiceLocator.Instance.Get<IUnitOfWork>("Ucb");
            //    domainService = new UcbPublishService(SimpleServiceLocator.Instance.Get<IReportingServices>(), UcbUow,
            //    DataAccessUtilities.RepositoryLocator<IUcbRepository<ReportCategory>>(UcbUow.ObjectContext),
            //    DataAccessUtilities.RepositoryLocator<IUcbRepository<StandardReport>>(UcbUow.ObjectContext)
            //    );

            //}
            else
            {
                domainService = (DomainService)Activator.CreateInstance(domainServiceType);
            }

            domainService.Initialize(context);
            return(domainService);
        }
        public void UpdateUser(UcbManagementInformation.Server.DataAccess.MCUser user)
        {
            // Ensure the user data that will be modified represents the currently
            // authenticated identity
            if ((this.ServiceContext.User == null) ||
                (this.ServiceContext.User.Identity == null) ||
                !string.Equals(this.ServiceContext.User.Identity.Name, user.Name, System.StringComparison.Ordinal))
            {
                throw new UnauthorizedAccessException("You are only authorized to modify your own profile.");
            }

            //this.ObjectContext.Users.AttachAsModified(user, this.ChangeSet.GetOriginal(user));

            IUcbManagementInformationRepository <UcbManagementInformation.Server.DataAccess.MCUser> UserRep = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UcbManagementInformation.Server.DataAccess.MCUser> >(this.ObjectContext);

            UserRep.Attach(user);
            UserRep.SaveChanges();
        }
        public FileUploadJob(Guid code, string fileName, string providerKey, string userID, string webPath, DateTime?added, DateTime?started, DateTime?ended, string description)
        {
            Code           = code;
            ProviderKey    = providerKey;
            UniqueFileName = fileName;
            AddedTime      = added;
            StartTime      = started;
            EndTime        = ended;
            Description    = description;
            //GET Schema file paths from configuration
            _schema        = webPath + ConfigurationManager.AppSettings["ParticipantSchema"];
            _mappingSchema = webPath + ConfigurationManager.AppSettings["ParticipantMappingSchema"];

            //Get Connection string from configuration
            _connectionString = ConfigurationManager.ConnectionStrings["MIStagingConnectionString"].ConnectionString;

            //set private variables
            IUcbManagementInformationRepository <ProviderOrganisation> providerOrganisationRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <ProviderOrganisation> >();
            ProviderOrganisation providerOrganisationItem =
                providerOrganisationRepository.First(x => x.KeyValue == ProviderKey);

            _providingOrganistaionCode = providerOrganisationItem.Code;
            _fileType = "Participant";
            FileInfo DataFileInfoItem = new FileInfo(UniqueFileName);

            _fileLength = DataFileInfoItem.Length;

            _userID  = userID;
            UserId   = userID;
            JobSteps = new List <JobStep>()
            {
                new JobStep("SchemaValidation", "Schema Validation", this, 1),
                new JobStep("DeleteFromLoadingArea", "DeleteFromLoadingArea", this, 2),
                new JobStep("BulkUpload", "Bulk Load", this, 3),
                new JobStep("CopyBulkLoadedData", "CopyBulkLoadedData", this, 4),
                new JobStep("ValidateParticipantDuplicates", "Validate Participant", this, 5),
                new JobStep("ValidateAgreementRegion", "Validate Participant", this, 6),
                new JobStep("ValidateParticipantPostCode", "Validate Participant", this, 7),
                new JobStep("ValidateLeaver", "Validate Participant", this, 8),
                new JobStep("ValidateLeavingDate", "Validate Participant", this, 9),
                new JobStep("ValidateStartDate", "Validate Participant", this, 10),
                new JobStep("LoadParticipantMessages", "Validate Participant", this, 11),
                new JobStep("ValidatePreviousLoad", "Validate Participant", this, 12),
                new JobStep("UpdateParticipantCounts", "Validate Participant", this, 13)
            };
        }
        /// <summary>
        /// Constructs a MatrixReport
        /// </summary>
        /// <param name="reportConstituents">A ReportDefinitionBusinessObject
        /// encapsulating the input parameters.</param>
        public MatrixReport(ReportDefinitionBusinessObject reportConstituents, string modelDataSource)
        {
            _dataSource = modelDataSource;
            //switch (model)
            //{
            //    case "INES":
            //        _dataSource = "ESF2007";
            //        break;
            //    case "MI Participant":
            //        _dataSource = "ESFMIBUSINESSDATA";
            //        break;
            //    case "Managing Authority":
            //        _dataSource = "MANAGINGAUTHORITYDATA";
            //        break;

            //}
            //_dbConnectionString
            //    = ConfigurationManager.ConnectionStrings["BusinessDataConnectionString"].ConnectionString;
            CurrentDataModel = DataAccessUtilities.RepositoryLocator <IDataModelRepository>().Single(x => x.DatasourceName == _dataSource,
                                                                                                     "DataTables",
                                                                                                     "DataTables.DataItems",
                                                                                                     "DataCategories",
                                                                                                     "DataTableJoins",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelashionship",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelashionship.DataTable",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelashionship.DataTable1");
            _textboxStyle = new ReportingServicesStyle(
                ReportingServicesStyle.TextBoxStyle.MatrixReport);

            _cornerTextboxStyle = new ReportingServicesStyle(
                ReportingServicesStyle.TextBoxStyle.MatrixReportCorner);

            _columnTotalDataItemList = reportConstituents.ColumnTotalDataItems;
            _rowTotalDataItemList    = reportConstituents.RowTotalDataItems;

            if (reportConstituents.IsOuterJoin == false)
            {
                _joinMethod = " FULL OUTER JOIN ";
            }
            else
            {
                _joinMethod = " INNER JOIN ";
            }


            // Temporary ArrayList used when instantiating the Dataset
            List <DataItem> TempGroupList = new List <DataItem>(reportConstituents.RowTotalDataItems);

            TempGroupList.AddRange(reportConstituents.ColumnTotalDataItems);

            // Initialise the querywrappers
            _mainQueryWrapper = new QueryWrapper(reportConstituents.SelectedDataItems, TempGroupList,
                                                 reportConstituents.FilterList, reportConstituents.ParameterDataItems, false, reportConstituents.JoinList, CurrentDataModel);

            //30/06/05 LL - TIR0163 Parameter query needs to be build for each data item
            foreach (DataItem CurrentParameter in reportConstituents.ParameterDataItems)
            {
                if (!CurrentParameter.IsValueType)
                {
                    List <DataItem> ParameterList = new List <DataItem>();
                    ParameterList.Add(CurrentParameter);
                    _parameterQueryWrapperArrayList.Add(new QueryWrapper(ParameterList,
                                                                         null, null, null, true, null, CurrentDataModel));
                }
            }

            // Iteration counter used in MatrixRow and MatrixStaticRow instantiations
            int MatrixRowCount = 0;

            /* Used when instantiating ColumnGroup and RowGroup lists:
             * The bools Denote if current item is first in list, so should be set to
             * false after first item dealt with.
             * The PrevItemName is the name of the item previous to the current item.
             */
            bool   IsFirstInColGroupList = true, IsFirstInRowGroupList = true;
            string PrevItemName = "";

            // MatrixRow
            foreach (DataItem SelectedItem in reportConstituents.SelectedDataItems)
            {
                if (!reportConstituents.RowTotalDataItems.Contains(SelectedItem) &&
                    !reportConstituents.ColumnTotalDataItems.Contains(SelectedItem))
                {
                    _matrixRowList.Add(
                        new MatrixRow("MatrixRowTextBox" + MatrixRowCount, SelectedItem, CurrentDataModel));
                }

                MatrixRowCount++;
            }

            // MatrixDynamicColumnGrouping
            foreach (DataItem ColumnItem in reportConstituents.ColumnTotalDataItems)
            {
                if (IsFirstInColGroupList)
                {
                    // To ensure drilldown groupname is unique in case of data items with same name,
                    // concatenate the tablename and itemname
                    DataTable SubtotalDataTable
                        = CurrentDataModel.DataTables.Single(x => x.Code == ColumnItem.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(ColumnItem.DataTableCode);
                    string SubtotalTableName = SubtotalDataTable.Name;
                    string SubtotalName      = SubtotalTableName + ColumnItem.Name + "Subtotal";

                    _dynamicColumnGroupingList.Add(
                        new MatrixDynamicColumnGrouping(ColumnItem, SubtotalName, true, CurrentDataModel));
                    IsFirstInColGroupList = false;
                }
                else
                {
                    _dynamicColumnGroupingList.Add(
                        new MatrixDynamicColumnGrouping(ColumnItem, PrevItemName, false, CurrentDataModel));
                }

                // To ensure field name is unique in case of data items with same name,
                // concatenate the tablename and itemname
                DataTable ThisDataTable = CurrentDataModel.DataTables.Single(x => x.Code == ColumnItem.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(ColumnItem.DataTableCode);
                string    TableName     = ThisDataTable.Name;
                PrevItemName = TableName + ColumnItem.Name;
            }

            // MatrixDynamicRowGrouping
            foreach (DataItem RowItem in reportConstituents.RowTotalDataItems)
            {
                if (IsFirstInRowGroupList)
                {
                    // To ensure drilldown groupname is unique in case of data items with same name,
                    // concatenate the tablename and itemname
                    DataTable SubtotalDataTable
                        = CurrentDataModel.DataTables.Single(x => x.Code == RowItem.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(RowItem.DataTableCode);
                    string SubtotalTableName = SubtotalDataTable.Name;
                    string SubtotalName      = SubtotalTableName + RowItem.Name + "Subtotal";

                    _dynamicRowGroupingList.Add(
                        new MatrixDynamicRowGrouping(RowItem, SubtotalName, true, CurrentDataModel));
                    IsFirstInRowGroupList = false;
                }
                else
                {
                    _dynamicRowGroupingList.Add(
                        new MatrixDynamicRowGrouping(RowItem, PrevItemName, false, CurrentDataModel));
                }

                // To ensure field name is unique in case of data items with same name,
                // concatenate the tablename and itemname
                DataTable ThisDataTable = CurrentDataModel.DataTables.Single(x => x.Code == RowItem.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(RowItem.DataTableCode);
                string    TableName     = ThisDataTable.Name;
                PrevItemName = TableName + RowItem.Name;
            }

            // MatrixStaticRow
            MatrixRowCount = 0;
            foreach (DataItem SelectedItem in reportConstituents.SelectedDataItems)
            {
                if (!(reportConstituents.RowTotalDataItems.Contains(SelectedItem)) &&
                    !(reportConstituents.ColumnTotalDataItems.Contains(SelectedItem)))
                {
                    _matrixStaticRowList.Add(new MatrixStaticRow(
                                                 "MatrixStaticRowTextBox" + MatrixRowCount, SelectedItem, CurrentDataModel));
                }

                MatrixRowCount++;
            }

            // Dataset
            _datasetList.Add(new Dataset(reportConstituents.SelectedDataItems, _matrixDataSetName,
                                         _mainQueryWrapper, CurrentDataModel));

            //30/06/05 LL - TIR0163 Parameter query needs to be build for each data item
            int i = 0;

            foreach (DataItem Item in reportConstituents.ParameterDataItems)
            {
                if (!Item.IsValueType)
                {
                    // We only require a query for the current data item, so put it into
                    // an arraylist to pass to the Dataset constructor.
                    List <DataItem> ParameterList = new List <DataItem>();
                    ParameterList.Add(Item);

                    // To ensure this parameter's datasetname is unique in case of data items
                    // with same name, concatenate the tablename and itemname
                    DataTable ThisDataTable = CurrentDataModel.DataTables.Single(x => x.Code == Item.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(Item.DataTableCode);
                    string    TableName     = ThisDataTable.Name;

                    _datasetList.Add(new Dataset(ParameterList, TableName + Item.Name + "Parameter",
                                                 (QueryWrapper)_parameterQueryWrapperArrayList[i], CurrentDataModel));
                    _parameterName    = TableName + Item.Name;
                    _parameterCaption = Item.Caption;
                    _parameterName    = "=\"Selected " + _parameterCaption + " :\"+Parameters!" + _parameterName + ".Value";
                    _parameterList.Add(_parameterName);
                    i++;
                }
            }


            // ReportParameter
            foreach (DataItem ParameterItem in reportConstituents.ParameterDataItems)
            {
                _reportParameterList.Add(new ReportParameter(ParameterItem, CurrentDataModel));
            }

            //Report Description DBS
            _reportDescription = "Report Description : " + reportConstituents.ReportDescription + " . Show only data with a common denominator = " + reportConstituents.IsOuterJoin.ToString();

            foreach (ReportFilterBusinessObject CurrentFilter in reportConstituents.FilterList)
            {
                //TODO: Code Review Issue 11/05/05: Do not use 'my' in variable names.
                //Choose a meaningful name. Pascal casing for variables.
                // Done 24/05/2005
                Guid     DataItemCode = Guid.Parse(CurrentFilter.DataItemCode);
                DataItem CurrentItem  = CurrentDataModel.DataTables.SelectMany(x => x.DataItems).Single(y => y.Code == DataItemCode); //DataAccessUtilities.RepositoryLocator<IDataItemRepository>().GetByCode((CurrentFilter.DataItemCode));

                DataTable CurrentTable = CurrentDataModel.DataTables.Single(x => x.Code == CurrentItem.DataTableCode);                //DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(CurrentItem.DataTableCode);

                //25/08/05 LL - TIR0289 convert 'Current Month' to appropriate data format
                if (CurrentFilter.FilterValue == CURRENTMONTH)
                {
                    CurrentFilter.FilterValue = DateUtility.GetCurrentYearMonth();
                }
                ReportFilterBusinessObject ReportFilter = new ReportFilterBusinessObject();
                ReportFilter.DataItemCaption = CurrentItem.Caption;
                ReportFilter.Operand         = CurrentFilter.Operand;
                ReportFilter.FilterValue     = CurrentFilter.FilterValue;
                _filterItemList.Add(ReportFilter);
            }

            // Initialise the MemoryStream and the XmlWriter
            _memoryStream = new MemoryStream();
            _xmlWriter    = new XmlTextWriter(
                _memoryStream, Encoding.UTF8);
            // Either of the lines below may be used as alternative outputs for debugging
            //_stream, Encoding.UTF8);
            // Console.Out);
        }
Ejemplo n.º 19
0
        private void i9ComboBox_DropDownOpened(object sender, EventArgs e)
        {
            i9ComboBox i9cb = (i9ComboBox)sender;

            if (!String.IsNullOrEmpty(i9cb.i9BindCodeSetName) && i9cb.Items.Count <= 0)
            {
                ClientDataAccess cda = new ClientDataAccess();
                DataTable        dt  = cda.GetDataTable("SELECT Code, CodeText FROM i9Code WHERE Enabled <> 0 AND CodeSetName = " + DataAccessUtilities.GetDBStr(i9cb.i9BindCodeSetName) + " Order By CodeText ", "i9Code");
                i9ComboBox.PopulateCombobox(i9cb, dt, "i9Code");
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Constructs a TabularReport.
        /// </summary>
        /// <param name="reportConstituents">A ReportDefinitionBusinessObject
        /// encapsulating the input parameters.</param>
        public TabularReport(ReportDefinitionBusinessObject reportConstituents, string modelDataSource)
        {
            _dataSource = modelDataSource;
            //switch (model)
            //{
            //    case "INES":
            //        _dataSource = "ESF2007";
            //        break;
            //    case "MI Participant":
            //        _dataSource = "ESFMIBUSINESSDATA";
            //        break;
            //    case "Managing Authority":
            //        _dataSource = "MANAGINGAUTHORITYDATA";
            //        break;

            //}
            //_dbConnectionString
            //    = ConfigurationManager.ConnectionStrings["BusinessDataConnectionString"].ConnectionString;

            // When instantiating the TableGroups, we must record whether we are
            // instantiating the first group or not AND the name of the group previous
            // to the one we are currently dealing with.

            CurrentDataModel = DataAccessUtilities.RepositoryLocator <IDataModelRepository>().Single(x => x.DatasourceName == _dataSource,
                                                                                                     "DataTables",
                                                                                                     "DataTables.DataItems",
                                                                                                     "DataCategories",
                                                                                                     "DataTableJoins",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelationship",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelationship.DataTable",
                                                                                                     "DataTableJoins.DataTableRelationshipJoins.DataTableRelationship.DataTable1");

            bool   IsFirstGroup       = true;
            string PreviousGroupName  = "";
            bool   IsDataMapDisplayed = false;

            IsDataMapDisplayed = reportConstituents.IsDataMapDisplayed;
            _noOfFilters       = reportConstituents.FilterList.Count;
            //Table Join
            _isDrillDown       = reportConstituents.IsDrillDown;
            _isPageOnFirstItem = reportConstituents.IsPageBreak;
            if (reportConstituents.IsOuterJoin == false)
            {
                _joinMethod = " FULL OUTER JOIN ";
            }
            else
            {
                _joinMethod = " INNER JOIN ";
            }


            // Get the selectedDataItems
            _selectedDataItems = reportConstituents.SelectedDataItems;
            _fieldDataItems    = reportConstituents.FieldDataItems;
            // Instantiate the querywrapper for the main query
            _mainQueryWrapper = new QueryWrapper(reportConstituents.SelectedDataItems,
                                                 reportConstituents.RowTotalDataItems, reportConstituents.FilterList,
                                                 reportConstituents.ParameterDataItems, false, reportConstituents.JoinList, CurrentDataModel);

            // Instantiate the querywrapper for the parameter query
            //30/06/05 LL - TIR0163 Parameter query needs to be build for each data item
            foreach (DataItem CurrentParameter in reportConstituents.ParameterDataItems)
            {
                if (!CurrentParameter.IsValueType)
                {
                    List <DataItem> ParameterList = new List <DataItem>();
                    ParameterList.Add(CurrentParameter);
                    _parameterQueryWrapperArrayList.Add(new QueryWrapper(ParameterList,
                                                                         null, null, null, true, null, CurrentDataModel));
                }
            }

            // Call the constructors of each of the report constituents
            // TableHeader
            _tableHeader = new TableHeader(reportConstituents.FieldDataItems, DataAccessUtilities.RepositoryLocator <IDataTableRepository>(), CurrentDataModel);


            // TableFooter

            #region Join Description Appended
            //Add any joins in the list that are in the JoinList
            StringBuilder JoinDescription = new StringBuilder();
            foreach (ReportDataTableJoin currentReportJoin in reportConstituents.JoinList)
            {
                DataTableJoin currentJoin     = CurrentDataModel.DataTableJoins.Single(x => x.Code == currentReportJoin.DataTableJoinCode);
                string        fromTablePlural = currentJoin.FromTable.Substring(currentJoin.FromTable.Length - 1).ToUpper() == "Y" ? currentJoin.FromTable.Substring(0, currentJoin.FromTable.Length - 1) + "ies" : currentJoin.FromTable + "s";
                string        toTablePlural   = currentJoin.ToTable.Substring(currentJoin.ToTable.Length - 1).ToUpper() == "Y" ? currentJoin.ToTable.Substring(0, currentJoin.ToTable.Length - 1) + "ies" : currentJoin.ToTable + "s";

                switch (currentReportJoin.JoinType)
                {
                case "INNER":
                    JoinDescription.Append("INNER: Select only " + fromTablePlural + " that have related " + toTablePlural + " and " +
                                           "select only " + toTablePlural + " that have related " + fromTablePlural + Environment.NewLine);
                    break;

                case "LEFT":
                    JoinDescription.Append("LEFT: Select all " + fromTablePlural + " and only related " +
                                           toTablePlural + Environment.NewLine);
                    break;

                case "RIGHT":
                    JoinDescription.Append("RIGHT: Select all " + toTablePlural + " and only related " +
                                           fromTablePlural + Environment.NewLine);
                    break;

                case "FULL":
                    JoinDescription.Append("FULL: Select all " + fromTablePlural + " and " +
                                           toTablePlural + " with or without relations" + Environment.NewLine);
                    break;
                }
            }
            #endregion
            _tableFooter = new TableFooter(reportConstituents.ReportDescription + Environment.NewLine + JoinDescription.ToString(), reportConstituents.FieldDataItems.Count.ToString(), reportConstituents.FilterList, CurrentDataModel);

            // TableGroup


            // This list contains data items that are not grouped by, but are moved into
            // being displayed within a group by the TableGroup constructor.
            List <DataItem> DataItemsPromotedToGroup = new List <DataItem>();

            // This list contains the extra groups added by the wrapper. They are ordered, so
            // each group's index in the list (plus 1) is its grouping level.
            List <DataItem> NewGroupList = _mainQueryWrapper.NewGroupList;

            foreach (DataItem Item in reportConstituents.RowTotalDataItems)
            {
                if (reportConstituents.IsDrillDown)
                {
                    if (IsFirstGroup)
                    {
                        _tableGroupList.Add(new TableGroup(reportConstituents.FieldDataItems,
                                                           reportConstituents.RowTotalDataItems, Item, "", DataItemsPromotedToGroup,
                                                           _mainQueryWrapper.NewGroupList, IsDataMapDisplayed, CurrentDataModel));
                        IsFirstGroup = false;
                    }
                    else
                    {
                        _tableGroupList.Add(new TableGroup(reportConstituents.FieldDataItems,
                                                           reportConstituents.RowTotalDataItems, Item, PreviousGroupName,
                                                           DataItemsPromotedToGroup, _mainQueryWrapper.NewGroupList, IsDataMapDisplayed, CurrentDataModel));
                    }
                }
                else
                {
                    _tableGroupList.Add(new TableGroup(reportConstituents.FieldDataItems,
                                                       reportConstituents.RowTotalDataItems, Item, "", DataItemsPromotedToGroup,
                                                       _mainQueryWrapper.NewGroupList, IsDataMapDisplayed, CurrentDataModel));
                }

                // To ensure grouping name is unique in case of data items with same name,
                // concatenate the tablename and itemname
                DataTable ThisDataTable = CurrentDataModel.DataTables.Single(x => x.Code == Item.DataTableCode);            //DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(Item.DataTableCode);
                string    TableName     = ThisDataTable.Name;
                PreviousGroupName = TableName + Item.Name;
            }

            // TableDetails
            if (reportConstituents.IsDrillDown)
            {
                _tableDetails = new TableDetails(reportConstituents.FieldDataItems,
                                                 reportConstituents.RowTotalDataItems, PreviousGroupName,
                                                 DataItemsPromotedToGroup, IsDataMapDisplayed, CurrentDataModel);
            }
            else
            {
                _tableDetails = new TableDetails(reportConstituents.FieldDataItems,
                                                 reportConstituents.RowTotalDataItems, "", DataItemsPromotedToGroup, reportConstituents.IsDataMapDisplayed, CurrentDataModel);
            }

            // IsSummaryReport
            _isSummaryReport = reportConstituents.IsSummaryReport;
            // Dataset for main query
            _datasetList.Add(new Dataset(reportConstituents.SelectedDataItems, "Table",
                                         _mainQueryWrapper, CurrentDataModel));

            //30/06/05 LL - TIR0163 Parameter query needs to be build for each data item
            int i = 0;
            foreach (DataItem Item in reportConstituents.ParameterDataItems)
            {
                // Add a dataset for each reference-type parameter
                if (!Item.IsValueType || Item.DataType == "bit")
                {
                    // We only require a query for the current data item, so put it into
                    // an arraylist to pass to the Dataset constructor.
                    List <DataItem> ParameterList = new List <DataItem>();
                    ParameterList.Add(Item);

                    // To ensure this parameter's datasetname is unique in case of data items
                    // with same name, concatenate the tablename and itemname
                    DataTable ThisDataTable = CurrentDataModel.DataTables.Single(x => x.Code == Item.DataTableCode);//DataAccessUtilities.RepositoryLocator<IDataTableRepository>().GetByCode(Item.DataTableCode);
                    string    TableName     = ThisDataTable.Name;
                    if (Item.DataType != "bit")
                    {
                        _datasetList.Add(new Dataset(ParameterList, TableName + Item.Name + "Parameter",
                                                     (QueryWrapper)_parameterQueryWrapperArrayList[i], CurrentDataModel));
                        i++;
                    }
                    _parameterName    = TableName + Item.Name;
                    _parameterCaption = Item.Caption;
                    _parameterName    = "=\"Selected " + _parameterCaption + " :\"+Parameters!" + _parameterName + ".Label";
                    _parameterList.Add(_parameterName);
                }

                // ReportParameter
                _reportParametersList.Add(new ReportParameter(Item, CurrentDataModel));
            }
            reportConstituents.ChartList = (from x in reportConstituents.ChartList orderby x.SortOrder select x).ToList();

            foreach (ReportChartBusinessObject ChartItem in reportConstituents.ChartList)
            {
                Guid     CategoryDataItemCode = Guid.Parse(ChartItem.CategoryDataItemCode);
                DataItem CategoryDataItem     = CurrentDataModel.DataTables.SelectMany(x => x.DataItems).Single(y => y.Code == CategoryDataItemCode);//DataAccessUtilities.RepositoryLocator<IDataItemRepository>().GetByCode(CategoryDataItemCode);


                List <DataItem> ChartSeriesDataItems = new List <DataItem>();
                ChartItem.ChartSeriesList = (from x in ChartItem.ChartSeriesList orderby x.SortOrder select x).ToList();
                foreach (ReportChartSeriesBusinessObject currentSeries in ChartItem.ChartSeriesList)
                {
                    Guid seriesDataItemCode = Guid.Parse(currentSeries.SeriesDataItemCode);

                    DataItem SeriesDataItem = CurrentDataModel.DataTables.SelectMany(x => x.DataItems).Single(y => y.Code == seriesDataItemCode);//DataAccessUtilities.RepositoryLocator<IDataItemRepository>().GetByCode(seriesDataItemCode);

                    ChartSeriesDataItems.Add(SeriesDataItem);
                }

                Chart newChart = new Chart(ChartItem.Type, CategoryDataItem, "TableDataSet", ChartSeriesDataItems[0].DataType, ChartSeriesDataItems, ChartItem.SortOrder, ChartItem.Description, CurrentDataModel);
                _chartList.Add(newChart);
            }

            // Initialise the MemoryStream and the XmlWriter
            _memoryStream = new MemoryStream();
            _xmlWriter    = new XmlTextWriter(
                _memoryStream, Encoding.UTF8);
            // Either of the lines below may be used as alternative outputs for debugging
            // _stream, Encoding.UTF8);
            // Console.Out);
        }
Ejemplo n.º 21
0
        public IEnumerable <JobBase> GetCompleteFileUploadJobs()
        {
            List <JobBase> listToReturn = new List <JobBase>();
            DateTime       Yesterday    = DateTime.Now.AddDays(-1);
            IUcbManagementInformationRepository <UploadJobQueue> uploadJobQueueRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UploadJobQueue> >();
            var uploadjobList = uploadJobQueueRepository.Find(x => x.TimeAdded > Yesterday && (x.Status == "Succeeded" || x.Status == "Failed"), "JobSteps").OrderByDescending(x => x.TimeStarted);

            foreach (var uploadjob in uploadjobList)
            {
                var     descSplit   = uploadjob.JobDescription.Split('|');
                JobBase jobToReturn = new JobBase()
                {
                    Code        = uploadjob.Code,
                    AddedTime   = uploadjob.TimeAdded,
                    Description = uploadjob.JobDescription,
                    StartTime   = uploadjob.TimeStarted,
                    EndTime     = uploadjob.EndTime,
                    Status      = (JobStatus)Enum.Parse(typeof(JobStatus), uploadjob.Status),
                    UserId      = uploadjob.UserId,
                    JobSteps    = new List <MIFileUpload.JobQueue.JobStep>()
                };
                foreach (UcbManagementInformation.Server.DataAccess.JobStep step in uploadjob.JobSteps.OrderBy(x => x.StepOrder))
                {
                    jobToReturn.JobSteps.Add(
                        new MIFileUpload.JobQueue.JobStep(step.StartTime, step.EndTime, (JobStepStatus)Enum.Parse(typeof(JobStepStatus), step.Status))
                    {
                        Code      = step.Code,
                        Category  = step.Category,
                        Name      = step.Name,
                        ParentJob = jobToReturn,
                        Order     = step.StepOrder
                    });
                }
                listToReturn.Add(jobToReturn);
            }
            return(listToReturn);
            // return listToReturn;
        }
        // the main work loop
        public void Run()
        {
            // initialize the flag that keeps the loop going
            IsOn = true;
            // start
            while (IsOn)
            {
                try
                {
                    // get the next pending job, otherwise the default one
                    AtomicAction("Dequeue", Guid.Empty);
                    // execute the job and retrieve the delay value
                    if (CurrentJob != null)
                    {
                        CurrentJob.Status = JobStatus.Running;
                        IUnitOfWork uow = SimpleServiceLocator.Instance.Get <IUnitOfWork>("UcbManagementInformation");

                        IUcbManagementInformationRepository <UploadJobQueue> uploadJobQueueRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UploadJobQueue> >(uow.ObjectContext);
                        IUcbManagementInformationRepository <UcbManagementInformation.Server.DataAccess.JobStep> jobStepRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <UcbManagementInformation.Server.DataAccess.JobStep> >(uow.ObjectContext);
                        IUcbManagementInformationRepository <Alert>     alertRepository     = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <Alert> >(uow.ObjectContext);
                        IUcbManagementInformationRepository <AlertUser> alertUserRepository = DataAccessUtilities.RepositoryLocator <IUcbManagementInformationRepository <AlertUser> >(uow.ObjectContext);

                        var waitingJob = uploadJobQueueRepository.First(x => x.Code == CurrentJob.Code);
                        waitingJob.Status      = "Running";
                        waitingJob.TimeStarted = DateTime.Now;
                        uploadJobQueueRepository.Update(waitingJob);
                        uow.Commit();

                        int rv = CurrentJob.RunJob();

                        using (uow)
                        {
                            //Log the job and job steps;
                            waitingJob = uploadJobQueueRepository.First(x => x.Code == CurrentJob.Code);
                            uploadJobQueueRepository.Update(waitingJob);

                            if (rv == 0)
                            {
                                CurrentJob.Status  = JobStatus.Succeeded;
                                waitingJob.EndTime = DateTime.Now;
                                waitingJob.Status  = "Succeeded";
                            }
                            else
                            {
                                CurrentJob.Status  = JobStatus.Failed;
                                waitingJob.EndTime = DateTime.Now;
                                waitingJob.Status  = "Failed";
                            }
                            uploadJobQueueRepository.Update(waitingJob);
                            foreach (JobStep currentStep in CurrentJob.JobSteps)
                            {
                                UcbManagementInformation.Server.DataAccess.JobStep stepToSave = new UcbManagementInformation.Server.DataAccess.JobStep()
                                {
                                    Code               = currentStep.Code,
                                    Category           = currentStep.Category,
                                    EndTime            = currentStep.EndTime,
                                    StartTime          = currentStep.StartTime,
                                    Status             = currentStep.Status.ToString(),
                                    Name               = currentStep.Name,
                                    UploadJobQueueCode = CurrentJob.Code,
                                    StepOrder          = currentStep.Order
                                };
                                jobStepRepository.Add(stepToSave);
                            }
                            var alertToUpdate = alertRepository.FirstOrDefault(x => x.RelatedEntityCode == CurrentJob.Code);
                            if (alertToUpdate != null)
                            {
                                alertToUpdate.Status        = "Completed";
                                alertToUpdate.CompletedDate = DateTime.Now;
                                alertToUpdate.Message       = "File upload job : " + waitingJob.JobDescription + " has finished. ";
                                if (CurrentJob.Status == JobStatus.Succeeded)
                                {
                                    alertToUpdate.Message += "The Job was successfull.";
                                }
                                else
                                {
                                    alertToUpdate.Message += "The Job failed.";
                                    var failedStep = CurrentJob.JobSteps.FirstOrDefault(x => x.Status == JobStepStatus.Failed);
                                    if (failedStep != null)
                                    {
                                        alertToUpdate.Message += " The failing step was " + failedStep.Name;
                                    }
                                }
                            }
                            uow.Commit();
                        }

                        if (CurrentJob.UnhandledException != null)
                        {
                            ExceptionPolicy.HandleException(CurrentJob.UnhandledException, ExceptionHandlingPolicies.UnhandledException);
                        }
                        //Job completed and saved to DB so remove from memory!!!!
                        CurrentJob = null;
                    }
                    // check to make sure a stop hasn't been issued
                    // and that the job calls for a wait
                    if (IsOn && sleepTime > 0)
                    {
                        // wait for the time specified
                        System.Threading.Thread.Sleep(sleepTime);
                    }
                }
                catch (Exception ex)
                {
                    //publish ex;

                    ExceptionPolicy.HandleException(ex, ExceptionHandlingPolicies.UnhandledException);
                }
            }
        }