Exemplo n.º 1
0
        public void DeleteExpiredDocument()
        {
            DateTime expirationDate = DateTime.Today.AddDays(_days);

            List <PrintLogModel> printLogModels = printLogDb.Models
                                                  .Where(p => p.PrintedDateTime != null && p.PrintedDateTime < expirationDate && p.Status != PrintModel.archivedStatus)
                                                  .ToList();

            if (printLogModels != null)
            {
                foreach (PrintLogModel printLogModel in printLogModels)
                {
                    if (printLogModel.FileLocation.StartsWith(_localBase))
                    {
                        try
                        {
                            File.Delete(printLogModel.FileLocation);
                            printLogModel.Status       = PrintModel.archivedStatus;
                            printLogModel.ErrorMessage = null;
                        }
                        catch (Exception e)
                        {
                            printLogModel.ErrorMessage = "Archive failed. " + e.Message;
                        }
                        printLogDb.Entry(printLogModel).State = EntityState.Modified;
                    }
                }
                printLogDb.SaveChanges(_userId);
            }
        }
Exemplo n.º 2
0
        public static bool AddJob(FileHelper fileModel, string entityName, string primaryKey, int printerId, string userId)
        {
            string printDirectory = FileDirectoryService.GetPathByName("PrintServiceDirectory");
            BaseModelContext <PrintModel> printDb = new BaseModelContext <PrintModel>();
            PrintModel printModel = new PrintModel()
            {
                EntityName   = entityName,
                PrimaryKey   = primaryKey,
                PrinterId    = printerId,
                FileLocation = "C:\\Temp",
                Status       = PrintModel.newStatus
            };

            printDb.Models.Add(printModel);
            printDb.SaveChanges(userId);
            if (printModel.Id > 0)
            {
                string printServicePath = printDirectory + printModel.Id.ToString() + "-" + fileModel.FileName;
                if (fileModel.CopyTo(printServicePath))
                {
                    printModel.Status       = PrintModel.queuedStatus;
                    printModel.FileLocation = printServicePath;
                    printDb.Entry(printModel);
                    printDb.SaveChanges(userId);
                    return(true);
                }
                else
                {
                    printDb.Models.Remove(printModel);
                    printDb.SaveChanges(userId);
                }
            }
            return(false);
        }
Exemplo n.º 3
0
        public ActionResult DeleteAvatar()
        {
            BaseModelContext <UserModel> userDb = new BaseModelContext <UserModel>();
            UserModel user = userDb.Models.Find(User.Identity.GetUserId());

            if (user != null)
            {
                user.Avatar = null;
                userDb.Entry(user);
                userDb.SaveChanges();
                FileHelper fileModel = new FileHelper(user.Id + ".jpg", user.Id);
                fileModel.Delete();
            }
            return(Redirect(Url.Action("UpdateProfile", "Manage")));
        }
Exemplo n.º 4
0
        public static void GetPrinterTrays(PrinterModel printerModel)
        {
            if (string.IsNullOrWhiteSpace(printerModel.Name))
            {
                return;
            }

            BaseModelContext <PrinterTrayModel> printerTrayDb = new BaseModelContext <PrinterTrayModel>();
            PrintDocument         printDocument = new PrintDocument();
            List <SelectListItem> trayOptions   = new List <SelectListItem>();

            printDocument.PrinterSettings.PrinterName = printerModel.Name.Trim();
            Dictionary <int, string> paperSources = new Dictionary <int, string>();

            if (printDocument.PrinterSettings.IsValid)
            {
                //Get Trays for this printer
                List <PrinterTrayModel> printerTrays = printerTrayDb.Models.Where(t => t.PrinterId == printerModel.Id).ToList();
                //Add printer trays
                int i = 0;
                foreach (PaperSource paperSource in printDocument.PrinterSettings.PaperSources)
                {
                    paperSources[i] = paperSource.SourceName;
                    PrinterTrayModel exists = printerTrays.Where(t => t.Index == i && t.Name == paperSource.SourceName).FirstOrDefault();
                    if (exists == null)
                    {
                        printerTrayDb.Models.Add(new PrinterTrayModel()
                        {
                            PrinterId = printerModel.Id,
                            Index     = i,
                            Name      = paperSource.SourceName
                        });
                    }
                    i++;
                }
                //Remove Printer Trays
                foreach (PrinterTrayModel printerTrayModel in printerTrays)
                {
                    if (!(paperSources.ContainsKey(printerTrayModel.Index) && paperSources[printerTrayModel.Index].Equals(printerTrayModel.Name)))
                    {
                        printerTrayDb.Entry(printerTrayModel);
                        printerTrayDb.Models.Remove(printerTrayModel);
                    }
                }
            }
            printerTrayDb.SaveChanges();
        }
