void Application_Error(object sender, EventArgs e) { string error = ""; if (Context != null && Server.GetLastError() != null) { DataTypesHelper.getError(Context.Error, ref error); } if (HttpContext.Current.Error != null) { DataTypesHelper.getError(HttpContext.Current.Error, ref error); } //if is there error on client side we need aditional information about error error += "\r\n \r\n" + sender.GetType().FullName + "\r\n" + HttpContext.Current.Request.UrlReferrer.AbsoluteUri + "\r\n"; DataTypesHelper.LogThis(error); if (Context != null) { Context.ClearError(); } Server.ClearError(); }
private void ProcessEventsToAvtomatika() { try { //poiščemo takšne dogodke ki so v tabeli Dogodki in jih ne najdemo v SystemMessageEvents tabeli //int tip = (int)Enums.SystemMessageEventStatus.UnProcessed; var query = from dogodek in context.Dogodek where dogodek.Tip.Equals("Avtomatika") && !context.Avtomatika.Any(a => (a.DogodekID == dogodek.idDogodek)) select new EventFullModel { idDogodek = dogodek.idDogodek, tsIDOsebe = dogodek.tsIDOsebe.HasValue ? dogodek.tsIDOsebe.Value : 0, DatumOtvoritve = dogodek.DatumOtvoritve.Value, Izvajalec = dogodek.Osebe.idOsebe, Opis = dogodek.Opis }; foreach (var item in query.ToList()) { DataTypesHelper.LogThis("*****In foreach statement*****"); DataTypesHelper.LogThis("*****Dogodek: *****" + "ID: " + item.idDogodek.ToString() + " Oseba: " + item.Izvajalec.Value.ToString()); Avtomatika newAutoEvent = new Avtomatika(); newAutoEvent.AvtomatikaID = 0; newAutoEvent.Status = (int)Enums.SystemMessageEventStatus.UnProcessed; newAutoEvent.OsebaID = item.Izvajalec.HasValue ? item.Izvajalec.Value : 0; newAutoEvent.DogodekID = item.idDogodek; newAutoEvent.StopnjaNadrejenega = 1; newAutoEvent.ts = DateTime.Now; newAutoEvent.Opis = item.Opis; context.Avtomatika.Add(newAutoEvent); } context.SaveChanges(); } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); FileNotFoundException exFileNotFound = exSub as FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); //DataTypesHelper.LogThis("*****ReflectionTypeLoadException! - ***** " + errorMessage); //Display or log the error based on your application. } catch (Exception ex) { DataTypesHelper.LogThis("*****Exception! - ***** " + ValidationExceptionError.res_08 + " " + ex.Message); throw new Exception(ValidationExceptionError.res_08, ex); } }
/// <summary> /// Launch the application with some options set. /// </summary> public void LaunchPantheonCreatePDF() { // For the example string ex1 = ConfigurationManager.AppSettings["PantheonCreatePDFPath"].ToString(); string PanthExeFile = ConfigurationManager.AppSettings["PantheonEXEFile"].ToString(); string PanthExeArgs = ConfigurationManager.AppSettings["PantheonEXEArgs"].ToString(); string PanthDB = ConfigurationManager.AppSettings["PantheonDB"].ToString(); string sPanthExeTimeout = ConfigurationManager.AppSettings["PantheonEXETimeOut"]; DataTypesHelper.LogThis("OTP Config: PDF Path: " + ex1 + ", PantheonEXEFile: " + PanthExeFile + ", Args: " + PanthExeArgs + ", PanthDB: " + PanthDB + ", Timeout: " + sPanthExeTimeout); int timeout = Convert.ToInt32(sPanthExeTimeout); //string ex1 = "C:\\Temp\\OtpProject\\"; PanthExeArgs = PanthExeArgs.Replace("DatabaseNameDB", "\"" + PanthDB + "\""); DataTypesHelper.LogThis("OTP Process info - Config"); // Use ProcessStartInfo class ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; //startInfo.FileName = ex1 + "CreatePDFPantheon.bat"; startInfo.FileName = PanthExeFile; startInfo.Arguments = PanthExeArgs; startInfo.WindowStyle = ProcessWindowStyle.Normal; //startInfo.Arguments = "/lens"; DataTypesHelper.LogThis("OTP Start File: " + startInfo.FileName.ToString()); DataTypesHelper.LogThis("OTP Start Args: " + startInfo.Arguments.ToString()); if (!File.Exists(startInfo.FileName)) { DataTypesHelper.LogThis("OTP App doesnt exist: " + startInfo.FileName.ToString()); return; } try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. DataTypesHelper.LogThis("OTP Run Process - Start"); using (Process exeProcess = Process.Start(startInfo)) { DataTypesHelper.LogThis("OTP Process - Start timeout"); exeProcess.WaitForExit(timeout); DataTypesHelper.LogThis("OTP Run Process - Succesfull"); if (exeProcess.HasExited == false) { DataTypesHelper.LogThis("OTP Process - Killed"); exeProcess.Kill(); } } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message + "\r\n " + ex.Source + "\r\n " + ex.StackTrace); } }
public void CheckRecallsForCarriersSubmittingPrices() { //pridobi vse odpoklice ki imajo flag PovprasevanjePolsnoPrevoznikom nastavlen na 1 in PrevoznikOddalNajnizjoCeno 0 ter DatumNaklada še ni potekel List <int> recalls = context.Odpoklic.Where(o => o.PovprasevanjePoslanoPrevoznikom.Value && !o.PrevoznikOddalNajnizjoCeno.Value && o.DatumNaklada > DateTime.Now).Select(o => o.OdpoklicID).ToList();//select uporabimo zato ker v spodnjem query kličemo funkcijo Any ki dovoljuje samo enostavne //pridobimo vse prijave prevoznikov ki predstavljajo odpoklice v seznamu odpoklicev (recalls) in jih grupiramo po OdpoklicID polju List <IGrouping <Odpoklic, PrijavaPrevoznika> > listPrijavaPrevoznika = context.PrijavaPrevoznika.Where(pp => recalls.Any(o => o == pp.OdpoklicID)).ToList().GroupBy(g => g.Odpoklic).ToList(); foreach (var item in listPrijavaPrevoznika) { //En teden pred datumom naklada DateTime oneWeekFromLoadingDate = item.Key.DatumNaklada.Value.AddDays(-7); if (oneWeekFromLoadingDate.Date == DateTime.Now.Date)//če je današnji dan enak tistemu ki je en teden pred datumom naklada { DataTypesHelper.LogThis("Trenutni datum je 1 teden pred datumom naklada " + item.Key.DatumNaklada.Value.ToShortDateString() + " za " + item.Key.Relacija.Naziv); CheckForLowestPriceInPrijavaPrevoznika(item); } else if (oneWeekFromLoadingDate.Date < DateTime.Now.Date && item.Key.DatumNaklada.Value.Date > DateTime.Now.Date)//če je današnji datum večji (pretekel) kot en teden pre datumom naklada in vseeno manjši od datuma naklada. { DataTypesHelper.LogThis("Trenutni datum je pretekel Datum naklada -1 teden " + item.Key.DatumNaklada.Value.ToShortDateString() + " za " + item.Key.Relacija.Naziv); //Implementiraj da se bo pošiljalo samo enkrat na dan. //Pošljemo mail logistiki. //Še vseeno zbiramo najnižjo ceno prevoznikov CheckForLowestPriceInPrijavaPrevoznika(item); } } }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (e != null && e.ExceptionObject != null) { DataTypesHelper.LogThis(e.ExceptionObject.ToString()); } }
private string ReplaceDefaultValuesInTemplate(Object o, string template) { string result = ""; string value = template; Type type = o.GetType(); object[] indexArgs = { 0 }; PropertyInfo[] myFields = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); for (int i = 0; i < myFields.Length; i++) { try { value = value.Replace("$%" + myFields[i].Name + "%$", myFields[i].GetValue(o, null) == null ? "" : myFields[i].GetValue(o, null).ToString()); } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message); } } result = value; return(result); }
public void CreateEmailForAdmin_NoPDFForOrderPDO(string sOdobritevKomentar, string sStevilkaDokumenta, string sStevilkaNarocilnice, bool bOdpoklic) { StreamReader reader = null; try { //DataTypesHelper.LogThis("*****IN Method ProcessEventMessage*****"); string emailSubject = SystemEmailMessageResource.res_21; string templatePathRez = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["ADMIN_EMAIL_RECALL"].ToString()).Replace("\"", "\\"); string templatePath = (ConfigurationManager.AppSettings["ADMIN_EMAIL_RECALL"].ToString()).Replace("\"", "\\"); //DataTypesHelper.LogThis(AppDomain.CurrentDomain.BaseDirectory); RecallApprovalEmailModel message = new RecallApprovalEmailModel(); templatePath = File.Exists(templatePath) ? templatePath : templatePathRez; reader = new StreamReader(templatePath); string templateString = reader.ReadToEnd(); message.Comments = sOdobritevKomentar; message.OdpoklicID = sStevilkaDokumenta; // return all user with admin role List <Osebe_PDO> employeesList = context.Osebe_PDO.Where(o => o.VlogaID == 2).ToList(); if (employeesList != null) { foreach (var employee in employeesList) { message.FirstName = employee.Ime; message.Lastname = employee.Priimek; message.Email = employee.Email; message.ServerTagOTP = ConfigurationManager.AppSettings["ServerTagOTP"].ToString(); message.Comments = "Kriranje PDF dokumenta v PANTHEONU že 5x ni vrnilo PDF Številka naročilnice: " + sStevilkaNarocilnice; message.Comments += "<br> Preverite zakaj je tako!"; message.Comments += bOdpoklic ? "<br> <b>ODPOKLIC</b> " : "<br> <b>PDO Naročilo</b> "; templateString = ReplaceDefaultValuesInTemplate(message, templateString); SaveToSystemEmailMessage(message.Email, templateString, null, 1, emailSubject); } } if (employeesList.Count == 0) { DataTypesHelper.LogThis("V podatkovni bazi ni osebe z vlogo ADMIN (ID=2)"); } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message); } }
public void CreateEmailForSupplierOrder(OrderPDOFullModel order) { StreamReader reader = null; try { //DataTypesHelper.LogThis("*****IN Method ProcessEventMessage*****"); string emailSubject = SystemEmailMessageResource.res_22; string templatePathRez = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["SUPPLIER_MAIL_ORDER"].ToString()).Replace("\"", "\\"); string templatePath = (ConfigurationManager.AppSettings["SUPPLIER_MAIL_ORDER"].ToString()).Replace("\"", "\\"); string rootURL = ConfigurationManager.AppSettings["ServerTagCarrierPage"].ToString(); DataTypesHelper.LogThis(AppDomain.CurrentDomain.BaseDirectory); var Dobavitelj = context.Stranka_PDO.Where(s => s.StrankaID == order.StrankaDobaviteljID).FirstOrDefault(); CarrierMailModel message = null; if (Dobavitelj != null) { templatePath = templatePath.Replace("XXX", Dobavitelj.Jeziki.Koda.ToString()); templatePathRez = templatePathRez.Replace("XXX", Dobavitelj.Jeziki.Koda.ToString()); if (!String.IsNullOrEmpty(Dobavitelj.Email))//TODO: kaj pa če ima stranka vpisanih več mail-ov { DataTypesHelper.LogThis("Send order to email: " + Dobavitelj.Email); message = new CarrierMailModel(); SetLanguageContentEmail(message, Dobavitelj.Jeziki.Koda); message.AdditionalText = message.AdditionalText + order.NarociloID.ToString(); message.CarrierName = Dobavitelj.NazivPrvi; message.Email = Dobavitelj.Email; templatePath = File.Exists(templatePath) ? templatePath : templatePathRez; reader = new StreamReader(templatePath); string templateString = reader.ReadToEnd(); templateString = ReplaceDefaultValuesInTemplate(message, templateString); SaveToSystemEmailMessage(message.Email, templateString, null, 1, message.SubjectText, order.P_TransportOrderPDFDocPath); } else { throw new Exception("Stranka " + Dobavitelj.NazivPrvi + "nima vpisanega elektrnoskega naslova!"); } } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message); } }
public void UpdateSystemMessageEvents(SystemMessageEvents message) { try { DataTypesHelper.LogThis("UPDATING SystemMessageEvents status."); var original = context.SystemMessageEvents.Where(s => s.SystemMessageEventID == message.SystemMessageEventID).FirstOrDefault(); context.Entry(original).CurrentValues.SetValues(message); context.SaveChanges(); } catch (Exception ex) { throw new Exception(ex.Message); } }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { // TODO: Insert monitoring activities here. DataTypesHelper.LogThis(args.SignalTime.ToLongTimeString() + "\n"); try { //TODO: Preveri tabelo Avtomatika in prenesi zapise v SystemMessageEvents. if (timeToStartAvtomatika.CompareTo(args.SignalTime) <= 0) { systemMessageEventsRepo.GetUnProcessedRecordsAvtomatika(); timeToStartAvtomatika = args.SignalTime; timeToStartAvtomatika = timeToStartAvtomatika.AddMinutes(Convert.ToDouble(ConfigurationManager.AppSettings["TimeIntervalAvtomatika"].ToString()));//every 3 min DataTypesHelper.LogThis("Current time: " + args.SignalTime.ToLongTimeString() + "\n"); DataTypesHelper.LogThis("Next start at: " + timeToStartAvtomatika.ToLongTimeString() + "\n"); } systemMessageEventsRepo.GetEventsWithNoReportForMeeting(); systemMessageEventsRepo.GetEventsWithNoPreparationForMeeting(); foreach (SystemMessageEvents item in systemMessageEventsRepo.GetUnProcessedMesseges()) { if (item.Code == Enums.SystemMessageEventCodes.NewMessage.ToString()) { systemMessageEventsRepo.ProcessNewMessage(item); } else if (item.Code == Enums.SystemMessageEventCodes.AUTO.ToString()) { systemMessageEventsRepo.ProcessAutoMessage(item); } else if (item.Code == Enums.SystemMessageEventCodes.EVENT_DOGODEK.ToString()) { systemMessageEventsRepo.ProcessEventMessage(item); } else if (item.Code == Enums.SystemMessageEventCodes.EVENT_PRIPRAVA_OPOZORILO.ToString()) { systemMessageEventsRepo.ProcessEventMessage(item, Enums.SystemMessageEventCodes.EVENT_PRIPRAVA_OPOZORILO); } else if (item.Code == Enums.SystemMessageEventCodes.EVENT_POROCILO_OPOZORILO.ToString()) { systemMessageEventsRepo.ProcessEventMessage(item, Enums.SystemMessageEventCodes.EVENT_POROCILO_OPOZORILO); } } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message + "\n" + ex.InnerException != null ? ex.InnerException.Message : "" + "\n" + ex.StackTrace); } }
protected override void OnStart(string[] args) { try { /*System.Timers.Timer timer = new System.Timers.Timer(); * timer.Interval = Convert.ToDouble(ConfigurationManager.AppSettings["TimeInterval"].ToString()); // every 6min * timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer); * timer.Start();*/ this.ScheduleService(); } catch (Exception e) { DataTypesHelper.LogThis(e.Message); throw; } }
public IHttpActionResult SaveInquiryPurchase([FromBody] object inquiryData) { WebResponseContentModel <InquiryFullModel> model = null; try { model = JsonConvert.DeserializeObject <WebResponseContentModel <InquiryFullModel> >(inquiryData.ToString()); DataTypesHelper.LogThis("SaveInquiryPurchase : " + model.Content.StatusPovprasevanja.Koda.ToString()); if (model.Content != null) { if (model.Content.PovprasevanjeID > 0)//We update existing record in DB { inquiryRepo.SaveInquiry(model.Content); // send email to all grafolit contacts = Nabava DataTypesHelper.LogThis("Generate mail for Purchase dept : " + model.Content.StatusPovprasevanja.Koda.ToString()); if (model.Content.StatusPovprasevanja.Koda == Enums.StatusOfInquiry.POSLANO_V_NABAVO.ToString()) { var employee = employeeRepo.GetEmployeeByID(model.Content.PovprasevanjeOddalID); string sGrafolitDept = ConfigurationManager.AppSettings["PantheonCreateOrderDefBuyer"].ToString(); ClientFullModel cfmGrafolit = clientPdoRepo.GetClientByName(sGrafolitDept); DataTypesHelper.LogThis("Generate mail for Purchase dept"); messageEventsRepo.CreateEmailForGrafolitPurcaheDept(cfmGrafolit, employee, model.Content); } } model.IsRequestSuccesful = true; } else { model.IsRequestSuccesful = false; model.ValidationError = ValidationExceptionError.res_09; } } catch (Exception ex) { model.IsRequestSuccesful = false; model.ValidationError = ExceptionValidationHelper.GetExceptionSource(ex); return(Json(model)); } return(Json(model)); }
public void GetEventsWithNoReportForMeeting() { try { DataTypesHelper.LogThis("*****IN GetEventsWithNoReportForMeeting*****"); int reportDeadline = int.Parse(ConfigurationManager.AppSettings["DeadlineForReportInDays"].ToString()); DataTypesHelper.LogThis("*****AFTER ConfigurationManager.AppSettings 1 *********"); int notifyBeforeDeadline = reportDeadline - int.Parse(ConfigurationManager.AppSettings["NotificationBeforeReportDeadlineInDays"].ToString()); DataTypesHelper.LogThis("*****AFTER ConfigurationManager.AppSettings 1 *********"); string tipDogodka = Enums.EventMeetingType.POROCILO.ToString(); var query = from dogodek in context.Dogodek where !context.DogodekSestanek.Any(ds => (ds.DogodekID == dogodek.idDogodek) && (ds.Tip.Equals(tipDogodka))) select new EventFullModel { idDogodek = dogodek.idDogodek, tsIDOsebe = dogodek.tsIDOsebe.HasValue ? dogodek.tsIDOsebe.Value : 0, DatumOtvoritve = dogodek.DatumOtvoritve.Value }; DataTypesHelper.LogThis("*****IN GetEventsWithNoReportForMeeting count: *****" + query.ToList().Count.ToString()); foreach (var item in query.ToList()) { DateTime dateNotifyBeforeDeadline = item.DatumOtvoritve.AddDays(notifyBeforeDeadline); // datum ki je 7 dni pred rokom DateTime dateDeadline = item.DatumOtvoritve.AddDays(reportDeadline); //datum ki je rok poteka if (DateTime.Now.CompareTo(dateNotifyBeforeDeadline) >= 0 && DateTime.Now.CompareTo(dateDeadline) <= 0) //če je trenutni datum med zgraj navedenima datuma { CreateSystemMessageEventsForEvent(item, Enums.SystemMessageEventCodes.EVENT_POROCILO_OPOZORILO); } else if (DateTime.Now.CompareTo(dateDeadline) > 0 && DateTime.Now.CompareTo(dateDeadline.AddDays(7)) <= 0)// če na dan roka še ni poročila se od datuma roka +7 dni pošilja mail zaposlenemu in nadrejenemu { CreateSystemMessageEventsForEvent(item, Enums.SystemMessageEventCodes.EVENT_POROCILO_OPOZORILO_NADREJENI); } else if (DateTime.Now.CompareTo(dateDeadline.AddDays(7)) > 0 && DateTime.Now.CompareTo(dateDeadline.AddDays(14)) <= 0)//če po 7 dneh od datuma roka še vedno ni poročila se pošlje mail še direktorju - je potrebno omejit zgornji datum? (v tem primeru je zgornji datum 14 dni od datuma zapadlosti dogodka) { CreateSystemMessageEventsForEvent(item, Enums.SystemMessageEventCodes.EVENT_POROCILO_OPOZORILO_NADREJENI_DIREKTOR); } } context.SaveChanges(); DataTypesHelper.LogThis("*****IN GetEventsWithNoReportForMeeting AFTER SAVING: *****"); } catch (Exception ex) { DataTypesHelper.LogThis("*****IN GetEventsWithNoReportForMeeting ERROR: *****" + ex.Message); throw new Exception(ValidationExceptionError.res_08, ex); } }
private void CreateSystemMessageEventsForEvent(EventFullModel dogodek, Enums.SystemMessageEventCodes eventType) { DataTypesHelper.LogThis("*****CREATING NEW SYSTEMMESSGE EVENT: event type = *****" + eventType.ToString()); SystemMessageEvents newEvent = new SystemMessageEvents(); newEvent.SystemMessageEventID = 0; newEvent.Status = (int)Enums.SystemMessageEventStatus.UnProcessed; newEvent.MasterID = dogodek.idDogodek; newEvent.Code = eventType.ToString(); newEvent.ts = DateTime.Now; if (dogodek.tsIDOsebe != 0) { newEvent.tsIDOsebe = dogodek.tsIDOsebe; } context.SystemMessageEvents.Add(newEvent); }
//public string GetOrderPDFFilePDO(int iPDOOrderID) //{ // try // { // OrderPDOFullModel rfm = orderPDORepo.GetOrderByID(iPDOOrderID); // string curFile = ""; // string sResult = ""; // if (rfm != null) // { // rfm.NarociloStevilka_P = (rfm.NarociloStevilka_P != null) ? rfm.NarociloStevilka_P : "xxx"; // // če je 5x neuspešno, potem se pošlje mail Daniju // if ((rfm.P_UnsuccCountCreatePDFPantheon >= 5) && (rfm.P_SendWarningToAdmin == 0)) // { // messageRepo.CreateEmailForAdmin_NoPDFForOrder("", rfm.NarociloStevilka_P.ToString(), rfm.P_TransportOrderPDFName, false); // rfm.P_SendWarningToAdmin = 1; // return "NOT_EXIST"; // } // else if (rfm.P_SendWarningToAdmin == 1) // { // DataTypesHelper.LogThis("Za naročilo št. " + rfm.NarociloStevilka_P + " ni bilo kreirano PDF in je bil poslal že mail administraotrju."); // return "NOT_EXIST"; // } // curFile = ((rfm.P_TransportOrderPDFDocPath != null) && (rfm.P_TransportOrderPDFDocPath.Length > 0)) ? rfm.P_TransportOrderPDFDocPath : ""; // sResult = File.Exists(curFile) ? "EXIST" : "NOT_EXIST"; // } // if (sResult != "EXIST") // { // LaunchPantheonCreatePDF(); // rfm.P_UnsuccCountCreatePDFPantheon++; // rfm.P_LastTSCreatePDFPantheon = DateTime.Now; // } // else // { // InquiryStatus stat = orderPDORepo.GetPovprasevanjaStatusByCode(Enums.StatusOfInquiry.KREIRAN_POSLAN_PDF.ToString()); // if (stat != null) // { // rfm.StatusID = stat.StatusPovprasevanjaID; // rfm.P_GetPDFOrderFile = DateTime.Now; // // Create mail for prevoznik // messageRepoPDO.CreateEmailForSupplierOrder(rfm); // } // } // orderPDORepo.SaveOrder(rfm, true, false); // return sResult; // } // catch (Exception ex) // { // throw ex; // } //} public void CreateOrderTransport(CreateOrderModel model) { try { RecallFullModel rfm = recallRepo.GetRecallFullModelByID(model.RecallID); if (rfm.P_CreateOrder.Year < 2000) { DataTypesHelper.LogThis("cREATE oRDER xml"); string xml = GetXMLForOrder(model); DataTypesHelper.LogThis(xml); DataTypesHelper.LogThis("Run Create order procedure _upJM_CreateSupplierOrder"); // run store procedure _upJM_CreateSupplierOrder CreateOrderDocument coData = sqlFunctionRepo.GetOrderDocumentData(xml); DataTypesHelper.LogThis("Update Create order Recall Data"); // update odpoklic - uspešno kreirana naročilnica v pantheonu RecallStatus stat = recallRepo.GetRecallStatusByCode(Enums.StatusOfRecall.USTVARJENO_NAROCILO.ToString()); if (stat != null) { rfm.StatusID = stat.StatusOdpoklicaID; } rfm.P_UnsuccCountCreatePDFPantheon = 0; rfm.P_CreateOrder = DateTime.Now; rfm.P_TransportOrderPDFName = coData.PDFFile.ToString(); rfm.P_TransportOrderPDFDocPath = coData.ExportPath.ToString(); recallRepo.SaveRecall(rfm, true); //DataTypesHelper.LogThis("Launch Create PDF Pantheon.exe"); // launch Pantheon EXE command //LaunchPantheonCreatePDF(); DataTypesHelper.LogThis("Finish CreateOrderTransport"); } } catch (Exception ex) { throw ex; } }
private void ScheduleService() { try { timerSchedular = new Timer(new TimerCallback(TimerScheduleCallback)); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; string scheduleMode = System.Configuration.ConfigurationManager.AppSettings["ScheduleMode"].ToString(); if (scheduleMode == "Dnevno") { scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } else if (scheduleMode == "Interval") { int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMin"]); scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. timerSchedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message + ex.StackTrace); } }
private void TimerScheduleCallback(object e) { try { DataTypesHelper.LogThis("*****TimerScheduleCallback start*****"); systemMessageEventsRepo.GetEventsWithNoReportForMeeting(); systemMessageEventsRepo.GetEventsWithNoPreparationForMeeting(); DataTypesHelper.LogThis("*****Before Firing Method GetUnProcessedRecordsAvtomatika*****"); systemMessageEventsRepo.GetUnProcessedRecordsAvtomatika(); DataTypesHelper.LogThis("*****After Firing Method GetUnProcessedRecordsAvtomatika*****"); foreach (SystemMessageEvents item in systemMessageEventsRepo.GetUnProcessedMesseges()) { DataTypesHelper.LogThis("*****in foreach GetUnProcessedMesseges - instance values: *****" + item.Code); if (item.Code == Enums.SystemMessageEventCodes.NewMessage.ToString()) { systemMessageEventsRepo.ProcessNewMessage(item); } else if (item.Code == Enums.SystemMessageEventCodes.AUTO.ToString()) { //DataTypesHelper.LogThis("*****Before ProcesAutoMesages*****"); systemMessageEventsRepo.ProcessAutoMessage(item); //DataTypesHelper.LogThis("*****After ProcesAutoMesages*****"); } else if (item.Code == Enums.SystemMessageEventCodes.EVENT_DOGODEK.ToString()) { systemMessageEventsRepo.ProcessEventMessage(item); } else if (systemMessageEventsRepo.EventPreparationOrReport(item.Code)) { systemMessageEventsRepo.ProcessEventMessage(item, (Enums.SystemMessageEventCodes)Enum.Parse(typeof(Enums.SystemMessageEventCodes), item.Code, true)); } } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message + "\n" + ex.InnerException != null ? ex.InnerException.Message : "" + "\n" + ex.StackTrace); } this.ScheduleService(); }
public void CreateEmailForUserCreateNewCodeForProduct(CreateNewCodeMailModel model) { StreamReader reader = null; try { //DataTypesHelper.LogThis("*****IN Method ProcessEventMessage*****"); string emailSubject = SystemEmailMessageResource.res_23; string templatePath = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["USER_MAIL_NOZ"].ToString()).Replace("\"", "\\"); string rootURL = ConfigurationManager.AppSettings["ServerURL_NOZ"].ToString(); DataTypesHelper.LogThis(AppDomain.CurrentDomain.BaseDirectory); var user = context.Osebe_NOZ.Where(o => o.OsebaID == model.UserId).FirstOrDefault(); if (user != null) { if (!String.IsNullOrEmpty(user.Email))//TODO: kaj pa če ima stranka vpisanih več mail-ov { model.Email = user.Email; model.EmployeeName = user.Ime + " " + user.Priimek; model.RootURL = rootURL; reader = new StreamReader(templatePath); string templateString = reader.ReadToEnd(); templateString = ReplaceDefaultValuesInTemplate(model, templateString); SaveToSystemEmailMessage(user.Email, templateString, null, 1, emailSubject); } else { throw new Exception("Oseba " + user.Ime + " " + user.Priimek + " nima vpisanega elektrnoskega naslova!"); } } } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message); } }
public MessageEmailService() { try { InitializeComponent(); kernel = new StandardKernel(); kernel.Bind <ISystemMessageEventsRepository>().To <SystemMessageEventsRepository>(); kernel.Bind <IEventRepository>().To <EventRepository>(); kernel.Bind <IEmployeeRepository>().To <EmployeeRepository>(); kernel.Bind <IPostRepository>().To <PostRepository>(); systemMessageEventsRepo = kernel.Get <ISystemMessageEventsRepository>(); timeToStartAvtomatika = DateTime.Now; } catch (Exception ex) { DataTypesHelper.LogThis(ex.Message); } }
public List <OrderPositionModelNew> GetListOfOrderNumber10() {//TODO: pridobimo še vse pozicije iz tabele lastna zaloga če je izbran dobavitelj iz naše tabele stranka_otp i da je tipa SKLADISCE try { DataTypesHelper.LogThis("GetListOfOrderNumber10"); var query = from np in context.SeznamPozicijNarocilnic10ZaOdpoklic() select new OrderPositionModelNew { Status = np.Status, ZeljeniRokDobave = np.ZeljeniRokDobave.HasValue ? np.ZeljeniRokDobave.Value : DateTime.MinValue, Narocilnica = np.StevilkaDokumenta, Kupec = np.Stranka, Dobavitelj = np.Dobavitelj == null ? "" : np.Dobavitelj, Kategorija = np.Kategorija == null ? "" : np.Kategorija, Ident = np.KodaArtikla, Artikel = np.NazivArtikla, Naroceno = np.NarocenaKolicina, EnotaMere = np.EnotaMere, PotrjeniRokDobave = np.PotrjeniRokDobave.HasValue ? np.PotrjeniRokDobave.Value : DateTime.MinValue }; List <OrderPositionModelNew> list = query.ToList(); int count = 1; foreach (var item in list) { item.tempID = count; count++; } return(list); } catch (Exception ex) { throw new Exception(ValidationExceptionError.res_06, ex); } }
public IHttpActionResult SaveTender([FromBody] object tenderData) { WebResponseContentModel <TenderFullModel> model = null; try { DataTypesHelper.LogThis("Start - Controler"); model = JsonConvert.DeserializeObject <WebResponseContentModel <TenderFullModel> >(tenderData.ToString()); if (model.Content != null) { if (model.Content.RazpisID > 0)//We update existing record in DB { tenderRepo.SaveTender(model.Content); } else // We add and save new recod to DB { model.Content.RazpisID = tenderRepo.SaveTender(model.Content, false); } model.IsRequestSuccesful = true; } else { model.IsRequestSuccesful = false; model.ValidationError = ValidationExceptionError.res_09; } } catch (Exception ex) { model.IsRequestSuccesful = false; model.ValidationError = ExceptionValidationHelper.GetExceptionSource(ex); return(Json(model)); } return(Json(model)); }
public CreateOrderDocument GetOrderDocumentData(string OrderDocXML) { CreateOrderDocument _coData = new CreateOrderDocument(); ObjectParameter opExportPath = new ObjectParameter("p_cExportPath", ""); ObjectParameter opPDFFileName = new ObjectParameter("p_cKey", ""); ObjectParameter opErrorDesc = new ObjectParameter("p_cError", ""); var obj = context.DodajPantheonDokument(OrderDocXML, opExportPath, opPDFFileName, opErrorDesc); string sExportPath = Convert.ToString(opExportPath.Value); string sPDFFileName = Convert.ToString(opPDFFileName.Value); string sErrorDesc = Convert.ToString(opErrorDesc.Value); DataTypesHelper.LogThis("Številka naročilnice: " + sPDFFileName); if (sErrorDesc.Length > 0) { DataTypesHelper.LogThis("Error create naročilnica : " + sErrorDesc); } if (sErrorDesc.Length > 0) { throw new Exception(ValidationExceptionError.res_28 + "<br><br>" + sErrorDesc); } _coData.ExportPath = sExportPath; _coData.PDFFile = sPDFFileName; _coData.ErrorDesc = sErrorDesc; return(_coData); }
public IHttpActionResult SaveRecall([FromBody] object recallData) { WebResponseContentModel <RecallFullModel> model = null; try { DataTypesHelper.LogThis("SaveRecall : (model.Content.OdpoklicID) - Začetek!"); model = JsonConvert.DeserializeObject <WebResponseContentModel <RecallFullModel> >(recallData.ToString()); if (model.Content != null) { var employee = employeeRepo.GetEmployeeByID(model.Content.UserID); if (model.Content.OdpoklicID > 0)//We update existing record in DB { DataTypesHelper.LogThis("SaveRecall1 : (model.Content.OdpoklicID) :" + model.Content.OdpoklicID.ToString()); recallRepo.SaveRecall(model.Content); RecallStatus stat = recallRepo.GetRecallStatusByCode(Enums.StatusOfRecall.V_ODOBRITEV.ToString()); if (model.Content.RecallStatusChanged && (stat != null && model.Content.StatusID == stat.StatusOdpoklicaID)) { //messageEventsRepo.CreateEmailForRecallStatusChanged(model.Content); DataTypesHelper.LogThis("SaveRecall : " + stat.Koda); messageEventsRepo.CreateEmailForLeaderToApproveRecall(model.Content); } stat = recallRepo.GetRecallStatusByCode(Enums.StatusOfRecall.RAZPIS_PREVOZNIK.ToString()); if (model.Content.RecallStatusChanged && (stat != null && model.Content.StatusID == stat.StatusOdpoklicaID)) { DataTypesHelper.LogThis("SaveRecall : " + stat.Koda); messageEventsRepo.CreateEmailForCarriers(model.Content, employee); } } else // We add and save new recod to DB { DataTypesHelper.LogThis("SaveRecall2 : (model.Content.OdpoklicID) :" + model.Content.OdpoklicID.ToString()); model.Content.OdpoklicID = recallRepo.SaveRecall(model.Content, false); RecallStatus stat = recallRepo.GetRecallStatusByCode(Enums.StatusOfRecall.V_ODOBRITEV.ToString()); if (stat != null && model.Content.StatusID == stat.StatusOdpoklicaID) { DataTypesHelper.LogThis("SaveRecall2 : " + stat.Koda); messageEventsRepo.CreateEmailForLeaderToApproveRecall(model.Content); } stat = recallRepo.GetRecallStatusByCode(Enums.StatusOfRecall.RAZPIS_PREVOZNIK.ToString()); if (model.Content.RecallStatusChanged && (stat != null && model.Content.StatusID == stat.StatusOdpoklicaID)) { DataTypesHelper.LogThis("SaveRecall3 : " + stat.Koda); messageEventsRepo.CreateEmailForCarriers(model.Content, employee); } } model.IsRequestSuccesful = true; } else { model.IsRequestSuccesful = false; model.ValidationError = ValidationExceptionError.res_09; } } catch (Exception ex) { model.IsRequestSuccesful = false; model.ValidationError = ExceptionValidationHelper.GetExceptionSource(ex); return(Json(model)); } return(Json(model)); }
public List <OrderPositionModelNew> GetListOfOpenedOrderPositions(string supplier, int clientID = 0) {//TODO: pridobimo še vse pozicije iz tabele lastna zaloga če je izbran dobavitelj iz naše tabele stranka_otp i da je tipa SKLADISCE try { if (supplier == null || supplier.Length == 0) { return(null); } DataTypesHelper.LogThis("GetListOfOpenedOrderPositions for : " + supplier); supplier = supplier.Replace("|", "&"); var query = from np in context.SeznamPozicijOdprtihNarocilnicGledeNaDobavitelja(supplier.Trim()) select new OrderPositionModelNew { UniqueID = string.Concat("-", np.Narocilnica, SqlFunctions.StringConvert((double)np.St_Pozicija)), //UniqueID = SqlFunctions.StringConvert((double)np.St_Pozicija), Artikel = np.Artikel, Datum_Dobave = np.Datum_Dobave, Datum_narocila = np.Datum_narocila.HasValue ? np.Datum_narocila.Value : DateTime.MinValue, Dobavitelj = np.Dobavitelj, Kupec = np.Kupec, Naroceno = np.Naroceno, Narocilnica = np.Narocilnica, Order_Confirm = np.Order_Confirm, Prevzeto = np.Prevzeto, Razlika = np.Razlika.HasValue ? np.Razlika.Value : 0, St_Pozicija = np.St_Pozicija, Tovarna = np.Tovarna, Tip = np.Tip, Zaloga = np.Zaloga.HasValue ? np.Zaloga.Value : 0, Interno = np.Interno, Dovoljeno_Odpoklicati = np.Dovoljeno_odpoklicati, Proizvedeno = np.Proizvedeno, Kategorija = np.Kategorija == null ? "" : np.Kategorija, Ident = np.Ident, Kupec_Kraj = np.Kupec_Kraj, Kupec_Naslov = np.Kupec_Naslov, Kupec_Posta = np.Kupec_Posta, EnotaMere = np.Enota_Mere }; //var pos = query.Where(o => o.Order_Confirm == "15-4988/30").FirstOrDefault(); List <OrderPositionModelNew> list = query.ToList(); int count = 1; foreach (var item in list) { item.tempID = count; count++; } //DataTypesHelper.LogThis("count : " + count); string kodaPotrjen = Enums.StatusOfRecall.POTRJEN.ToString(); int statusPotrjen = context.StatusOdpoklica.Where(so => so.Koda == kodaPotrjen).FirstOrDefault().StatusOdpoklicaID; string kodaDelnoPrevzet = Enums.StatusOfRecall.DELNO_PREVZET.ToString(); int statusDelnoPrevzet = context.StatusOdpoklica.Where(so => so.Koda == kodaDelnoPrevzet).FirstOrDefault().StatusOdpoklicaID; //DataTypesHelper.LogThis("Before CheckPositionQuantity"); CheckPositionQuantity(list, statusPotrjen, statusDelnoPrevzet); //DataTypesHelper.LogThis("After CheckPositionQuantity"); // preverimo za katero aplikacijo gre //DataTypesHelper.LogThis("Before SetApplicationToOrderPosition"); list = SetApplicationToOrderPosition(list); //DataTypesHelper.LogThis("After SetApplicationToOrderPosition"); list = list.OrderBy(p => p.Datum_Dobave).OrderBy(p1 => p1.SortGledeNaTipApp).ToList(); #region /*for (int i = list.Count - 1; i >= 0; i--) * { * OrderPositionModelNew item = list[i]; * //OdpoklicPozicija rPos = context.OdpoklicPozicija.Where(op => op.MaterialIdent == item.Ident && op.Odpoklic.StatusID == statusPotrjen).OrderByDescending(op => op.DatumVnosa).FirstOrDefault(); * List<OdpoklicPozicija> currentKolicinaOTPList = context.OdpoklicPozicija.Where(op => op.MaterialIdent == item.Ident && * !op.StatusPrevzeto.Value && * (op.Odpoklic.StatusID == statusPotrjen || op.Odpoklic.StatusID == statusDelnoPrevzet)).ToList(); * * decimal? currentRecallQuantity = 0; * if (currentKolicinaOTPList.Count > 0) * currentRecallQuantity = currentKolicinaOTPList.Sum(op => op.Kolicina); * * //pridobimo vse pozicije odpoklicev za posamezno pozicijo naročilnice * List<OdpoklicPozicija> posByOrderPosNum = context.OdpoklicPozicija.Where(op => op.MaterialIdent == item.Ident && * op.NarociloID == item.Narocilnica && * op.NarociloPozicijaID == item.St_Pozicija && * !op.StatusPrevzeto.Value && * (op.Odpoklic.StatusID == statusPotrjen || op.Odpoklic.StatusID == statusDelnoPrevzet)).ToList(); * * //seštejemo odpoklicano količino za pozicijo naročilnice * item.OdpoklicKolicinaOTP = posByOrderPosNum.Sum(op => op.Kolicina); * * if (item.OdpoklicKolicinaOTP == item.Naroceno) * list.RemoveAt(i); * else if (currentRecallQuantity.HasValue && item.Naroceno == (currentRecallQuantity + item.Zaloga)) * { * item.VsotaOdpoklicKolicinaOTP = (currentRecallQuantity.Value - item.OdpoklicKolicinaOTP);//rPos.KolicinaOTP.Value; * } * else if (currentRecallQuantity.HasValue && currentRecallQuantity.Value < item.Naroceno) * { * //list[i].Naroceno -= rPos.KolicinaOTP.HasValue ? rPos.KolicinaOTP.Value : 0; * //list[i].Razlika = list[i].Naroceno - list[i].Prevzeto;//TODO: Kaj če bo večja količina prevzeta kot naročena? (negativna razlika????) * item.VsotaOdpoklicKolicinaOTP = (currentRecallQuantity.Value - item.OdpoklicKolicinaOTP); * } * else if (currentRecallQuantity.HasValue && currentRecallQuantity.Value > item.Naroceno) * { * item.VsotaOdpoklicKolicinaOTP = (currentRecallQuantity.Value - item.OdpoklicKolicinaOTP); * //TODO: na večih pozicijah naročilnic potrebno odšteti in po potrebi le-to odstraniti iz seznama * /**decimal tempQuantity = rPos.KolicinaOTP.Value; * for (int j = list.Count - 1; j >= 0; j--) * { * OrderPositionModelNew obj = list[j]; * if (obj.Ident == item.Ident) * { * if (tempQuantity > obj.Naroceno) * { * tempQuantity -= obj.Naroceno; * list.RemoveAt(j); * } * else if (tempQuantity == obj.Naroceno) * { * tempQuantity -= obj.Naroceno; * list.RemoveAt(j); * } * else if (tempQuantity < obj.Naroceno) * { * obj.Naroceno -= tempQuantity; * obj.Razlika = obj.Naroceno - obj.Prevzeto;//TODO: Kaj če bo večja količina prevzeta kot naročena? (negativna razlika????) * } * } * } * } * }*/ #endregion //DataTypesHelper.LogThis("Before clientID : " + clientID.ToString()); if (clientID > 0) { var lastnoSkladisce = from ow in context.LastnaZaloga where ow.LastnoSkladisceID == clientID select new OrderPositionModelNew { Artikel = ow.Material, // Datum_Dobave = np.Datum_Dobave, //Datum_narocila = np.Datum_narocila.HasValue ? np.Datum_narocila.Value : DateTime.MinValue, //Dobavitelj = np.Dobavitelj, Kupec = ow.KupecNaziv, Naroceno = ow.KolicinaIzNarocila, Narocilnica = ow.NarociloID, Order_Confirm = ow.OC, Prevzeto = ow.KolicinaPrevzeta.HasValue ? ow.KolicinaPrevzeta.Value : 0, Razlika = ow.KolicinaRazlika.HasValue ? ow.KolicinaRazlika.Value : 0, St_Pozicija = ow.NarociloPozicijaID, //Tovarna = np.Tovarna, Tip = ow.TipNaziv, Zaloga = ow.TrenutnaZaloga.HasValue ? ow.TrenutnaZaloga.Value : 0, Interno = ow.Interno, Dovoljeno_Odpoklicati = ow.OptimalnaZaloga.HasValue ? (int)ow.OptimalnaZaloga.Value : 0, Proizvedeno = ow.Proizvedeno.HasValue ? ow.Proizvedeno.Value : 0, Ident = ow.MaterialIdent, Kupec_Kraj = ow.KupecKraj, Kupec_Naslov = ow.KupecNaslov, Kupec_Posta = ow.KupecPosta, OdpoklicID = ow.OdpoklicID, EnotaMere = ow.EnotaMere }; List <OrderPositionModelNew> newList = lastnoSkladisce.ToList(); foreach (var item in newList) { item.tempID = count; count++; } CheckPositionQuantity(newList, statusPotrjen, statusDelnoPrevzet, true); list.AddRange(newList); } //DataTypesHelper.LogThis("After Client"); return(list); } catch (Exception ex) { throw new Exception(ValidationExceptionError.res_06, ex); } }
public void ProcessAutoMessage(SystemMessageEvents message) { DataTypesHelper.LogThis("ProcessAutoMessage Method - 1 : BEFORE Open templatePath"); string templatePath = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["EMPLOYEE_MESSAGE_TEMPLATE"].ToString()).Replace("\"", "\\"); StreamReader reader = new StreamReader(templatePath); DataTypesHelper.LogThis("ProcessAutoMessage Method - 2 : AFTER Open templatePath"); try { DataTypesHelper.LogThis("ProcessAutoMessage Method - 3 : BEFORE get avtomatikaList"); List <Avtomatika> avtomatikaList = context.Avtomatika.Where(a => a.OsebaID == message.MasterID && a.Status == (int)Enums.SystemMessageEventStatus.UnProcessed).ToList(); DataTypesHelper.LogThis("ProcessAutoMessage Method - 4 : After get avtomatikaList"); DataTypesHelper.LogThis("ProcessAutoMessage Method - 5 : BEFORE get Get Oseba by message.MasterID"); Osebe oseba = context.Osebe.Where(o => o.idOsebe == message.MasterID).FirstOrDefault(); //DataTypesHelper.LogThis("After getting avtomatika values from DB - " + avtomatikaList.Count.ToString()); DataTypesHelper.LogThis("BEFORE reading template string"); string templateString = reader.ReadToEnd(); DataTypesHelper.LogThis("AFTER reading template string."); //DataTypesHelper.LogThis("Before if! AvtomatikaList count =" + avtomatikaList.Count.ToString() + " - Oseba :" + (oseba != null).ToString() + " - OsebaID: " + message.MasterID.ToString()); if (avtomatikaList.Count > 0 && oseba != null) { //DataTypesHelper.LogThis("*********Before ReplaceDefaultValuesInTemplate**********"); templateString = ReplaceDefaultValuesInTemplate(oseba, templateString); DataTypesHelper.LogThis("BEFORE ConstructTemplate for clients."); int index = templateString.IndexOf("##INSERT_CLIENTS_HERE##"); //DataTypesHelper.LogThis("*********Before ConstructTemplate**********"); templateString = templateString.Insert(index, ConstructTemplate(avtomatikaList, templateString)); DataTypesHelper.LogThis("AFTER ConstructTemplate for clients."); templateString = templateString.Replace("##INSERT_CLIENTS_HERE##", ""); //DataTypesHelper.LogThis("*****After ConstructTemplate method IN ProcessAutoMessage***** - user email : " + avtomatikaList[0].Osebe.Email + "Stopnja nadrejenega : " + avtomatikaList[0].StopnjaNadrejenega.ToString()); DataTypesHelper.LogThis("BEFORE Saving item to SystemEmailMessage table."); SaveToSystemEmailMessage(oseba.Email, templateString, message.tsIDOsebe, avtomatikaList[0].StopnjaNadrejenega, SystemEmailMessageResource.res_02); DataTypesHelper.LogThis("AFTER Saving item to SystemEmailMessage table."); } int count = 0; DataTypesHelper.LogThis("BEFORE update avtomatikaList."); //update Avtomatika table status foreach (var item in avtomatikaList) { //var original = context.Avtomatika.Where(av => av.AvtomatikaID == item.AvtomatikaID).FirstOrDefault(); // if (original != null) // { context.Entry(item).Entity.Status = (int)Enums.SystemMessageEventStatus.Processed; count++; DataTypesHelper.LogThis("Trenutni count : " + count); // } } DataTypesHelper.LogThis("Avtomatika / Count :" + count.ToString() + "\r\n" + "AvtomatikaList count : " + avtomatikaList.Count.ToString()); context.SaveChanges(); DataTypesHelper.LogThis("BEFORE update UpdateSystemMessageEvents status."); //update status message.Status = (int)Enums.SystemMessageEventStatus.Processed; UpdateSystemMessageEvents(message); DataTypesHelper.LogThis("AFTER update UpdateSystemMessageEvents status."); } catch (Exception ex) { throw new Exception(ex.Message); } finally { reader.Close(); } }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { if (isSending) { return; } isSending = true; SmtpClient client = new SmtpClient(); try { client.Host = ConfigurationManager.AppSettings["SmtpHost"]; client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);//Port 465 (SSL required) client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SmtpEnableSsl"]); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpTimeout"]); if (Convert.ToBoolean(ConfigurationManager.AppSettings["HasCredentials"])) { client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]); } else { client.UseDefaultCredentials = true; } systemEmailMessageRepo.UpdateFailedMessges(); List <SystemEmailMessage> emailList = systemEmailMessageRepo.GetUnprocessedEmails(); DataTypesHelper.LogThis("List of Unproccessed mail's. Count: " + emailList.Count.ToString()); foreach (var item in emailList) { SendMessages(client, item, null); } } catch (Exception ex) { DataTypesHelper.LogThis("CRM:" + ex.Message); } finally { isSending = false; } try { otpSystemEmailMessageRepo = kernel.Get <ISystemEmailMessageRepository_OTP>(); //OTP MAIL SETTINGS client = new SmtpClient(); client.Host = ConfigurationManager.AppSettings["SmtpHostOTP"]; client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPortOTP"]);//Port 465 (SSL required) client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SmtpEnableSslOTP"]); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpTimeout"]); if (Convert.ToBoolean(ConfigurationManager.AppSettings["HasCredentialsOTP"])) { client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UsernameOTP"], ConfigurationManager.AppSettings["PasswordOTP"]); } else { client.UseDefaultCredentials = true; } otpSystemEmailMessageRepo.UpdateFailedMessges(); List <SystemEmailMessage_OTP> otpEmailList = otpSystemEmailMessageRepo.GetUnprocessedEmails(); DataTypesHelper.LogThis("List of OTP Unproccessed mail's. Count: " + otpEmailList.Count.ToString()); foreach (var item in otpEmailList) { SendMessages(client, null, item); } } catch (Exception ex) { DataTypesHelper.LogThis("OTP : " + ex.Message); } finally { isSending = false; } try { pdoSystemEmailMessageRepo = kernel.Get <ISystemEmailMessageRepository_PDO>(); pdoSettingsRepo = kernel.Get <ISettingsRepository>(); DataTypesHelper.LogThis("PDO Mailing setup"); //PDO MAIL SETTINGS client = new SmtpClient(); client.Host = ConfigurationManager.AppSettings["SmtpHostPDO"]; client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPortPDO"]);//Port 465 (SSL required) client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SmtpEnableSslPDO"]); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpTimeout"]); if (Convert.ToBoolean(ConfigurationManager.AppSettings["HasCredentialsPDO"])) { client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UsernamePDO"], ConfigurationManager.AppSettings["PasswordPDO"]); } else { client.UseDefaultCredentials = true; } pdoSystemEmailMessageRepo.UpdateFailedMessges(); List <SystemEmailMessage_PDO> pdoEmailList = pdoSystemEmailMessageRepo.GetUnprocessedEmails(); DataTypesHelper.LogThis("List of PDO Unproccessed mail's. Count: " + pdoEmailList.Count.ToString()); foreach (var item in pdoEmailList) { SendMessages(client, null, null, item); } } catch (Exception ex) { DataTypesHelper.LogThis("PDO" + ex.Message); } finally { isSending = false; } try { nozSystemEmailMessageRepo = kernel.Get <ISystemEmailMessageRepository_NOZ>(); DataTypesHelper.LogThis("NOZ Mailing setup"); // NOZ MAIL SETTINGS client = new SmtpClient(); client.Host = ConfigurationManager.AppSettings["SmtpHostNOZ"]; DataTypesHelper.LogThis("NOZ - 1"); client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPortNOZ"]);//Port 465 (SSL required) DataTypesHelper.LogThis("NOZ - 2"); client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SmtpEnableSslNOZ"]); DataTypesHelper.LogThis("NOZ - 3"); client.DeliveryMethod = SmtpDeliveryMethod.Network; DataTypesHelper.LogThis("NOZ - 4"); client.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpTimeout"]); DataTypesHelper.LogThis("NOZ - 5"); if (Convert.ToBoolean(ConfigurationManager.AppSettings["HasCredentialsNOZ"])) { client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["UsernameNOZ"], ConfigurationManager.AppSettings["PasswordNOZ"]); } else { client.UseDefaultCredentials = true; } DataTypesHelper.LogThis("NOZ - 6"); nozSystemEmailMessageRepo.UpdateFailedMessges(); DataTypesHelper.LogThis("NOZ - 7"); List <SystemEmailMessage_NOZ> nozEmailList = nozSystemEmailMessageRepo.GetUnprocessedEmails(); DataTypesHelper.LogThis("List of NOZ Unproccessed mail's. Count: " + nozEmailList.Count.ToString()); foreach (var item in nozEmailList) { SendMessages(client, null, null, null, item); } } catch (Exception ex) { DataTypesHelper.LogThis("NOZ: " + ex.Message); } finally { isSending = false; } }
private void SendMessages(SmtpClient client, SystemEmailMessage item = null, SystemEmailMessage_OTP otpItem = null, SystemEmailMessage_PDO pdoItem = null, SystemEmailMessage_NOZ nozItem = null) { bool isOTPitem = false; bool isPDOitem = false; bool isNOZItem = false; try { if (otpItem != null) { isOTPitem = true; } else if (pdoItem != null) { isPDOitem = true; } else if (nozItem != null) { isNOZItem = true; } //if (String.IsNullOrEmpty(isOTPitem ? otpItem.EmailTo : (isPDOitem ? ((pdoItem.TOEmails != null && pdoItem.TOEmails.Length > 0) ? pdoItem.TOEmails : pdoItem.EmailTo) : (isNOZItem ? nozItem.EmailTo : item.EmailTo)))) if (String.IsNullOrEmpty(isOTPitem ? otpItem.EmailTo : (isPDOitem ? pdoItem.EmailTo : (isNOZItem ? nozItem.EmailTo : item.EmailTo)))) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isNOZItem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Processed; } DataTypesHelper.LogThis("Couldn't send email! Email to is empty"); } else { string sender = "", emailTitle = "", emailTo = "", emailSubject = "", emailBody = ""; if (isOTPitem) { DataTypesHelper.LogThis("OTP ITEM!"); sender = ConfigurationManager.AppSettings["SenderOTP"].ToString(); //sender = otpItem.EmailFrom; emailTitle = "(" + otpItem.EmailFrom + ") - " + ConfigurationManager.AppSettings["EmailTitleOTP"].ToString(); emailTo = otpItem.EmailTo; emailSubject = otpItem.EmailSubject; emailBody = otpItem.EmailBody; } else if (isPDOitem) { DataTypesHelper.LogThis("PDO ITEM"); if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseUserEmailSettings"])) { if (pdoItem.OsebaEmailFromID.HasValue) { SettingsModel set = pdoSettingsRepo.GetLatestSettings(); string host = String.IsNullOrEmpty(set.EmailStreznik) ? pdoItem.Osebe_PDO.EmailStreznik : set.EmailStreznik; //int port = 587;//set.EmailVrata > 0 ? set.EmailVrata : pdoItem.Osebe_PDO.EmailVrata.Value; int port = set.EmailVrata > 0 ? set.EmailVrata : pdoItem.Osebe_PDO.EmailVrata.Value; //bool sslEnable = false;//!set.EmailSifriranjeSSL ? pdoItem.Osebe_PDO.EmailSifriranjeSSL.Value : set.EmailSifriranjeSSL; bool sslEnable = set.EmailSifriranjeSSL ? pdoItem.Osebe_PDO.EmailSifriranjeSSL.Value : set.EmailSifriranjeSSL; //var credentials = new NetworkCredential("*****@*****.**"/*pdoItem.Osebe_PDO.Email, "Geslo123."/*pdoItem.Osebe_PDO.EmailGeslo); var credentials = new NetworkCredential(pdoItem.Osebe_PDO.Email, pdoItem.Osebe_PDO.EmailGeslo); client = new SmtpClient { Host = host, Port = port, EnableSsl = sslEnable, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = credentials }; } } string emailTitleOseba = pdoItem.Osebe_PDO != null ? pdoItem.Osebe_PDO.Ime + " " + pdoItem.Osebe_PDO.Priimek : ConfigurationManager.AppSettings["EmailTitlePDO"].ToString();; sender = pdoItem.OsebaEmailFromID != null ? pdoItem.Osebe_PDO.Email : ConfigurationManager.AppSettings["SenderPDO"].ToString(); emailTitle = emailTitleOseba; emailTo = pdoItem.EmailTo; emailSubject = pdoItem.EmailSubject; emailBody = pdoItem.EmailBody; } else if (isNOZItem) { sender = ConfigurationManager.AppSettings["SenderNOZ"].ToString(); //sender = otpItem.EmailFrom; //string emailTitleOseba = nozItem.Osebe_PDO != null ? pdoItem.Osebe_PDO.Ime + " " + pdoItem.Osebe_PDO.Priimek : ConfigurationManager.AppSettings["EmailTitlePDO"].ToString(); ; //sender = nozItem.OsebaEmailFromID != null ? nozItem.Osebe_PDO.Email : ConfigurationManager.AppSettings["SenderNOZ"].ToString(); emailTitle = "(" + nozItem.EmailFrom + ") - " + ConfigurationManager.AppSettings["EmailTitleNOZ"].ToString(); emailTo = nozItem.EmailTo; emailSubject = nozItem.EmailSubject; emailBody = nozItem.EmailBody; } else { sender = ConfigurationManager.AppSettings["Sender"].ToString(); emailTitle = ConfigurationManager.AppSettings["EmailTitle"].ToString(); emailTo = item.EmailTo; emailSubject = item.EmailSubject; emailBody = item.EmailBody; } MailMessage message = new MailMessage(); // preverimo če je emailTO prazen pomeni, da vazame list pošiljateljev if (emailTo.Length > 0) { if (emailTo != null && emailTo.Length > 0) { string[] splitTOEmails = emailTo.Split(';'); if (splitTOEmails.Length > 1) { foreach (var email in splitTOEmails) { MailAddress ToEmail = new MailAddress(email); message.To.Add(ToEmail); } } else { message.To.Add(emailTo); } } } message.Sender = new MailAddress(sender); message.From = new MailAddress(sender, emailTitle); message.Subject = emailSubject; message.IsBodyHtml = true; message.Body = emailBody; message.BodyEncoding = Encoding.UTF8; if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Processed; } // Boris 20.11.2019: attachments string attachmentFilename = ""; if (isOTPitem || isPDOitem || isNOZItem) { attachmentFilename = isOTPitem ? otpItem.Attachments : (isPDOitem ? pdoItem.Attachments : nozItem.Attachments); } else { } // Boris 27.04.2020: CC seznam emailov if (isPDOitem) { if (pdoItem.CCEmails != null && pdoItem.CCEmails.Length > 0) { string[] splitCCEmails = pdoItem.CCEmails.Split(';'); foreach (var email in splitCCEmails) { MailAddress copy = new MailAddress(email); message.CC.Add(copy); } } } if (!string.IsNullOrEmpty(attachmentFilename)) { string[] splitAttachments = attachmentFilename.Split(';'); foreach (var fileAttachment in splitAttachments) { if (File.Exists(attachmentFilename)) { Attachment attachment = new Attachment(fileAttachment, MediaTypeNames.Application.Octet); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = File.GetCreationTime(fileAttachment); disposition.ModificationDate = File.GetLastWriteTime(fileAttachment); disposition.ReadDate = File.GetLastAccessTime(fileAttachment); disposition.FileName = Path.GetFileName(fileAttachment); disposition.Size = new FileInfo(fileAttachment).Length; disposition.DispositionType = DispositionTypeNames.Attachment; message.Attachments.Add(attachment); } } } // ------------------------------------------------------------------------------------ client.Send(message); } if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } catch (SmtpFailedRecipientsException ex) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("Couldn't send the email to receipient: " + item.EmailTo + "\n" + ex.Message); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } catch (SmtpException ex) { if (ex.Message.Contains("Mailbox unavailable")) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("Could not send the email to receipient: " + item.EmailTo); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } else { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("SmtpException: " + ex.Message); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } } catch (Exception ex) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Error; } if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } DataTypesHelper.LogThis("LOG1: " + ex.Message); } }
public void ProcessEventMessage(SystemMessageEvents message, Enums.SystemMessageEventCodes eventCode = Enums.SystemMessageEventCodes.EVENT_DOGODEK) { StreamReader reader = null; try { //DataTypesHelper.LogThis("*****IN Method ProcessEventMessage*****"); int employeeHierarchyLevel = GetEmployeeHierarchyLevel(eventCode); string emailSubject = SystemEmailMessageResource.res_03; string templatePath = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["NEW_EVENT_TEMPLATE"].ToString()).Replace("\"", "\\"); DataTypesHelper.LogThis(AppDomain.CurrentDomain.BaseDirectory); Dogodek dogodek = context.Dogodek.Where(dog => dog.idDogodek == message.MasterID).FirstOrDefault(); EventMessageTemplateModel modelForTemplate = new EventMessageTemplateModel(); if (EventPreparationOrReport(eventCode)) { templatePath = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["MEETING_WARNING_TEMPLATE"].ToString()).Replace("\"", "\\"); modelForTemplate.Tip = EventPreparation(eventCode) ? "Priprava" : "Poročilo"; modelForTemplate.Zamuda = DateTime.Now.Subtract(dogodek.DatumOtvoritve.Value).Days; modelForTemplate.Otvoritev = dogodek.DatumOtvoritve.Value; modelForTemplate.ServerTag = ConfigurationManager.AppSettings["ServerTag"].ToString(); emailSubject = SystemEmailMessageResource.res_04.Replace("%Tip%", modelForTemplate.Tip); } //DataTypesHelper.LogThis("*****Afer if statement of checking if event is about priprava or Poročilo***** EVENT ID: " + dogodek.idDogodek.ToString()); //DataTypesHelper.LogThis("*****TemplatePath: ********" + templatePath); reader = new StreamReader(templatePath); //DataTypesHelper.LogThis("***1***"); modelForTemplate.idDogodek = dogodek.idDogodek; //DataTypesHelper.LogThis("***2***"); modelForTemplate.ImeIzvajalec = dogodek.Osebe != null ? dogodek.Osebe.Ime : ""; //DataTypesHelper.LogThis("***3***"); modelForTemplate.PriimekIzvajalec = dogodek.Osebe != null ? dogodek.Osebe.Priimek : ""; //DataTypesHelper.LogThis("***4***"); modelForTemplate.ImeSkrbnik = dogodek.Osebe1 != null ? dogodek.Osebe1.Ime : ""; //DataTypesHelper.LogThis("***5***"); modelForTemplate.PriimekSkrbnik = dogodek.Osebe1 != null ? dogodek.Osebe1.Priimek : ""; //DataTypesHelper.LogThis("***6***"); modelForTemplate.Kategorija = dogodek.Kategorija != null ? dogodek.Kategorija.Naziv : ""; //DataTypesHelper.LogThis("***7***"); modelForTemplate.KategorijaKoda = dogodek.Kategorija != null ? dogodek.Kategorija.Koda : ""; //DataTypesHelper.LogThis("***8***"); modelForTemplate.NazivPrvi = dogodek.Stranka != null ? dogodek.Stranka.NazivPrvi : ""; //DataTypesHelper.LogThis("***9***"); modelForTemplate.Opis = dogodek.Opis; //DataTypesHelper.LogThis("***10***"); modelForTemplate.EmailTo = dogodek.Osebe != null ? dogodek.Osebe.Email : ""; //DataTypesHelper.LogThis("***11***"); modelForTemplate.Rok = dogodek.Rok.HasValue ? dogodek.Rok.Value : DateTime.MinValue; //DataTypesHelper.LogThis("***12***"); modelForTemplate.Status = dogodek.StatusDogodek != null ? dogodek.StatusDogodek.Naziv : ""; //DataTypesHelper.LogThis("***13***"); string templateString = reader.ReadToEnd(); //DataTypesHelper.LogThis("*****Before ReplaceDefaultValuesInTemplate*****"); templateString = ReplaceDefaultValuesInTemplate(modelForTemplate, templateString); //DataTypesHelper.LogThis("*****After ReplaceDefaultValuesInTemplate*****"); if (String.IsNullOrEmpty(modelForTemplate.Opis)) { templateString = templateString.Replace("$%Opis%$ ", ""); } //DataTypesHelper.LogThis("*****Before if statement Sporocila*****"); if (dogodek.Sporocila != null && eventCode.Equals(Enums.SystemMessageEventCodes.EVENT_DOGODEK)) { foreach (var item in dogodek.Sporocila) { int index = templateString.IndexOf("##INSERT_MESSAGE_HERE##"); templateString = templateString.Insert(index, item.OpisDel + "<br />"); } } //DataTypesHelper.LogThis("*****After if statement Sporocila*****"); templateString = templateString.Replace("##INSERT_MESSAGE_HERE##", ""); if (dogodek.Osebe != null) { SaveToSystemEmailMessage(dogodek.Osebe.Email, templateString, dogodek.Osebe.idOsebe, employeeHierarchyLevel, emailSubject); } //DataTypesHelper.LogThis("*****After SaveSystemEmailMessage*****"); //TODO: Update Avtomatika tabela //update status message.Status = (int)Enums.SystemMessageEventStatus.Processed; //DataTypesHelper.LogThis("*****Before UpdateSysteMessageEvents*****"); UpdateSystemMessageEvents(message); //DataTypesHelper.LogThis("*****After UpdateSysteMessageEvents*****"); } catch (Exception ex) { DataTypesHelper.LogThis("Error:" + ex.Message); throw new Exception(ex.Message); } finally { reader.Close(); } }
public List <SystemMessageEvents> GetUnProcessedMesseges() { DataTypesHelper.LogThis("*****IN GetUnProcessedMesseges*****"); return(context.SystemMessageEvents.Where(sme => sme.Status.Value == (int)Enums.SystemMessageEventStatus.UnProcessed).ToList()); }
private string ConstructTemplate(List <Avtomatika> list, string parentTemplate) { try { string templatePath = (AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["EMPLOYEE_PARTIAL_TEMPLATE"].ToString()).Replace("\"", "\\"); StreamReader reader = new StreamReader(templatePath); string clientPartialTemplate = reader.ReadToEnd(); reader.Close(); clientPartialTemplate = clientPartialTemplate.Replace("$%ServerTag%$", ConfigurationManager.AppSettings["ServerTag"].ToString()); string concatenateTemplate = ""; var groupByClient = list.GroupBy(ag => ag.Dogodek.idStranka).ToList(); //DataTypesHelper.LogThis("*****ConstructTemplate before first foreach*****"); foreach (var item in groupByClient)//Number of clients { //DataTypesHelper.LogThis("*****ConstructTemplate IN first foreach*****" + " clientID : " + item.Key.Value.ToString() + " Dogodek : " + item.Select(o => o.Dogodek).FirstOrDefault().idDogodek); Stranka stranka = item.Select(o => o.Dogodek).FirstOrDefault().Stranka; if (stranka == null) { break; //če stranka ne obstaja v bazi zaključimo for zanko in vrenmo template } concatenateTemplate += ReplaceDefaultValuesInTemplate(stranka, clientPartialTemplate); int itemCount = 1; //DataTypesHelper.LogThis("*****ConstructTemplate before second foreach - number of clients: *****" + groupByClient.Count.ToString()); foreach (var avtomatika in item.ToList()) { if (avtomatika.Dogodek.Kategorija != null)//če so določene posamezne kategorije na katerih je bil zaznan padec prodaje { //DataTypesHelper.LogThis("*****ConstructTemplate IN second foreach***** EVENT ID" + avtomatika.DogodekID.ToString() + " : items: " + item.ToList().Count.ToString() + " clientID : " + item.Key.Value.ToString() + " employeeID : " + avtomatika.OsebaID.ToString()); int index = concatenateTemplate.IndexOf("##INSERT_CATEGORIES_HERE##"); //DataTypesHelper.LogThis("*****1 - indexOF method***** : " + index.ToString()); if (avtomatika.Equals(item.ToList().Last()) && (itemCount % 2 != 0 || item.ToList().Count == 1)) { //DataTypesHelper.LogThis("*****2 - Dogodek Values: ***** : " + avtomatika.Dogodek.idDogodek.ToString() + " - " + avtomatika.Dogodek.Kategorija.Naziv); concatenateTemplate = concatenateTemplate.Insert(index, "<div class='catFullWidth'>" + avtomatika.Dogodek.Kategorija.Naziv + "<br />" + " <strong>PADEC</strong></div>"); break; } //DataTypesHelper.LogThis("*****3 - after if***** : "); if (itemCount % 2 == 0) { concatenateTemplate = concatenateTemplate.Insert(index, "<div class='catOneHalfRight'>" + avtomatika.Dogodek.Kategorija.Naziv + "<br />" + " <strong>PADEC</strong></div>"); } else { concatenateTemplate = concatenateTemplate.Insert(index, "<div class='catOneHalfLeft'>" + avtomatika.Dogodek.Kategorija.Naziv + "<br />" + " <strong>PADEC</strong></div>"); } //DataTypesHelper.LogThis("*****4 - before itemCount++***** : " + itemCount.ToString()); } itemCount++; } //DataTypesHelper.LogThis("*****ConstructTemplate AFTER first foreach*****"); concatenateTemplate = concatenateTemplate.Replace("##INSERT_CATEGORIES_HERE##", ""); } return(concatenateTemplate); } catch (Exception ex) { DataTypesHelper.LogThis("*****Error - ***** : " + ex.Message + " " + ex.InnerException.Message + " " + ex.StackTrace); throw new Exception("", ex); } }