Exemplo n.º 5
0
        public void ProcessDocuments()
        {
            //Get the documents to be printed.
            List <PrintModel> printModels = printDb.Models
                                            .Where(a => (a.Status == PrintModel.queuedStatus || a.Status == PrintModel.failedStatus) && a.RetryCount < 5)
                                            .ToList();

            //Loop the document list and send the document to printer
            foreach (PrintModel printModel in printModels)
            {
                //Null out any previous errors
                printModel.ErrorMessage = null;
                try
                {
                    //Validate the file
                    if (string.IsNullOrEmpty(printModel.FileLocation) || !File.Exists(printModel.FileLocation.Trim()))
                    {
                        using (EventLog eventLog = new EventLog("Application"))
                        {
                            eventLog.Source = _serviceName;
                            eventLog.WriteEntry($"File '{printModel.FileLocation}' not found.", EventLogEntryType.Error, 101, 1);
                            printModel.ErrorMessage = $"File '{printModel.FileLocation}' not found.";
                        }
                    }
                    else
                    {
                        using (PdfDocument pdfDocument = new PdfDocument())
                        {
                            pdfDocument.LoadFromFile(printModel.FileLocation.Trim());
                            PrintDocument printDocument = pdfDocument.PrintDocument;
                            printDocument.PrinterSettings.PrinterName = printModel.Printer.Name.Trim();

                            //Validate the printer name
                            if (printModel.Printer == null || string.IsNullOrEmpty(printModel.Printer.Name) || !printDocument.PrinterSettings.IsValid)
                            {
                                //serviceResult.Error("No Printer information found!");
                                using (EventLog eventLog = new EventLog("Application"))
                                {
                                    eventLog.Source = _serviceName;
                                    eventLog.WriteEntry($"Printer '{printModel.Printer}' found!", EventLogEntryType.Error, 101);
                                    printModel.ErrorMessage = $"Printer '{printModel.Printer}' found!";
                                }
                            }
                            else
                            {
                                //Check out the paper source
                                if (printModel.Printer.PrinterTray != null)
                                {
                                    printDocument.DefaultPageSettings.PaperSource = printDocument.PrinterSettings.PaperSources[printModel.Printer.PrinterTray.Index];
                                }

                                //Check the config setting if we want to actually send to printer.
                                if (_sendToPrinter)
                                {
                                    printDocument.Print();
                                }

                                printModel.Status = PrintModel.printedStatus;
                            }

                            //Update the print status
                            if (!string.IsNullOrWhiteSpace(printModel.ErrorMessage))
                            {
                                printModel.Status = PrintModel.failedStatus;
                            }

                            printModel.RetryCount      = (printModel.Status != PrintModel.printedStatus ? printModel.RetryCount + 1 : printModel.RetryCount);
                            printModel.PrintedDateTime = (printModel.Status.Equals(PrintModel.printedStatus) ? DateTime.Now : printModel.PrintedDateTime);
                        }
                    }
                }
                catch (Exception e)
                {
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = _serviceName;
                        eventLog.WriteEntry("Print service Exception " + e.Message, EventLogEntryType.Error, 101, 1);
                    }
                    printModel.Status       = PrintModel.failedStatus;
                    printModel.RetryCount   = (printModel.Status != PrintModel.printedStatus ? printModel.RetryCount + 1 : printModel.RetryCount);
                    printModel.ErrorMessage = "Print service Exception " + e.Message;
                }
                printDb.Entry(printModel).State = EntityState.Modified;
            }
            printDb.SaveChanges(_userId);
        }
Exemplo n.º 6
0
        public static List <ReportModel> GetReports(ReportModel reportModel, string category, IPrincipal User)
        {
            BaseModelContext <ReportModel> reportDb = new BaseModelContext <ReportModel>();
            List <ReportModel>             reports;

            //Get list of active reports
            if (!User.IsInRole(SiteRole.Administrators))
            {
                reports = reportDb.Models.Where(r => r.IsActive == true).ToList();
            }
            else
            {
                reports = reportDb.Models.ToList();
            }
            //Reduce to category if category is specified
            if (!string.IsNullOrWhiteSpace(category))
            {
                reports = reports.Where(r => r.Category == category).ToList();
            }

            //Reduce to a specific report if specified
            if (reportModel != null)
            {
                reports = reports.Where(r => r.Id == reportModel.Id).ToList();
            }

            //If Admin return all report/s
            if (User.IsInRole(SiteRole.Administrators))
            {
                return(reports);
            }
            List <ReportModel> userReports = new List <ReportModel>();

            //Add report/s for everyone
            userReports = userReports.Concat(
                reports.Where(r => r.Permit == ReportModel.permitEveryone)
                ).ToList();

            //Gather roleIds of user
            string userId = User.Identity.GetUserId();
            BaseModelContext <UserModel> userDb = new BaseModelContext <UserModel>();
            UserModel userModel = userDb.Models.Find(userId);

            //UserRoles are not preloaded. So load them.
            userDb.Entry(userModel).Collection("UserRoles").Load();

            if (userModel != null)
            {
                List <string> roleIds = userModel.UserRoles.Select(r => r.RoleId).ToList();

                //Add reports matching user roles
                userReports = userReports.Concat(
                    reports.Where(r => r.Permit == ReportModel.permitUserOrRole).SelectMany(r => r.ReportRoles.Where(e => roleIds.Contains(e.RoleId))).Select(r => r.Report)
                    ).ToList();


                //Add reprots matching user
                userReports = userReports.Concat(
                    reports.Where(r => r.Permit == ReportModel.permitUserOrRole && r.ReportUsers.Select(u => u.UserId).Contains(userId))
                    ).ToList();
            }

            //Return Unique Reports.
            return(new HashSet <ReportModel>(userReports).ToList());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Run reports is used for scheduled reports.
        /// </summary>
        /// <param name="reportModel"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static FileHelper Run(ReportModel reportModel, string userId)
        {
            string URL     = reportServerPathRunner + reportModel.SSRSReportName.Replace(".rdl", "");
            string Command = "Render";
            string Query   = "";

            FileHelper file = new FileHelper((!string.IsNullOrWhiteSpace(reportModel.FileName) ? reportModel.FileName : reportModel.SSRSReportName.Replace(".rdl", "")), userId);

            //Replace filename parameters.
            foreach (ReportParameterModel reportParameter in reportModel.ReportParameters)
            {
                //Setup the query
                if (!string.IsNullOrWhiteSpace(reportParameter.DefaultValue))
                {
                    Query += $"&{reportParameter.Name}={reportParameter.DefaultValue}";
                }
                //Replace any parameter in the name.
                if (file.FileName.Contains("{" + reportParameter.Name + "}"))
                {
                    string defaultValue = reportParameter.DefaultValue;
                    //If the parameter is a date make sure we format it so its fiel friendly.
                    if (!string.IsNullOrWhiteSpace(reportParameter.DataType) && reportParameter.DataType.Equals(ReportParameterModel.dateTimeType))
                    {
                        DateTime dateTimeValue;
                        DateTime.TryParse(reportParameter.DefaultValue, out dateTimeValue);
                        defaultValue = (dateTimeValue != null ? dateTimeValue.ToString("yyyyMMdd") : "");
                    }
                    file.FileName = file.FileName.Replace("{" + reportParameter.Name + "}", defaultValue);
                }
            }
            file.FileName = Regex.Replace(file.FileName, "-{2,}", "-");
            file.FileName = file.FileName + "." + ReportModel.Extensions[reportModel.Format];
            //Delete existing file
            if (file.Delete())
            {
                URL = URL + "&rs:Command=" + Command + "&rs:Format=" + reportModel.Format + Query;

                System.Net.HttpWebRequest Req        = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
                NetworkCredential         credential = new NetworkCredential(userName, password, domain);

                Req.Credentials = credential;
                Req.Method      = "GET";
                //Specify the path for saving.

                //Do File Service here and return FileService fileService = new FileService();

                //file.FilePathAndName = string.Format("{0}{1}{2}", file.FilePath, file.FileName, @".pdf");
                System.Net.WebResponse objResponse = Req.GetResponse();
                System.IO.FileStream   fs          = new System.IO.FileStream(file.FilePathAndName, System.IO.FileMode.Create);
                System.IO.Stream       stream      = objResponse.GetResponseStream();

                byte[] buf = new byte[1024];
                int    len = stream.Read(buf, 0, 1024);
                while (len > 0)
                {
                    fs.Write(buf, 0, len);
                    len = stream.Read(buf, 0, 1024);
                }
                stream.Close();
                fs.Close();

                BaseModelContext <ReportUserActivityLogModel> reportUserActivityLogDb = new BaseModelContext <ReportUserActivityLogModel>();
                ReportUserActivityLogModel reportUserActivityModel = new ReportUserActivityLogModel()
                {
                    ReportId   = reportModel.Id,
                    UserId     = userId,
                    Activity   = ReportUserActivityLogModel.RunActivity,
                    Parameters = Query
                };
                reportUserActivityLogDb.Models.Add(reportUserActivityModel);
                reportUserActivityLogDb.SaveChanges(userId);


                BaseModelContext <ReportModel> reportDb = new BaseModelContext <ReportModel>();
                reportModel.LastRun = DateTime.Now;
                reportDb.Entry(reportModel);
                reportDb.SaveChanges(userId);
            }
            return(file);
        }