public String Render(TemplateModel templateModel) { var assembly = Assembly.GetExecutingAssembly(); string template; using (var sr = new StreamReader(assembly.GetManifestResourceStream("HotGlue.Generator.MVCRoutes.Templates.Routing.razor"))) { template = sr.ReadToEnd(); } var config = new TemplateServiceConfiguration { BaseTemplateType = typeof (JavaScriptRoutingTemplateBase<>) }; string result; try { using (var service = new TemplateService(config)) { Razor.SetTemplateService(service); result = Razor.Parse(template, templateModel); return result; } } catch (TemplateCompilationException ex) { foreach (var error in ex.Errors) { Console.WriteLine(error.ErrorText); } throw; } }
public override Passbook.Generator.PassGeneratorRequest GetPass(string serialNumber) { PassGeneratorRequest request = new PassGeneratorRequest(); request.PassTypeIdentifier = PassTypeIdentifier; request.SerialNumber = Guid.NewGuid().ToString("D"); TemplateModel parameters = new TemplateModel(); parameters.AddField("origin", FieldAttribute.Label, "San Francisco"); parameters.AddField("origin", FieldAttribute.Value, "SFO"); parameters.AddField("destination", FieldAttribute.Label, "London Heathrow"); parameters.AddField("destination", FieldAttribute.Value, "LHR"); parameters.AddField("seat", FieldAttribute.Value, "7A"); parameters.AddField("boarding-gate", FieldAttribute.Value, "F12"); parameters.AddField("passenger-name", FieldAttribute.Value, "John Appleseed"); request.AddBarCode("M1APPLESEED/JMR EZQ7O92 GVALHRBA 00723319C002F00009100", BarcodeType.PKBarcodeFormatPDF417, "iso-8859-1"); request.LoadTemplate("BoardingPass", parameters); return request; }
public override Passbook.Generator.PassGeneratorRequest GetPass(string serialNumber) { PassGeneratorRequest request = new PassGeneratorRequest(); request.PassTypeIdentifier = PassTypeIdentifier; request.SerialNumber = Guid.NewGuid().ToString("D"); TemplateModel parameters = new TemplateModel(); request.AddBarCode("01927847623423234234", BarcodeType.PKBarcodeFormatPDF417, "UTF-8", "01927847623423234234"); request.LoadTemplate("Coupon", parameters); return request; }
public override Passbook.Generator.PassGeneratorRequest GetPass(string serialNumber) { PassGeneratorRequest request = new PassGeneratorRequest(); request.PassTypeIdentifier = PassTypeIdentifier; request.SerialNumber = Guid.NewGuid().ToString("D"); TemplateModel parameters = new TemplateModel(); parameters.AddField("event", FieldAttribute.Value, "Jeff Wayne's War of the Worlds"); DateTime eventDate = DateTime.Now.AddDays(1); parameters.AddField("doors-open", FieldAttribute.Value, new DateTime(eventDate.Year, eventDate.Month, eventDate.Day, 20, 30, 00)); parameters.AddField("seating-section", FieldAttribute.Value, 10); request.AddBarCode("01927847623423234234", BarcodeType.PKBarcodeFormatPDF417, "iso-8859-1", "01927847623423234234"); request.LoadTemplate("Event", parameters); return request; }
/// <summary> /// Renders the contentData using the wrapped renderer and catches common, non-critical exceptions. /// </summary> public void Render(HtmlHelper helper, PartialRequest partialRequestHandler, IContentData contentData, TemplateModel templateModel) { try { _mvcRenderer.Render(helper, partialRequestHandler, contentData, templateModel); } catch (NullReferenceException ex) { if (HttpContext.Current.IsDebuggingEnabled) { //If debug="true" we assume a developer is making the request throw; } HandlerError(helper, contentData, ex); } catch (ArgumentException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (ApplicationException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (InvalidOperationException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (NotImplementedException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (IOException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (EPiServerException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } catch (XFormException ex) { if (HttpContext.Current.IsDebuggingEnabled) { throw; } HandlerError(helper, contentData, ex); } }
protected TemplateFacade(TemplateModel model) : base(model) { }
public async ValueTask <IResponseBuilder> RenderAsync(TemplateModel model) { return(model.Request.Respond() .Content(await Template.RenderAsync(model)) .Type(CONTENT_TYPE)); }
public IActionResult ChangeTemplate(TemplateModel model) { InitializeModel(model); return(View("Template", model)); }
public IActionResult Update([FromBody] TemplateModel model) { _templateService.Update(model); return(NoContent()); }
public eFleetVehicleIncidentModel SaveEfleetVehicleIncident(eFleetVehicleIncidentModel objeFleetVehicleIncidentModel) { try { LocationMaster objLocationMaster = new LocationMaster(); var objeFleetVehicleIncident = new eFleetVehicleIncident(); var objeFleetVehicleIncidentRepository = new eFleetVehicleIncidentRepository(); var objeTracLoginModel = new eTracLoginModel(); if (objeFleetVehicleIncidentModel.IncidentID == 0) { AutoMapper.Mapper.CreateMap <eFleetVehicleIncidentModel, eFleetVehicleIncident>(); var objfleetVehicleIncidentMapper = AutoMapper.Mapper.Map(objeFleetVehicleIncidentModel, objeFleetVehicleIncident); objeFleetVehicleIncidentRepository.Add(objfleetVehicleIncidentMapper); // objeFleetVehicle.QRCodeID = objeFleetVehicleModel.QRCodeID + "EFV" + (objeFleetVehicle.VehicleID + 100).ToString(); objeFleetVehicleIncidentRepository.SaveChanges(); objeFleetVehicleIncidentModel.Result = Result.Completed; if (objeFleetVehicleIncidentModel.Result == Result.Completed) { #region Save DAR DARModel objDAR = new DARModel(); objDAR.ActivityDetails = DarMessage.RegisterNeweFleetIncidentVehicle(objeFleetVehicleIncidentModel.LocationName); objDAR.LocationId = objeFleetVehicleIncidentModel.LocationID; objDAR.UserId = objeFleetVehicleIncidentModel.UserID; objDAR.CreatedBy = objeFleetVehicleIncidentModel.UserID; objDAR.CreatedOn = DateTime.UtcNow; objDAR.TaskType = (long)TaskTypeCategory.eFleetVehicleIncidentSubmission; Result result = _ICommonMethod.SaveDAR(objDAR); #endregion Save DAR //Created By Ashwajit Bansod for Sending the Mail of Vehicle Incident to the Manager #region Email var objEmailLogRepository = new EmailLogRepository(); var objEmailReturn = new List <EmailToManagerModel>(); var objListEmailog = new List <EmailLog>(); var objTemplateModel = new TemplateModel(); if (result == Result.Completed) { objEmailReturn = objEmailLogRepository.SendEmailToManagerForeFleetInspection(objeFleetVehicleIncidentModel.LocationID, objeFleetVehicleIncidentModel.UserID).Result; } if (objEmailReturn.Count > 0 && result == Result.Completed) { foreach (var item in objEmailReturn) { bool IsSent = false; var objEmailHelper = new EmailHelper(); objEmailHelper.emailid = item.ManagerEmail; objEmailHelper.ManagerName = item.ManagerName; objEmailHelper.VehicleNumber = objeFleetVehicleIncidentModel.VehicleNumber; objEmailHelper.LocationName = objeFleetVehicleIncidentModel.LocationName; objEmailHelper.UserName = item.UserName; objEmailHelper.QrCodeId = objeFleetVehicleIncidentModel.QRCodeID; objEmailHelper.AccidentDate = objeFleetVehicleIncidentModel.AccidentDate.ToString(); objEmailHelper.City = objeFleetVehicleIncidentModel.City; objEmailHelper.NumberOfInjuries = objeFleetVehicleIncidentModel.NumberOfInjuries; objEmailHelper.DriverNameForVehicleIncident = objeFleetVehicleIncidentModel.DriverName; objEmailHelper.IncidentDescription = objeFleetVehicleIncidentModel.Description; if (objeFleetVehicleIncidentModel.Preventability == true) { objEmailHelper.Prevenatability = "Yes"; } else { objEmailHelper.Prevenatability = "No"; } //objEmailHelper.InfractionStatus = obj.Status; objEmailHelper.MailType = "VehicleIncident"; objEmailHelper.SentBy = item.RequestBy; objEmailHelper.LocationID = item.LocationID; objEmailHelper.TimeAttempted = DateTime.UtcNow.ToMobileClientTimeZone(objTemplateModel.TimeZoneName, objTemplateModel.TimeZoneOffset, objTemplateModel.IsTimeZoneinDaylight, false).ToString(); IsSent = objEmailHelper.SendEmailWithTemplate(); //Push Notification string message = PushNotificationMessages.eFleetIncidentForServiceReported(objeFleetVehicleIncidentModel.LocationName, objeFleetVehicleIncidentModel.QRCodeID, objeFleetVehicleIncidentModel.VehicleNumber); PushNotification.GCMAndroid(message, item.DeviceId, objEmailHelper); if (IsSent == true) { var objEmailog = new EmailLog(); try { objEmailog.CreatedBy = item.RequestBy; objEmailog.CreatedDate = DateTime.UtcNow; objEmailog.DeletedBy = null; objEmailog.DeletedOn = null; objEmailog.LocationId = item.LocationID; objEmailog.ModifiedBy = null; objEmailog.ModifiedOn = null; objEmailog.SentBy = item.RequestBy; objEmailog.SentEmail = item.ManagerEmail; objEmailog.Subject = objEmailHelper.Subject; objEmailog.SentTo = item.ManagerUserId; objListEmailog.Add(objEmailog); } catch (Exception) { throw; } } } using (var context = new workorderEMSEntities()) { context.EmailLogs.AddRange(objListEmailog); context.SaveChanges();; } // //var x = EmailLogRepository.InsertEntitiesNew("EmailLog", objListEmailog); // //Task<bool> x = null; // //foreach (var i in objListEmailog) // //{ // // x = objEmailLogRepository.SaveEmailLogAsync(i); // //} //} #endregion Email } } } else { var vehicleIncidentData = objeFleetVehicleIncidentRepository.GetAll(v => v.IsDeleted == false && v.LocationID == objeFleetVehicleIncidentModel.LocationID && v.IncidentID == objeFleetVehicleIncidentModel.IncidentID).SingleOrDefault(); objeFleetVehicleIncidentModel.IncidentImage = vehicleIncidentData.IncidentImage; AutoMapper.Mapper.CreateMap <eFleetVehicleIncidentModel, eFleetVehicleIncident>(); // objeFleetVehicleIncident.FuelType = Convert.ToInt32(objeFleetVehicleIncidentModel.FuelType); var objfleetVehicleMapper = AutoMapper.Mapper.Map(objeFleetVehicleIncidentModel, vehicleIncidentData); objeFleetVehicleIncidentRepository.SaveChanges(); objeFleetVehicleIncidentModel.Result = Result.UpdatedSuccessfully; if (objeFleetVehicleIncidentModel.Result == Result.UpdatedSuccessfully) { #region Save DAR DARModel objDAR = new DARModel(); objDAR.ActivityDetails = DarMessage.UpdateeFleetVehicleIncident(objeFleetVehicleIncidentModel.LocationName); objDAR.LocationId = objeFleetVehicleIncidentModel.LocationID; objDAR.UserId = objeFleetVehicleIncidentModel.UserID; objDAR.ModifiedBy = objeFleetVehicleIncidentModel.UserID; objDAR.ModifiedOn = DateTime.UtcNow; objDAR.TaskType = (long)TaskTypeCategory.UpdateeFleetIncidentVehicle; Result result = _ICommonMethod.SaveDAR(objDAR); #endregion Save DAR } } return(objeFleetVehicleIncidentModel); } catch (Exception ex) { Exception_B.Exception_B.exceptionHandel_Runtime(ex, "public eFleetVehicleIncidentModel SaveEfleetVehicleIncident(eFleetVehicleIncidentModel objeFleetVehicleIncidentModel)", "Exception While saving vehicle Incident request.", objeFleetVehicleIncidentModel); throw; } }
static void SetPropertiesTo(object obj, TemplateModel template_model) { var properties = obj.get_public_writable_instance_properties( ); foreach (var property_info in properties) { var property_name = property_info.Name; var property_type = property_info.PropertyType; if (property_type.Inherits <Enumeration>( )) { var get_enumeration_method = typeof(TemplateModelExtentions).GetPublicStaticMethods("GetEnumeration").First( ); var enumeration = get_enumeration_method.Invoke(null, new object [] { template_model, property_type, property_name }); property_info.SetValue(obj, enumeration, null); continue; } if (property_type.Inherits <IList <> >( )) { var datas = template_model.template.data.Where(x => x.name.Contains(property_name) || x.name.pluralize().Contains(property_name)); var conversion_type = property_type.GetGenericArguments( ).First( ); var template_data = datas.Where(x => !string.IsNullOrEmpty(x.value)); IEnumerable <object> values = null; // TODO: refactor with specification pattern if (conversion_type == typeof(CustomFieldView)) { values = template_data.Select(x => new CustomFieldView { Id = Convert.ToInt64(x.name.Split('[')[1].Replace("]", "")), Value = x.value }); } else { values = template_data.Select(x => Convert.ChangeType(x.value, conversion_type)); } var list = ( IList )Activator.CreateInstance(typeof(List <>).MakeGenericType(conversion_type)); values.ForEach(x => list.Add(x)); property_info.SetValue(obj, list, null); continue; } if (IsNotAComponent(property_type)) { var get_template_value_method = typeof(TemplateModelExtentions).GetPublicStaticMethods("GetValue").WithGenericParameters(1); var get_template_value_method_of_property_type = get_template_value_method.MakeGenericMethod(property_type); var template_value = get_template_value_method_of_property_type.Invoke(null, new object [] { template_model, property_name }); property_info.SetValue(obj, template_value, null); continue; } var component_data = MapComponentDataFromTemplateModel(template_model, property_name); var component = Activator.CreateInstance(property_type); SetPropertiesTo(component, component_data); property_info.SetValue(obj, component, null); } }
static Lst <(FileName, Try <GeneratedCode>)> GenerateForSingleFile(TemplateModel model) =>
public void AfterFileProcessing(TemplateModel template) { }
private List <Tuple <string, string> > GetReplacementTokens(TemplateModel templateData) { var replacementTokens = new List <Tuple <string, string> >(); if (templateData?.Tokens != null && templateData.Tokens.Count > 0) { foreach (var token in templateData.Tokens) { switch (token.InputType) { case InputType.Options: { Console.WriteLine(string.Empty); for (int i = 0; i < token.Values.Count; i++) { Console.WriteLine($"{i} - {token.Values[i]}"); } Console.WriteLine(string.Empty); bool correctOption = false; int chosenOption; do { Console.Write($"Choose replacement value for token '{token.Token}':"); var key = Console.ReadLine().Trim(); if (int.TryParse(key, out chosenOption)) { if (chosenOption >= 0 && chosenOption < token.Values.Count) { correctOption = true; } } }while (correctOption); replacementTokens.Add(new Tuple <string, string>(token.Token, token.Values[chosenOption])); break; } default: { var initialText = !string.IsNullOrEmpty(token.Description) ? token.Description : $"Enter replacement value for token {token.Token}"; bool directoryAndFilesSuggestions = token.InputType == InputType.Files; string allowedFileExtensionGlobPattern = null; if (token.Files?.AllowedFileExtension != null) { allowedFileExtensionGlobPattern = token.Files.AllowedFileExtension.StartsWith("*.") ? token.Files.AllowedFileExtension : $"*.{token.Files.AllowedFileExtension}"; } var hints = new List <Hint>(); if (token.InputType == InputType.Hints) { hints.AddRange(token.Values.Select(value => new Hint() { Name = value, HintColor = ConsoleColor.DarkGray })); } var console = new FlubuConsole(hints, options: o => { o.WritePrompt = false; o.InitialText = initialText; o.InitialHelp = token.Help; o.OnlyDirectoriesSuggestions = directoryAndFilesSuggestions; o.IncludeFileSuggestions = directoryAndFilesSuggestions; o.FileSuggestionsSearchPattern = allowedFileExtensionGlobPattern; o.DefaultSuggestion = token.DefaultValue; }); bool isRightFileExtension = true; string newValue; do { newValue = console.ReadLine().Trim(); if (!string.IsNullOrEmpty(allowedFileExtensionGlobPattern)) { isRightFileExtension = CheckFileExtension(newValue, allowedFileExtensionGlobPattern); } }while (!isRightFileExtension); if (!string.IsNullOrEmpty(newValue)) { replacementTokens.Add(new Tuple <string, string>(token.Token, newValue)); } break; } } } } return(replacementTokens); }
public void BeforeFileProcessing(TemplateModel template, List <string> files) { _replacementTokens = GetReplacementTokens(template); }
public ActionResult Get(TemplateModel model) { return(Json(new { date = DateTime.UtcNow, model })); }
/// <summary> /// Renders from the cache or adds the result to the cache. /// </summary> /// <param name="helper">The helper.</param> /// <param name="partialRequest">The partial request.</param> /// <param name="content">The content.</param> /// <param name="templateModel">The template model.</param> /// <param name="settings">The settings.</param> protected virtual void RenderFromOrAddToCache(HtmlHelper helper, PartialRequest partialRequest, IContent content, TemplateModel templateModel, ICacheableSettings settings) { string cacheKey = KeyCreator.GenerateCacheKey(settings, helper, content); if (Cache.TryGet(cacheKey, ReadStrategy.Immediate, out string cachedHtml)) { helper.ViewContext.Writer.Write(cachedHtml); } else { RenderAndAddToCache(helper, partialRequest, content, templateModel, settings, cacheKey); } }
/// <summary> /// Tries to render the HTML from cache, falls back to the default renderer if the content is not cacheable. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="partialRequest">The partial request.</param> /// <param name="contentData">The content data.</param> /// <param name="templateModel">The template model.</param> public void RenderFromCache(HtmlHelper htmlHelper, PartialRequest partialRequest, IContentData contentData, TemplateModel templateModel) { if (SettingsService.TryGetSettingsFromContentData(contentData, out ICacheableSettings settings) && IsCacheEnabled() && contentData is IContent content) { RenderFromOrAddToCache(htmlHelper, partialRequest, content, templateModel, settings); } else { DefaultRenderer.Render(htmlHelper, partialRequest, contentData, templateModel); } bool IsCacheEnabled() { if (PageEditing.PageIsInEditMode) { return(settings.IsCacheEnabled && settings.CacheInCmsEditor); } return(settings.IsCacheEnabled); } }
protected void Delete() { long folderId = Convert.ToInt64(Request.QueryString["folderId"]); try { //if this is a master layout, check if it's used anywhere. if not then go ahead and delete, but otherwise, don't. if (m_EkContent.GetContentSubType(this.ContentId, this.LanguageId) == EkEnumeration.CMSContentSubtype.PageBuilderMasterData) { TemplateModel tm = new TemplateModel(); TemplateData template = tm.FindByMasterLayoutID(this.ContentId); if(template != null){ long[] folders = m_EkContent.GetTemplateDefaultFolderUsage(template.Id); Microsoft.VisualBasic.Collection contentblocks = m_EkContent.GetTemplateContentBlockUsage(template.Id); if (folders.Length == 0 && contentblocks.Count == 0) { m_EkContent.SubmitForDeletev2_0(this.ContentId, folderId); } else { StringBuilder sb = new StringBuilder(); sb.Append("Cannot delete this master layout.\r\n"); if (folders.Length > 0) { sb.Append("The following folders are associated with it:\r\n"); for (int i = 0; i < folders.Length; i++) { sb.Append(m_EkContent.GetFolderPath(folders[i]).Replace('\\', '/') + '/'); if (i != folders.Length - 1) sb.Append(","); sb.Append("\r\n"); } } if (contentblocks.Count > 0) { sb.Append("The following content is associated with it:\r\n"); for (int i = 1; i <= contentblocks.Count; i++) { Microsoft.VisualBasic.Collection inner = (Microsoft.VisualBasic.Collection)contentblocks[i]; ContentData cd = m_EkContent.GetContentById((long)inner["content_id"], EkContent.ContentResultType.Published); sb.Append("/" + cd.Path + cd.Title + " (id: " + cd.Id + ", lang: " + cd.LanguageId + ")"); if (i != contentblocks.Count) sb.Append(",\r\n"); } } DmsMenuActionsRepsonse.Text = "message:" + sb.ToString(); } } } else { m_EkContent.SubmitForDeletev2_0(this.ContentId, folderId); } } catch (Exception ex) { if (ex.Message.ToLower().Contains("delete master layout")) { DmsMenuActionsRepsonse.Text = "message:" + ex.Message; } else { throw ex; } } }
public void AfterFileProcessing(TemplateModel template) { ExecuteTasks(task => task.AfterFileProcessing(template)); }
private void btnScanAll_Click(object sender, EventArgs e) { using (WaitDialogForm fWait = new WaitDialogForm("Vui lòng chờ trong giây lát...", "Đang đổi tên file trong thư mục Scan")) { for (int i = 0; i < grvScan.RowCount; i++) { try { string filePath = grvScan.GetRowCellValue(i, colFilePath).ToString(); string thisProductCode = ""; if (Path.GetExtension(filePath) == ".jpg") { Image img = Image.FromFile(filePath); Bitmap mBitmap = new Bitmap(img); ArrayList barcodes = new ArrayList(); BarcodeImaging.FullScanPage(ref barcodes, mBitmap, 100); //string[] barcodes = BarcodeReader.read(mBitmap, BarcodeReader.CODE39); mBitmap.Dispose(); string contentBarcode = barcodes.ToArray().Where(o => o.ToString().StartsWith("+")).ToArray()[0].ToString();//nội dung barcode chứa tên biểu mẫu (VD: 2.BM01.A0101) thisProductCode = "TPAD." + contentBarcode.Substring(3); if (!thisProductCode.ToUpper().Contains(_productCode)) { continue; } string destFileName = @"D:\Thietke.Ck\TPAD." + _productCode.Substring(5, 1) + "\\" + _productCode + ".Ck\\BCCk." + _productCode + "\\BC-CAD." + _productCode + "\\" + thisProductCode + ".jpg"; if (File.Exists(destFileName)) { DialogResult result = MessageBox.Show("Đã tồn tại file: '" + thisProductCode + ".jpg' trong thiết kế" + Environment.NewLine + "Bạn có muốn ghi đè lên file cũ không?", TextUtils.Caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { File.Delete(destFileName); File.Copy(filePath, destFileName, true); img.Dispose(); mBitmap.Dispose(); File.Delete(filePath); } else { TextUtils.RenameFileVB(filePath, thisProductCode + ".jpg"); } } else { File.Copy(filePath, destFileName, true); img.Dispose(); mBitmap.Dispose(); File.Delete(filePath); } } else if (Path.GetExtension(filePath).ToLower() == ".pdf") { System.Collections.ArrayList barcodes = new System.Collections.ArrayList(); string outputFilePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + ".png"; pdfConverter().Convert(filePath, outputFilePath); Bitmap mBitmap = new Bitmap(outputFilePath); BarcodeImaging.FullScanPage(ref barcodes, mBitmap, 100); //string[] barcodes = BarcodeReader.read(mBitmap, BarcodeReader.CODE39); mBitmap.Dispose(); File.Delete(outputFilePath); string contentBarcode = barcodes.ToArray().Where(o => o.ToString().StartsWith("2.")).ToArray()[0].ToString();//nội dung barcode chứa tên biểu mẫu (VD: 2.BM01.A0101) string templateCode = contentBarcode.Split('.')[1]; TemplateModel temModel = (TemplateModel)TemplateBO.Instance.FindByAttribute("Code", templateCode)[0]; int tempType = temModel.Type; string code = contentBarcode.Split('.')[2]; if (tempType == 1 || tempType == 2) //1:cơ khí,2:điện,3:điện tử { thisProductCode = "TPAD." + code; } else { thisProductCode = "PCB." + code; } if (_productCode != thisProductCode) { continue; } string tempName = temModel.Name.Replace("code", thisProductCode); string tempFolderPath = temModel.PathFolderC.Replace("code", thisProductCode); if (tempType == 1) { string destFileName = @"D:\Thietke.Ck\TPAD." + code.Substring(0, 1) + "\\" + tempFolderPath + "\\" + tempName + Path.GetExtension(filePath); checkBeforeCopyFile(filePath, destFileName); } if (tempType == 2) { } if (tempType == 3) { string destFileName = @"D:\Thietke.Dt\PCB." + code.Substring(0, 1) + "\\" + tempFolderPath + "\\" + tempName + ".pdf"; checkBeforeCopyFile(filePath, destFileName); } } } catch (Exception) { continue; } } btnRefresh_Click(null, null); } }
public async Task <IActionResult> Create([FromBody] TemplateModel model) { await _templateService.Create(model); return(NoContent()); }
internal async Task DownloadAndPrepareProject(string templateUri) { using (var client = new HttpClient()) { try { FlubuSession.LogInfo($"Creating Flubu template '{Args.MainCommands[1]}'."); await client.DownloadFileAsync(templateUri, TmpZipPath); var rootDir = Path.GetFullPath("."); var files = FlubuSession.Tasks() .UnzipTask(TmpZipPath, rootDir) .WithLogLevel(LogLevel.None) .DoNotLogTaskExecutionInfo() .Execute(FlubuSession); if (!files.Any(x => x.EndsWith(".cs"))) { FlubuSession.LogInfo("Flubu template not found on specified url."); return; } string templateJsonPath = files.FirstOrDefault(x => x.EndsWith(TemplateJsonFileName, StringComparison.OrdinalIgnoreCase)); string templateCsFilePath = files.FirstOrDefault(x => x.EndsWith(TemplateCsFileName, StringComparison.OrdinalIgnoreCase)); TemplateModel templateData = null; if (templateJsonPath != null) { templateData = GetTemplateDataFromJsonFile(templateJsonPath); } else if (templateCsFilePath != null) { var flubuTemplate = await GetTemplateFromCsharpFile(templateCsFilePath); switch (flubuTemplate) { case null: FlubuSession.LogInfo("Template.cs must implement IFlubuTemplate interface."); return; //// ReSharper disable once SuspiciousTypeConversion.Global case IFlubuTemplateTask flubuTask: FlubuTemplateTasksExecutor.AddTaskToExecute(flubuTask); break; } var templateBuilder = new FlubuTemplateBuilder(); flubuTemplate.ConfigureTemplate(templateBuilder); templateData = templateBuilder.Build(); } FlubuTemplateTasksExecutor.SetTasksToExecute(_templateTasksToExecute); FlubuTemplateTasksExecutor.BeforeFileProcessing(templateData, files); foreach (var sourceFilePath in files) { string relativePath = sourceFilePath.Replace(rootDir, string.Empty).TrimStart(Path.DirectorySeparatorChar); relativePath = relativePath .Substring(relativePath.IndexOf(Path.DirectorySeparatorChar)) .TrimStart(Path.DirectorySeparatorChar); if (templateData != null && templateData.SkipFiles.Contains(relativePath)) { continue; } var destinationFilePath = Path.Combine(rootDir, relativePath); var destinationDir = Path.GetDirectoryName(destinationFilePath); if (!string.IsNullOrEmpty(destinationDir)) { Directory.CreateDirectory(destinationDir); } FlubuTemplateTasksExecutor.BeforeFileCopy(sourceFilePath); File.Copy(sourceFilePath, destinationFilePath, true); FlubuTemplateTasksExecutor.AfterFileCopy(destinationFilePath); } FlubuTemplateTasksExecutor.AfterFileProcessing(templateData); var tmp = files[0].Substring(rootDir.Length).TrimStart(Path.DirectorySeparatorChar); var gitDirName = tmp.Substring(0, tmp.IndexOf(Path.DirectorySeparatorChar)); Directory.Delete(gitDirName, true); FlubuSession.LogInfo($"The template '{Args.MainCommands[1]}' was created successfully."); } catch (InvalidDataException) { FlubuSession.LogInfo("Flubu template not found on specified url."); } catch (HttpRequestException) { FlubuSession.LogInfo("Flubu template not found on specified url."); } finally { File.Delete(TmpZipPath); } } }
private void Process_DoFolderUpdate() { bool bInheritanceIsDif; bInheritanceIsDif = false; int isub = 0; string init_xmlconfig = Request.Form["init_xmlconfig"]; string init_frm_xmlinheritance = Request.Form["init_frm_xmlinheritance"]; Ektron.Cms.Content.EkXmlIndexing XmlInd; FolderData folder_data = null; Ektron.Cms.Content.EkContent m_refContent; SubscriptionPropertiesData sub_prop_data = new SubscriptionPropertiesData(); Collection page_subscription_data = new Collection(); Collection page_sub_temp = new Collection(); Array arrSubscriptions; int i = 0; BlogRollItem[] abriRoll; string sCatTemp = ""; List<string> siteAliasList = new List<string>(); string[] arSiteAliasList; Ektron.Cms.SiteAliasApi _refSiteAliasApi; bool subscriptionRestore = false; m_refContent = _ContentApi.EkContentRef; if (_FolderId == -1) { _FolderId = _Id; //i.e Request.Form(folder_id.UniqueID) } _FolderData = _ContentApi.GetFolderById(_Id, true, true); _FolderType = _FolderData.FolderType; if (Convert.ToString(_FolderId) != "") { if (_FolderType != (int)Ektron.Cms.Common.EkEnumeration.FolderType.Catalog) { if (!string.IsNullOrEmpty(Request.Form["web_alert_inherit_checkbox"])) { sub_prop_data.BreakInheritance = false; subscriptionRestore = true; } else { sub_prop_data.BreakInheritance = true; if (!string.IsNullOrEmpty(Request.Form["web_alert_restore_inherit_checkbox"])) { subscriptionRestore = true; } } if (Request.Form["notify_option"] == ("Always")) { sub_prop_data.NotificationType = Ektron.Cms.Common.EkEnumeration.SubscriptionPropertyNotificationTypes.Always; } else if (Request.Form["notify_option"] == ("Initial")) { sub_prop_data.NotificationType = Ektron.Cms.Common.EkEnumeration.SubscriptionPropertyNotificationTypes.Initial; } else if (Request.Form["notify_option"] == ("Never")) { sub_prop_data.NotificationType = Ektron.Cms.Common.EkEnumeration.SubscriptionPropertyNotificationTypes.Never; } sub_prop_data.SuspendNextNotification = false; sub_prop_data.SendNextNotification = false; sub_prop_data.OptOutID = Convert.ToInt64(Request.Form["notify_optoutid"]); if (!string.IsNullOrEmpty((Request.Form["use_message_button"]))) { sub_prop_data.DefaultMessageID = Convert.ToInt64(Request.Form["notify_messageid"]); } else { sub_prop_data.DefaultMessageID = 0; } if (!string.IsNullOrEmpty(Request.Form["use_summary_button"])) { sub_prop_data.SummaryID = 1; } else { sub_prop_data.SummaryID = 0; } if (!string.IsNullOrEmpty(Request.Form["use_content_button"])) { sub_prop_data.ContentID = Convert.ToInt64(Request.Form["frm_content_id"]); } else { sub_prop_data.ContentID = 0; } sub_prop_data.UnsubscribeID = Convert.ToInt64(Request.Form["notify_unsubscribeid"]); if (!string.IsNullOrEmpty(Request.Form["notify_url"])) { sub_prop_data.URL = Request.Form["notify_url"]; } else { sub_prop_data.URL = Request.ServerVariables["HTTP_HOST"]; } if (!string.IsNullOrEmpty(Request.Form["notify_weblocation"])) { sub_prop_data.FileLocation = Server.MapPath(_ContentApi.AppPath + "subscriptions"); } else { sub_prop_data.FileLocation = Server.MapPath(_ContentApi.AppPath + "subscriptions"); } if (!string.IsNullOrEmpty(Request.Form["notify_weblocation"])) { sub_prop_data.WebLocation = Request.Form["notify_weblocation"]; } else { sub_prop_data.WebLocation = "subscriptions"; } if (!string.IsNullOrEmpty(Request.Form["notify_subject"])) { sub_prop_data.Subject = Request.Form["notify_subject"]; } else { sub_prop_data.Subject = ""; } if (!string.IsNullOrEmpty(Request.Form["notify_emailfrom"])) { sub_prop_data.EmailFrom = Request.Form["notify_emailfrom"]; } else { sub_prop_data.EmailFrom = ""; } sub_prop_data.UseContentTitle = ""; if (!string.IsNullOrEmpty(Request.Form["use_contentlink_button"])) { sub_prop_data.UseContentLink = 1; } else { sub_prop_data.UseContentLink = 0; } if (!string.IsNullOrEmpty(Request.Form["content_sub_assignments"])) { arrSubscriptions = Strings.Split(Strings.Trim(Request.Form["content_sub_assignments"]), " ", -1, 0); if (arrSubscriptions.Length > 0) { for (isub = 0; isub <= (arrSubscriptions.Length - 1); isub++) { if (arrSubscriptions.GetValue(isub).ToString() != ",") // ignore empty value when web alerts are inherited { page_sub_temp = new Collection(); page_sub_temp.Add(long.Parse(Strings.Mid(arrSubscriptions.GetValue(isub).ToString(), 10)), "ID", null, null); page_subscription_data.Add(page_sub_temp, null, null, null); } } } } else { page_subscription_data = null; } page_sub_temp = null; } _PageData = new Collection(); _PageData.Add(Request.Form["foldername"].Trim(".".ToCharArray()), "FolderName", null, null); if (!string.IsNullOrEmpty(Request.Form["isblog"])) { _PageData.Add(Request.Form[tagline.UniqueID], "FolderDescription", null, null); } else { _PageData.Add(Request.Form[folderdescription.UniqueID], "FolderDescription", null, null); } _PageData.Add(Request.Form[folder_id.UniqueID], "FolderID", null, null); if (string.IsNullOrEmpty(Request.Form["TemplateTypeBreak"])) { _PageData.Add(Request.Form["templatefilename"], "TemplateFileName", null, null); //Defect # 54021 - Add failed. Duplicate key value supplied. //string templateName = (string)(Request.Form["templatefilename"].Split("(".ToCharArray())[0].TrimEnd()); //TemplateData[] template_data; //template_data = _ContentApi.GetAllTemplates("TemplateFileName"); //int j = 0; //for (j = 0; j <= template_data.Length - 1; j++) //{ // if (!(Request.Form["tinput_" + template_data[j].Id] == null) && template_data[j].FileName == templateName) // { // _PageData.Add(template_data[i].SubType, "TemplateSubType", null, null); // } //} // Defect # 56113 // Also added new hidden field to ascx + changes to TemplateConfigSave() in content.aspx if (!String.IsNullOrEmpty(Request.Form["defaultTemplateID"])) { TemplateModel templateModel = new TemplateModel(); TemplateData template_data = templateModel.FindByID(long.Parse(Request.Form["defaultTemplateID"].ToString())); _PageData.Add(template_data.SubType, "TemplateSubType", null, null); } } else { _PageData.Add("", "TemplateFileName", null, null); } //_PageData.Add(Request.Form("templatefilename"), "TemplateFileName") _PageData.Add(Request.Form["stylesheet"], "StyleSheet", null, null); if (_FolderType != (int)Ektron.Cms.Common.EkEnumeration.FolderType.Calendar) { if (Strings.LCase(Request.Form["TypeBreak"]) == "on") { if (init_frm_xmlinheritance == "0") { bInheritanceIsDif = true; } _PageData.Add(true, "XmlInherited", null, null); } else { if (init_frm_xmlinheritance == "1") { bInheritanceIsDif = true; } _PageData.Add(false, "XmlInherited", null, null); } _PageData.Add(Request.Form["xmlconfig"], "XmlConfiguration", null, null); } else { bInheritanceIsDif = false; _PageData.Add(false, "XmlInherited", null, null); _PageData.Add(Ektron.Cms.Content.Calendar.WebCalendar.WebEventSmartformId.ToString(), "XmlConfiguration", null, null); } // handle multitemplates if there are any i = 1; Collection altinfo = new Collection(); //While (Request.Form("namealt" + CStr(i)) <> "") // Dim namealt As String = Request.Form("namealt" + CStr(i)) // Dim xmlconfigalt As String = Request.Form("xmlconfigalt" + CStr(i)) // If (xmlconfigalt = "ignore") Then xmlconfigalt = -1 // Dim templatealt As String = Request.Form("templatealt" + CStr(i)) // If (templatealt = "ignore") Then templatealt = -1 // If ((xmlconfigalt > -1) Or (templatealt > -1)) Then // ' add this multitemplate only if a template or config is selected // Dim multitemplate As New Collection // multitemplate.Add(m_intFolderId, "FolderID") // multitemplate.Add(xmlconfigalt, "CollectionID") // multitemplate.Add(templatealt, "TemplateFileID") // multitemplate.Add("", "CSSFile") // multitemplate.Add(namealt, "Name") // altinfo.Add(multitemplate) // End If // i = i + 1 //End While //m_refContentApi.UpdateFolderContentTemplates(m_intFolderId, altinfo) bool isPublishedAsPdf = System.Convert.ToBoolean((Request.Form["publishAsPdf"] == "on") ? true : false); _PageData.Add(isPublishedAsPdf, "PublishPdfActive", null, null); // handle dynamic replication properties if (folder_data == null) { folder_data = _ContentApi.GetFolderById(_FolderId, true, true); } if (!string.IsNullOrEmpty(Request.Form["EnableReplication"]) || folder_data.IsCommunityFolder) { _PageData.Add(1, "EnableReplication", null, null); } else { _PageData.Add(0, "EnableReplication", null, null); } // add domain properties if they're there if ((!string.IsNullOrEmpty(Request.Form["IsDomainFolder"])) && (!string.IsNullOrEmpty(Request.Form["DomainProduction"]))) { _PageData.Add(true, "IsDomainFolder", null, null); string staging = Request.Form["DomainStaging"]; string production = Request.Form["DomainProduction"]; if (staging == null) { staging = ""; } if (production == null) { production = ""; } if (staging.EndsWith("/")) { staging = staging.Substring(0, staging.Length - 1); } if (production.EndsWith("/")) { production = production.Substring(0, production.Length - 1); } if (staging == "") { staging = production; } _PageData.Add(staging, "DomainStaging", null, null); _PageData.Add(production, "DomainProduction", null, null); } else { _PageData.Add(false, "IsDomainFolder", null, null); } if (!string.IsNullOrEmpty(Request.Form["isblog"])) //isblog { _PageData.Add(true, "isblog", null, null); _PageData.Add(Request.Form["blog_visibility"], "blog_visibility", null, null); _PageData.Add(Request.Form["blogtitle"], "blogtitle", null, null); if (!string.IsNullOrEmpty(Request.Form["postsvisible"])) { _PageData.Add(Request.Form["postsvisible"], "postsvisible", null, null); } else { _PageData.Add(-1, "postsvisible", null, null); } if (!string.IsNullOrEmpty(Request.Form["enable_comments"])) { _PageData.Add(true, "enablecomments", null, null); } else { _PageData.Add(false, "enablecomments", null, null); } if (!string.IsNullOrEmpty(Request.Form["moderate_comments"])) { _PageData.Add(true, "moderatecomments", null, null); } else { _PageData.Add(false, "moderatecomments", null, null); } if (!string.IsNullOrEmpty(Request.Form["require_authentication"])) { _PageData.Add(true, "requireauthentication", null, null); } else { _PageData.Add(false, "requireauthentication", null, null); } _PageData.Add(Request.Form["notify_url"], "notifyurl", null, null); if (!string.IsNullOrEmpty(Request.Form["categorylength"])) { for (i = 0; i <= (Convert.ToInt64(Request.Form["categorylength"]) - 1); i++) { if (Request.Form["category" + i.ToString()] != "") { if (i == (Convert.ToInt64(Request.Form["categorylength"]) - 1)) { sCatTemp += Strings.Replace(Request.Form["category" + i.ToString()], ";", "~@~@~", 1, -1, 0); } else { sCatTemp += (string)(Strings.Replace(Request.Form["category" + i.ToString()], ";", "~@~@~", 1, -1, 0) + ";"); } } } } _PageData.Add(sCatTemp, "blogcategories", null, null); if (!string.IsNullOrEmpty(Request.Form["rolllength"])) { abriRoll = new BlogRollItem[1]; for (i = 0; i <= (Convert.ToInt64(Request.Form["rolllength"]) - 1); i++) { Array.Resize(ref abriRoll, i + 1); if (!string.IsNullOrEmpty(Request.Form["editfolder_linkname" + i.ToString()]) && !string.IsNullOrEmpty(Request.Form["editfolder_url" + i.ToString()])) { //add only if we have something with a name/url abriRoll[i] = new BlogRollItem(); abriRoll[i].LinkName = Request.Form["editfolder_linkname" + i.ToString()]; abriRoll[i].URL = Request.Form["editfolder_url" + i.ToString()]; if (!string.IsNullOrEmpty(Request.Form["editfolder_short" + i.ToString()])) { abriRoll[i].ShortDescription = Request.Form["editfolder_short" + i.ToString()]; } else { abriRoll[i].ShortDescription = ""; } if (!string.IsNullOrEmpty(Request.Form["editfolder_rel" + i.ToString()])) { abriRoll[i].Relationship = Request.Form["editfolder_rel" + i.ToString()]; } else { abriRoll[i].Relationship = ""; } } else { abriRoll[i] = null; } } _PageData.Add(abriRoll, "blogroll", null, null); } else { _PageData.Add(null, "blogroll", null, null); } } if ((!string.IsNullOrEmpty(Request.Form["hdnInheritSitemap"])) && (Request.Form["hdnInheritSitemap"].ToString().ToLower() == "true")) { _PageData.Add(true, "SitemapPathInherit", null, null); } else { _PageData.Add(false, "SitemapPathInherit", null, null); } _PageData.Add(Utilities.DeserializeSitemapPath(Request.Form, this._ContentLanguage), "SitemapPath", null, null); if ((!string.IsNullOrEmpty(Request.Form["break_inherit_button"])) && Request.Form["break_inherit_button"].ToString().ToLower() == "on") { _PageData.Add(1, "InheritMetadata", null, null); //break inherit button is check. } else { _PageData.Add(0, "InheritMetadata", null, null); } _PageData.Add(Request.Form["inherit_meta_from"], "InheritMetadataFrom", null, null); if ((!string.IsNullOrEmpty(Request.Form["TaxonomyTypeBreak"])) && Request.Form["TaxonomyTypeBreak"].ToString().ToLower() == "on") { _PageData.Add(1, "InheritTaxonomy", null, null); if ((!string.IsNullOrEmpty(Request.Form["CategoryRequired"])) && Request.Form["CategoryRequired"].ToString().ToLower() == "on") { _PageData.Add(1, "CategoryRequired", null, null); } else { _PageData.Add(Request.Form[parent_category_required.UniqueID], "CategoryRequired", null, null); } } else { _PageData.Add(0, "InheritTaxonomy", null, null); if ((!string.IsNullOrEmpty(Request.Form["CategoryRequired"])) && Request.Form["CategoryRequired"].ToString().ToLower() == "on") { _PageData.Add(1, "CategoryRequired", null, null); } else { _PageData.Add(0, "CategoryRequired", null, null); } } string IdRequests = ""; if ((Request.Form["taxlist"] != null) && Request.Form["taxlist"] != "") { IdRequests = Request.Form["taxlist"]; } _PageData.Add(IdRequests, "TaxonomyList", null, null); _PageData.Add(Request.Form[inherit_taxonomy_from.UniqueID], "InheritTaxonomyFrom", null, null); //--------------------IscontentSearchable----------------------------- if (Request.Form["chkInheritIscontentSearchable"] != null && Request.Form["chkInheritIscontentSearchable"].ToString().ToLower() == "on") { _PageData.Add(1, "IsContentSearchableInherited", null, null); if (Request.Form["chkIscontentSearchable"] != null && Request.Form["chkIscontentSearchable"].ToString().ToLower() == "on") { _PageData.Add(1, "IscontentSearchable", null, null); } else { _PageData.Add(Request.Form[current_IscontentSearchable.UniqueID], "IscontentSearchable", null, null); } } else { _PageData.Add(0, "IsContentSearchableInherited", null, null); if (Request.Form["chkIscontentSearchable"] != null && Request.Form["chkIscontentSearchable"].ToString().ToLower() == "on") { _PageData.Add(1, "IscontentSearchable", null, null); } else { _PageData.Add(0, "IscontentSearchable", null, null); } } _PageData.Add(Request.Form[inherit_IscontentSearchable_from.UniqueID], "IsContentSearchableInheritedFrom", null, null); //--------------------IsContentSearchable End ------------------------- //-------------------DisplaySettings-------------------- int totalTabs = 0; if (Request.Form["chkInheritIsDisplaySettings"] != null && Request.Form["chkInheritIsDisplaySettings"].ToString().ToLower() == "on") { _PageData.Add(1, "IsDisplaySettingsInherited", null, null); if ((Request.Form["chkIsDisplaySettingsAllTabs"] != null && Request.Form["chkIsDisplaySettingsAllTabs"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsSummary"] != null && Request.Form["chkIsDisplaySettingsSummary"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsMetaData"] != null && Request.Form["chkIsDisplaySettingsMetaData"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsAliasing"] != null && Request.Form["chkIsDisplaySettingsAliasing"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsSchedule"] != null && Request.Form["chkIsDisplaySettingsSchedule"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsComment"] != null && Request.Form["chkIsDisplaySettingsComment"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsTemplates"] != null && Request.Form["chkIsDisplaySettingsTemplates"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsTaxonomy"] != null && Request.Form["chkIsDisplaySettingsTaxonomy"].ToString().ToLower() == "on")) { if (Request.Form["chkIsDisplaySettingsSummary"] != null && Request.Form["chkIsDisplaySettingsSummary"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Summary; } if (Request.Form["chkIsDisplaySettingsMetaData"] != null && Request.Form["chkIsDisplaySettingsMetaData"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.MetaData; } if (Request.Form["chkIsDisplaySettingsAliasing"] != null && Request.Form["chkIsDisplaySettingsAliasing"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Aliasing; } if (Request.Form["chkIsDisplaySettingsSchedule"] != null && Request.Form["chkIsDisplaySettingsSchedule"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Schedule; } if (Request.Form["chkIsDisplaySettingsComment"] != null && Request.Form["chkIsDisplaySettingsComment"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Comment; } if (Request.Form["chkIsDisplaySettingsTemplates"] != null && Request.Form["chkIsDisplaySettingsTemplates"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Templates; } if (Request.Form["chkIsDisplaySettingsTaxonomy"] != null && Request.Form["chkIsDisplaySettingsTaxonomy"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Taxonomy; } _PageData.Add(totalTabs, "DisplaySettings", null, null); } else { _PageData.Add(Request.Form[current_IsDisplaySettings.UniqueID], "DisplaySettings", null, null); } } else { _PageData.Add(0, "IsDisplaySettingsInherited", null, null); if ((Request.Form["chkIsDisplaySettingsAllTabs"] != null && Request.Form["chkIsDisplaySettingsAllTabs"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsSummary"] != null && Request.Form["chkIsDisplaySettingsSummary"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsMetaData"] != null && Request.Form["chkIsDisplaySettingsMetaData"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsAliasing"] != null && Request.Form["chkIsDisplaySettingsAliasing"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsSchedule"] != null && Request.Form["chkIsDisplaySettingsSchedule"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsComment"] != null && Request.Form["chkIsDisplaySettingsComment"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsTemplates"] != null && Request.Form["chkIsDisplaySettingsTemplates"].ToString().ToLower() == "on") || (Request.Form["chkIsDisplaySettingsTaxonomy"] != null && Request.Form["chkIsDisplaySettingsTaxonomy"].ToString().ToLower() == "on")) { if (Request.Form["chkIsDisplaySettingsSummary"] != null && Request.Form["chkIsDisplaySettingsSummary"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Summary; } if (Request.Form["chkIsDisplaySettingsMetaData"] != null && Request.Form["chkIsDisplaySettingsMetaData"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.MetaData; } if (Request.Form["chkIsDisplaySettingsAliasing"] != null && Request.Form["chkIsDisplaySettingsAliasing"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Aliasing; } if (Request.Form["chkIsDisplaySettingsSchedule"] != null && Request.Form["chkIsDisplaySettingsSchedule"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Schedule; } if (Request.Form["chkIsDisplaySettingsComment"] != null && Request.Form["chkIsDisplaySettingsComment"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Comment; } if (Request.Form["chkIsDisplaySettingsTemplates"] != null && Request.Form["chkIsDisplaySettingsTemplates"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Templates; } if (Request.Form["chkIsDisplaySettingsTaxonomy"] != null && Request.Form["chkIsDisplaySettingsTaxonomy"].ToString().ToLower() == "on") { totalTabs += (int)EkEnumeration.FolderTabDisplaySettings.Taxonomy; } _PageData.Add(totalTabs, "DisplaySettings", null, null); } else { _PageData.Add(1, "DisplaySettings", null, null); } } _PageData.Add(Request.Form[inherit_IsDisplaySettings_from.UniqueID], "DisplaySettingsInheritedFrom", null, null); //-------------------DisplaySettingsEnd------------------ if (Request.Form["chkInheritAliases"] != null && Request.Form["chkInheritAliases"].ToString().ToLower() == "on") { _PageData.Add(1, "InheritAlias", null, null); if (Request.Form["chkForceAliasing"] != null && Request.Form["chkForceAliasing"].ToString().ToLower() == "on") { _PageData.Add(1, "AliasRequired", null, null); } else { _PageData.Add(Request.Form[current_alias_required.UniqueID], "AliasRequired", null, null); } } else { _PageData.Add(0, "InheritAlias", null, null); if (Request.Form["chkForceAliasing"] != null && Request.Form["chkForceAliasing"].ToString().ToLower() == "on") { _PageData.Add(1, "AliasRequired", null, null); } else { _PageData.Add(0, "AliasRequired", null, null); } } _PageData.Add(Request.Form[inherit_alias_from.UniqueID], "InheritAliasFrom", null, null); // Update - add flagging items: ProcessFlaggingPostBack(_PageData); m_refContent.UpdateFolderPropertiesv2_0(_PageData); if (folder_data.FolderType == 2) //OrElse folder_data.Id = 0 Avoiding root to be site aliased { arSiteAliasList = Request.Form["savedSiteAlias"].TrimStart(" ".ToCharArray()).TrimStart(",".ToCharArray()).Split(",".ToCharArray()); foreach (string aliasStr in arSiteAliasList) { if (aliasStr != string.Empty) { siteAliasList.Add(aliasStr); } } _refSiteAliasApi = new Ektron.Cms.SiteAliasApi(); _refSiteAliasApi.Save(folder_data.Id, siteAliasList); } if ((string.IsNullOrEmpty(Request.Form["suppress_notification"])) && (_FolderType != (int)Ektron.Cms.Common.EkEnumeration.FolderType.Catalog)) { m_refContent.UpdateSubscriptionPropertiesForFolder(_FolderId, sub_prop_data); m_refContent.UpdateSubscriptionsForFolder(_FolderId, page_subscription_data); } if (subscriptionRestore) { m_refContent.DeleteSubscriptionsForContentinFolder(_FolderId); } if ((init_xmlconfig != Request.Form["xmlconfig"] || bInheritanceIsDif) && _FolderType != (int)Ektron.Cms.Common.EkEnumeration.FolderType.Calendar) { XmlInd = _ContentApi.EkXmlIndexingRef; if (Request.Form["xmlconfig"] != "0" && Request.Form["xmlconfig"] != "") { XmlInd.ReIndexAllDoc(Convert.ToInt64(Request.Form["xmlconfig"])); } else // inheritance has been turned on { if (Strings.LCase(Request.Form["frm_xmlinheritance"]) == "on") { folder_data = _ContentApi.GetFolderById(_FolderId, false, true); if (!(folder_data.XmlConfiguration == null)) { for (int x = 0; x <= (folder_data.XmlConfiguration.Length - 1); x++) { XmlInd.ReIndexAllDoc(folder_data.XmlConfiguration[x].Id); } //reverting 27535 - do not udpate xml_index table with new xml index search } else { XmlInd.RemoveAllIndexDoc(_FolderId); } //reverting 27535 - do not udpate xml_index table with new xml index search } else { XmlInd.RemoveAllIndexDoc(_FolderId); } } } if (string.IsNullOrEmpty(Request.Form["break_inherit_button"])) { _CustomFieldsApi.ProcessCustomFields(_FolderId); } else if ((Request.Form["break_inherit_button"] != null) && Request.Form["break_inherit_button"].ToString().ToLower() == "on") { if (folder_data.MetaInherited == 0) { _CustomFieldsApi.ProcessCustomFields(_FolderId); } } //If (Request.Form("break_inherit_button") IsNot Nothing AndAlso Request.Form("break_inherit_button").ToString().ToLower() = "on") Then // 'break inherit button is checked. // _CustomFieldsApi.ProcessCustomFields(_FolderId) //ElseIf folder_data.MetaInherited = 0 Then // _CustomFieldsApi.ProcessCustomFields(_FolderId) //ElseIf Request.Form("break_inherit_button") Is Nothing Then // _CustomFieldsApi.ProcessCustomFields(_FolderId) //End If } if (Request.Form["oldfoldername"] == Request.Form["foldername"]) { Response.Redirect((string)("content.aspx?LangType=" + _ContentLanguage + "&action=ViewFolder&id=" + Request.Form[folder_id.UniqueID]), false); } else { Response.Redirect("content.aspx?TreeUpdated=1&LangType=" + _ContentLanguage + "&action=ViewFolder&id=" + Request.Form[folder_id.UniqueID] + "&reloadtrees=Forms,Content,Library", false); } if (folder_data.FolderType == (int)Ektron.Cms.Common.EkEnumeration.FolderType.Catalog) { ProcessProductTemplatesPostBack(); } else { ProcessContentTemplatesPostBack(); } }
public async Task <WecharSendMessage> CreateWecharSendMessage(SendMessageInfo sendMessageInfo) { var YaeherConsultationInfo = await _YaeherConsultationrepository.FirstOrDefaultAsync(a => a.ConsultNumber == sendMessageInfo.ConsultNumber); // 咨询人 var ConsultantUserInfo = await _YaeherUserrepository.FirstOrDefaultAsync(a => a.Id == YaeherConsultationInfo.ConsultantID); var DoctorInfo = await _YaeherDoctorrepository.FirstOrDefaultAsync(a => a.Id == YaeherConsultationInfo.DoctorID); // 医生 var DoctorUserInfo = await _YaeherUserrepository.FirstOrDefaultAsync(a => a.Id == DoctorInfo.UserID); // 查询微信模板ID WecharSendMessage wecharSendMessage = new WecharSendMessage(); // 查询当前模板ID var YaeherMessageInfo = await _YaeherMessageTemplaterepository.FirstOrDefaultAsync(a => a.TemplateCode == sendMessageInfo.TemplateCode); wecharSendMessage.TemplateId = YaeherMessageInfo.TemplateId; // 是否自动发送 bool SendState = bool.Parse(_SystemParameterrepository.GetAll().Where(a => a.SystemCode == "WecharSendState").FirstOrDefault().Code); // 查询消息模板内容 var SendMessageList = _SendMessagerepository.GetAll().Where(a => a.TemplateCode == sendMessageInfo.TemplateCode && a.OperationType == sendMessageInfo.OperationType); try { if (SendMessageList.Count() > 0) { SendWechaMessage sendWechaMessage = new SendWechaMessage(); SendMsmHelper sendMsmHelper = new SendMsmHelper(); List <WecharSendMessage> WecharSendMessageList = new List <WecharSendMessage>(); using (var unitOfWork = _unitOfWorkManager.Begin()) { var IsDoctor = false; string MessageType = string.Empty; foreach (var SendMessageInfo in SendMessageList) { WecharSendMessage wecharMessage = new WecharSendMessage(); wecharMessage.ConsultNumber = sendMessageInfo.ConsultNumber; wecharMessage.TemplateCode = sendMessageInfo.TemplateCode; wecharMessage.OperationType = sendMessageInfo.OperationType; wecharMessage.ConsultantName = YaeherConsultationInfo.PatientName; // 修改为患者用户名 wecharMessage.DoctorName = YaeherConsultationInfo.DoctorName; wecharMessage.ConsultJson = JsonHelper.ToJson(YaeherConsultationInfo); wecharMessage.BackUrl = SendMessageInfo.BackUrl; wecharMessage.FirstMessage = SendMessageInfo.FirstMessage; // 查询标语 wecharMessage.Keyword1 = SendMessageInfo.Keyword1; // 称呼人 wecharMessage.Keyword2 = SendMessageInfo.Keyword2; // 时间 wecharMessage.Keyword3 = SendMessageInfo.Keyword3; // 内容 wecharMessage.MessageRemark = SendMessageInfo.MessageRemark; // 备注 wecharMessage.TemplateId = YaeherMessageInfo.TemplateId; // 将对应信息转为发送模板 SendTemplate WecharTemplate = new SendTemplate(); switch (SendMessageInfo.Recipient) { case "Patient": // 接受人为咨询者 wecharMessage.ToUser = ConsultantUserInfo.WecharOpenID; WecharTemplate = sendWechaMessage.ConsultantWecharTemplate(wecharMessage, sendMessageInfo.Inquiry); // 赋值咨询者信息 break; case "Doctor": // 接受人为医生 wecharMessage.ToUser = DoctorUserInfo.WecharOpenID; IsDoctor = true; WecharTemplate = sendWechaMessage.DoctorWecharTemplate(wecharMessage, sendMessageInfo.EvaluateLevel, sendMessageInfo.WarningTime); // 赋值医生信息 MessageType = WecharTemplate.MessageType; break; } // 将对应信息转为发送实际内容 wecharMessage.WecharData = sendWechaMessage.WecharContent(WecharTemplate); #region // 执行微信消息发送 TemplateModel templateModel = new TemplateModel(); if (SendState) // 是否实时发送 { var TokenInfo = _systemTokenService.SystemTokenList("Wechar").Result; templateModel = sendWechaMessage.SendWecharMessage(wecharMessage.WecharData, TokenInfo.access_token).Result; } if (templateModel.errcode == "error" || !SendState) { #region 增加重试机制 HangFireJob WecharhangFireJob = new HangFireJob(); WecharhangFireJob.JobName = "微信定时服务"; WecharhangFireJob.JobCode = "WechaMessageSend"; WecharhangFireJob.BusinessID = Commons.GetCurrentTimeStepNumber(); //int.Parse(new RandomCode().GenerateCheckCodeNum(5)); WecharhangFireJob.BusinessCode = sendMessageInfo.ConsultNumber; Random rd = new Random(); int Seconds = rd.Next(1, 5); WecharhangFireJob.JobRunTime = DateTime.Now.AddSeconds(Seconds); // 随机时间 WecharhangFireJob.JobSates = "Open"; WecharhangFireJob.CallbackUrl = Commons.AdminIp + "api/SendWechar/"; WecharhangFireJob.JobParameter = wecharMessage.WecharData; // 将需要发送的内容整理好 HangfireScheduleJob job = new HangfireScheduleJob(); JobModel model = new JobModel(); model.CallbackUrl = WecharhangFireJob.CallbackUrl; //回调URL model.queues = "adminqueue"; model.CallbackContent = JsonHelper.ToJson(WecharhangFireJob); //回调参数 model.Timespan = WecharhangFireJob.JobRunTime; //运行时间 var returnjobid = job.Schedule(model); if (returnjobid.IndexOf("error") < 0) { WecharhangFireJob.JobRunID = returnjobid; } WecharhangFireJob = await _HangFireJobrepository.InsertAsync(WecharhangFireJob); templateModel.msgid = WecharhangFireJob.BusinessID.ToString(); templateModel.errmsg = "Undo"; #endregion if (templateModel.errcode == "error") { #region 将错误日志存起来 YaeherOperList yaeherOperList = new YaeherOperList(); yaeherOperList.CreatedOn = DateTime.Now; yaeherOperList.OperExplain = JsonHelper.ToJson(sendMessageInfo); yaeherOperList.OperContent = "error:" + templateModel.errmsg; yaeherOperList.OperType = "发送消息异常测试备用:" + sendMessageInfo.OperationType; await _YaeherOperListrepository.InsertAsync(yaeherOperList); #endregion } } wecharMessage.MsgID = templateModel.msgid; wecharMessage.Status = templateModel.errmsg; wecharMessage.MsgType = wecharMessage.MsgType; WecharSendMessageList.Add(wecharMessage); #endregion } #region 发送短信 if (IsDoctor) { YaeherSendMsm yaeherSendMsm = new YaeherSendMsm(); yaeherSendMsm.PhoneNumbers = DoctorUserInfo.PhoneNumber == null? DoctorInfo.PhoneNumber : DoctorUserInfo.PhoneNumber; // 医生电话 yaeherSendMsm.MessageType = MessageType; // 短信类型 yaeherSendMsm.TemplateParam = "{\"remark\":\"" + sendMessageInfo.ConsultNumber + "\"}"; // 提示短信内容 // 发送短信 并存储记录 if (yaeherSendMsm.PhoneNumbers != null && yaeherSendMsm.MessageType != null) { var SendMessage = sendMsmHelper.SendMsm(yaeherSendMsm); // 发送短信 YaeherMessageRemind MessageRemind = new YaeherMessageRemind(); MessageRemind.UserID = 0; MessageRemind.UserName = "******"; MessageRemind.PhoneNumber = yaeherSendMsm.PhoneNumbers; MessageRemind.MessageType = yaeherSendMsm.MessageType; MessageRemind.Message = SendMessage.ToString(); //将发送短信消息存起来 MessageRemind.VerificationCode = ""; MessageRemind.Message = yaeherSendMsm.TemplateParam; MessageRemind.CreatedBy = 0; MessageRemind.CreatedOn = DateTime.Now; MessageRemind.EffectiveLength = 0; MessageRemind.EffectiveTime = DateTime.Now; await _MessageRemindrepository.InsertAsync(MessageRemind); } } #endregion #region 将发微信的消息记录 if (WecharSendMessageList.Count > 0) { foreach (var wecharMessage in WecharSendMessageList) { await _repository.InsertAsync(wecharMessage); } } #endregion #region 增加有效用户访问记录 暂时关掉获取有效访问量 //YaeherOperList yaeherOperList = new YaeherOperList(); //yaeherOperList.CreatedOn = DateTime.Now; //yaeherOperList.OperExplain = "ConsultNumber:"+ sendMessageInfo.ConsultNumber; //yaeherOperList.OperContent = JsonHelper.ToJson(ConsultantUserInfo); //yaeherOperList.OperType = "发送消息成功"; //await _YaeherOperListrepository.InsertAsync(yaeherOperList); #endregion unitOfWork.Complete(); } } } catch (Exception ex) { #region 增加有效用户访问记录 YaeherOperList yaeherOperList = new YaeherOperList(); yaeherOperList.CreatedOn = DateTime.Now; yaeherOperList.OperExplain = JsonHelper.ToJson(sendMessageInfo); yaeherOperList.OperContent = "error:" + ex.ToString(); yaeherOperList.OperType = "发送消息异常:" + sendMessageInfo.OperationType; await _YaeherOperListrepository.InsertAsync(yaeherOperList); #endregion } return(wecharSendMessage); }
/// <summary>Save eFleet Incident /// <CreatedBy>Bhushan Dod</CreatedBy> /// <CreatedFor>InsertVehicleIncident</CreatedFor> /// <CreatedOn>September-15-2017</CreatedOn> /// </summary> /// <param name="eFleetIncidentModel"></param> /// <returns></returns> public ServiceResponseModel <string> InsertVehicleIncident(eFleetIncidentModel objModel) { var objReturnModel = new ServiceResponseModel <string>(); try { var objeFleetVehicleIncidentRepository = new eFleetVehicleIncidentRepository(); var Obj = new eFleetVehicleIncident(); var objDAR = new DARModel(); AutoMapper.Mapper.CreateMap <eFleetIncidentModel, eFleetVehicleIncident>(); Obj = AutoMapper.Mapper.Map(objModel, Obj); Obj.CreatedBy = objModel.UserId; Obj.CreatedDate = DateTime.UtcNow; objeFleetVehicleIncidentRepository.Add(Obj); if (Obj.IncidentID > 0) { // objDAR.ActivityDetails = objModel.ActivityDetails; objDAR.ActivityDetails = DarMessage.RegisterNeweFleetIncidentVehicle(objModel.LocationName); objDAR.LocationId = objModel.LocationID; // objDAR.TaskType = objModel.TaskType; objDAR.TaskType = (long)TaskTypeCategory.EfleetIncidentSubmission; objDAR.CreatedBy = objModel.UserId; objDAR.CreatedOn = DateTime.UtcNow; objDAR.DeletedBy = null; objDAR.DeletedOn = null; objDAR.IsDeleted = false; objDAR.IsManual = false; objDAR.ModifiedBy = null; objDAR.ModifiedOn = null; objDAR.UserId = objModel.UserId; objDAR.StartTime = objModel.AccidentDate.ToString(); objDAR.EndTime = DateTime.UtcNow.ToString(); // objDARRepository.Add(objDAR); Result result = _ICommonMethod.SaveDAR(objDAR); #region Email var objEmailLogRepository = new EmailLogRepository(); var objEmailReturn = new List <EmailToManagerModel>(); var objListEmailog = new List <EmailLog>(); var objTemplateModel = new TemplateModel(); workorderEMSEntities db = new workorderEMSEntities(); if (result == Result.Completed) { objEmailReturn = objEmailLogRepository.SendEmailToManagerForeFleetInspection(objModel.LocationID, objModel.UserId).Result; } if (objEmailReturn.Count > 0 && result == Result.Completed) { foreach (var item in objEmailReturn) { bool IsSent = false; var objEmailHelper = new EmailHelper(); objEmailHelper.emailid = item.ManagerEmail; objEmailHelper.ManagerName = item.ManagerName; //objEmailHelper.DriverNameforFueling = objModel.DriverName; /// objEmailHelper.FuelType = (from gc in db.GlobalCodes where gc.GlobalCodeId == objModel.FuelType select gc.CodeName).FirstOrDefault(); objEmailHelper.IncidentDescription = objModel.Description; if (objModel.Preventability == true) { objEmailHelper.Prevenatability = "Yes"; } else { objEmailHelper.Prevenatability = "No"; } objEmailHelper.NumberOfInjuries = objModel.NumberOfInjuries; objEmailHelper.City = objModel.City; objEmailHelper.VehicleNumber = objModel.VehicleNumber; objEmailHelper.LocationName = objModel.LocationName; objEmailHelper.UserName = item.UserName; objEmailHelper.QrCodeId = objModel.QRCodeID; objEmailHelper.AccidentDate = objModel.AccidentDate.ToString(); //objEmailHelper.InfractionStatus = obj.Status; objEmailHelper.MailType = "EfleetIncidentForService"; objEmailHelper.SentBy = item.RequestBy; objEmailHelper.LocationID = item.LocationID; objEmailHelper.TimeAttempted = DateTime.UtcNow.ToMobileClientTimeZone(objTemplateModel.TimeZoneName, objTemplateModel.TimeZoneOffset, objTemplateModel.IsTimeZoneinDaylight, false).ToString(); IsSent = objEmailHelper.SendEmailWithTemplate(); //Push Notification string message = PushNotificationMessages.eFleetIncidentForServiceReported(objModel.LocationName, objModel.QRCodeID, objModel.VehicleNumber); PushNotification.GCMAndroid(message, item.DeviceId, objEmailHelper); if (IsSent == true) { var objEmailog = new EmailLog(); try { objEmailog.CreatedBy = item.RequestBy; objEmailog.CreatedDate = DateTime.UtcNow; objEmailog.DeletedBy = null; objEmailog.DeletedOn = null; objEmailog.LocationId = item.LocationID; objEmailog.ModifiedBy = null; objEmailog.ModifiedOn = null; objEmailog.SentBy = item.RequestBy; objEmailog.SentEmail = item.ManagerEmail; objEmailog.Subject = objEmailHelper.Subject; objEmailog.SentTo = item.ManagerUserId; objListEmailog.Add(objEmailog); } catch (Exception) { throw; } } } } using (var context = new workorderEMSEntities()) { context.EmailLogs.AddRange(objListEmailog); context.SaveChanges();; } // //var x = EmailLogRepository.InsertEntitiesNew("EmailLog", objListEmailog); // //Task<bool> x = null; // //foreach (var i in objListEmailog) // //{ // // x = objEmailLogRepository.SaveEmailLogAsync(i); // //} //} #endregion Email if (Obj.IncidentID > 0) { objReturnModel.Response = Convert.ToInt32(ServiceResponse.SuccessResponse, CultureInfo.InvariantCulture); objReturnModel.Message = CommonMessage.Successful(); } } } catch (Exception ex) { WorkOrderEMS.BusinessLogic.Exception_B.Exception_B.exceptionHandel_Runtime(ex, "ServiceResponseModel<string> InsertVehicleIncident(eFleetIncidentModel objModel)", "while insert eFleet vehicle incident", objModel); objReturnModel.Message = ex.Message; objReturnModel.Response = Convert.ToInt32(ServiceResponse.ExeptionResponse, CultureInfo.CurrentCulture); objReturnModel.Data = null; } return(objReturnModel); }
public async Task <ActionResult> Create(TemplateModel templateModel) { var response = new doorserve.Models.ResponseModel(); Boolean Isvalid = false; DataTable dtToEmailExcelData = new DataTable(); templateModel.UserId = CurrentUser.UserId; if (CurrentUser.UserTypeName.ToLower() != "super admin") { templateModel.CompanyId = CurrentUser.CompanyId; } if (!string.IsNullOrEmpty(templateModel.ScheduleDate) && !string.IsNullOrEmpty(templateModel.ScheduleTime)) { var times = templateModel.ScheduleTime.Split(':'); templateModel.ScheduleDateTime = Convert.ToDateTime(templateModel.ScheduleDate).AddHours(Convert.ToInt32(times[0])).AddMinutes(Convert.ToInt32(times[1])).ToString(); } if (templateModel.MessageTypeName == "SMTP Gateway") { if (templateModel.ToEmailFile != null) { string excelPath = SaveFile(templateModel.ToEmailFile, "ToEmail"); string conString = string.Empty; string extension = Path.GetExtension(templateModel.ToEmailFile.FileName); switch (extension) { case ".xls": //Excel 97-03 conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString; break; case ".xlsx": //Excel 07 or higher conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString; break; } conString = string.Format(conString, excelPath); using (OleDbConnection excel_con = new OleDbConnection(conString)) { excel_con.Open(); string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString(); dtToEmailExcelData.Columns.AddRange(new DataColumn[1] { new DataColumn("ToEmail", typeof(string)) }); using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT [To Email]as ToEmail FROM [" + sheet1 + "]", excel_con)) { oda.Fill(dtToEmailExcelData); } excel_con.Close(); } if (dtToEmailExcelData != null && dtToEmailExcelData.Rows.Count > 0) { var emailChecklist = dtToEmailExcelData.AsEnumerable().Select(x => new { Valid = IsEmail(x.Field <string>("ToEmail")) }).ToList(); int Count = (from mail in emailChecklist where mail.Valid == false select mail).Count(); if (Count > 0) { response.Response = "Upload Valid Email"; response.IsSuccess = Isvalid; TempData["response"] = response; return(Redirect("Create")); } else { Isvalid = true; } var ToEmailList = dtToEmailExcelData.AsEnumerable().Select(r => r.Field <string>("ToEmail")).ToList(); templateModel.UploadedEmail = string.Join(";", ToEmailList); templateModel.TotalCount = dtToEmailExcelData.Rows.Count; } } if (!string.IsNullOrEmpty(templateModel.ToEmail)) { string[] strToemail = templateModel.ToEmail.Split(';'); templateModel.TotalCount += strToemail.Length; Isvalid = true; } if (!string.IsNullOrEmpty(templateModel.ToCCEmail)) { string[] strToEmailcc = templateModel.ToCCEmail.Split(';'); templateModel.TotalCount += strToEmailcc.Length; Isvalid = true; } if (templateModel.TemplateTypeId == 69) { Isvalid = true; } if (!Isvalid) { response.Response = "Please Enter To CC Email Or Upload To Email Excel file"; response.IsSuccess = Isvalid; TempData["response"] = response; return(Redirect("Index")); } } else { if (templateModel.ToMobileNoFile != null) { string excelPath = SaveFile(templateModel.ToMobileNoFile, "ToMobile"); string conString = string.Empty; string extension = Path.GetExtension(templateModel.ToMobileNoFile.FileName); switch (extension) { case ".xls": //Excel 97-03 conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString; break; case ".xlsx": //Excel 07 or higher conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString; break; } conString = string.Format(conString, excelPath); DataTable dtToMobileNoExcelData = new DataTable(); using (OleDbConnection excel_con = new OleDbConnection(conString)) { excel_con.Open(); string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString(); dtToMobileNoExcelData.Columns.AddRange(new DataColumn[1] { new DataColumn("ToMobileNo", typeof(string)) }); using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT [To MobileNo]as ToMobileNo FROM [" + sheet1 + "]", excel_con)) { oda.Fill(dtToMobileNoExcelData); } excel_con.Close(); } if (dtToMobileNoExcelData != null && dtToMobileNoExcelData.Rows.Count > 0) { var ToMobileList = dtToMobileNoExcelData.AsEnumerable().Select(r => r.Field <string>("ToMobileNo")).ToList(); templateModel.UploadedMobile = string.Join(",", ToMobileList); templateModel.TotalCount = dtToMobileNoExcelData.Rows.Count; } } if (!string.IsNullOrEmpty(templateModel.PhoneNumber)) { string[] strPhoneNumber = templateModel.PhoneNumber.Split(','); templateModel.TotalCount += strPhoneNumber.Length; Isvalid = true; } if (templateModel.TemplateTypeId == 69) { Isvalid = true; } } if (Isvalid) { response = await _templateRepo.AddUpdateDeleteTemplate(templateModel, 'I'); // response.Response = "Successfully inserted record"; //response.IsSuccess = Isvalid; TempData["response"] = response; } return(RedirectToAction("Index")); }
public IActionResult Template(TemplateModel model) { InitializeModel(model); ForceSetOutputValues(model); return(View(model)); }
private async void PinTemplateToStart(TemplateModel template) { // Check whether the tile has been pinned before... if (!SecondaryTile.Exists(template.TemplateId.ToString())) { // Get assets (WARNING: It'll retrieve these from the base Revent-project!) Uri square150x150Logo = new Uri("ms-appx:///Assets/Logo/Square150x150Logo.scale-100.png"); Uri square44x44Logo = new Uri("ms-appx:///Assets/Logo/Square44x44Logo.scale-100.png"); Uri square71x71Logo = new Uri("ms-appx:///Assets/Logo/Square71x71Logo.scale-100.png"); Uri wide310x150Logo = new Uri("ms-appx:///Assets/Logo/Wide310x150Logo.scale-100.png"); Uri square310x310Logo = new Uri("ms-appx:///Assets/Logo/Square310x310Logo.scale-100.png"); // Set the activation arguments for the secondary tile string tileActivationArgs = template.TemplateId.ToString(); // Create the secondary tile... SecondaryTile secTile = new SecondaryTile(template.TemplateId.ToString(), template.TemplateName, tileActivationArgs, square150x150Logo, TileSize.Square150x150); secTile.VisualElements.ShowNameOnSquare150x150Logo = true; secTile.VisualElements.ShowNameOnWide310x150Logo = true; secTile.VisualElements.ShowNameOnSquare310x310Logo = true; secTile.VisualElements.Square44x44Logo = square44x44Logo; secTile.VisualElements.Square71x71Logo = square71x71Logo; // #TODO Is missing secTile.VisualElements.Wide310x150Logo = wide310x150Logo; secTile.VisualElements.Square310x310Logo = square310x310Logo; // And now pin it! await secTile.RequestCreateAsync(); // Let's get the stuff and show it on the tile if the user wants that var _localSettings = ApplicationData.Current.LocalSettings; const string infoOnTiles = "MoreInfoOnTiles"; if (_localSettings.Values[infoOnTiles].ToString() == "true") { // Try to make a Tile Notification try { TileContent content; if (template.AppointmentSubject != "" && template.AppointmentLocation != "") { // First, let's construct the Tiles content = new TileContent() { Visual = new TileVisual() { Branding = TileBranding.NameAndLogo, // The small tile, well uh, let's keep that sucker standard // So let's edit with the Medium, Wide and Large-tiles and make these look awesome // Medium TileMedium = new TileBinding() { Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { HintStyle = AdaptiveTextStyle.Caption, Text = template.AppointmentSubject }, new AdaptiveText() { HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, HintMaxLines = 3, Text = template.AppointmentDetails } } } }, // Wide TileWide = new TileBinding() { Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { HintStyle = AdaptiveTextStyle.Body, Text = template.AppointmentSubject }, new AdaptiveText() { HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, HintMaxLines = 3, Text = template.AppointmentDetails } } } }, // Large TileLarge = new TileBinding() { Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { HintStyle = AdaptiveTextStyle.Subtitle, Text = template.AppointmentSubject }, new AdaptiveText() { HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, Text = template.AppointmentLocation }, new AdaptiveText() { HintStyle = AdaptiveTextStyle.Caption, HintWrap = true, Text = template.AppointmentDetails } } } } } }; // END OF NORMAL-TILE // Now, let's turn the code into a tile notification var tileNotification = new TileNotification(content.GetXml()); // Now try to give it a tag, in case the tile needs to be updated try { tileNotification.Tag = template.TemplateId.ToString(); } catch { Debug.WriteLine("Could not give Secondary Live Tile an ID"); } // In case stuff f**k up, it won't add the ID to the Tile notification // And show the new Tile Notification! TileUpdateManager.CreateTileUpdaterForSecondaryTile(template.TemplateId.ToString()).Update(tileNotification); } } catch { Debug.WriteLine("Could not create Secondary Live Tile"); } } } }
public void BuildForUpdater() { var model = new TemplateModel(_context); Build(model); }
private static IEnumerable<Field> TemplateFields(FieldCollection templateFields, TemplateModel model) { foreach (FieldElement fieldElement in templateFields) { String key = fieldElement.Key; Field field = null; switch (fieldElement.Type) { case FieldType.Standard: StandardField standardField = new StandardField (); standardField.Value = model.GetField(key, FieldAttribute.Value, fieldElement.Value.Value); field = standardField; break; case FieldType.Date: DateField dateField = new DateField (); if (fieldElement.DateStyle != FieldDateTimeStyle.Unspecified) dateField.DateStyle = fieldElement.DateStyle; if (fieldElement.TimeStyle != FieldDateTimeStyle.Unspecified) dateField.TimeStyle = fieldElement.TimeStyle; if (fieldElement.IgnoresTimeZone.HasValue) dateField.IgnoresTimeZone = fieldElement.IgnoresTimeZone.Value; if (fieldElement.IsRelative.HasValue) dateField.IsRelative = fieldElement.IsRelative.Value; DateTime dateValue; if (!DateTime.TryParse(fieldElement.Value.Value, out dateValue)) dateValue = DateTime.MinValue; dateField.Value = model.GetField<DateTime>(key, FieldAttribute.Value, dateValue); field = dateField; break; case FieldType.Number: NumberField numberField = new NumberField (); if (fieldElement.NumberStyle != FieldNumberStyle.Unspecified) numberField.NumberStyle = fieldElement.NumberStyle; numberField.CurrencyCode = model.GetField(key, FieldAttribute.CurrencyCode, fieldElement.CurrencyCode.Value); Decimal decimalValue; if (!Decimal.TryParse(fieldElement.Value.Value, out decimalValue)) decimalValue = 0; numberField.Value = model.GetField<Decimal>(key, FieldAttribute.Value, decimalValue); field = numberField; break; } field.Key = fieldElement.Key; field.DataDetectorTypes = fieldElement.DataDetectorTypes; if (field.TextAlignment != FieldTextAlignment.Unspecified) field.TextAlignment = fieldElement.TextAlignment; field.Label = model.GetField(key, FieldAttribute.Label, fieldElement.Label.Value); field.AttributedValue = model.GetField(key, FieldAttribute.AttributedValue, fieldElement.AttributedValue.Value); field.ChangeMessage = model.GetField(key, FieldAttribute.ChangeMessage, fieldElement.ChangeMessage.Value); yield return field; } }
public override bool AddOperationToDB <TOPerationModel>(TOPerationModel operationToAdd, TemplateModel templateParam = null) { try { //if we have different types of operationToAddand operation if (typeof(TOPerationModel) != typeof(Operation)) { _dbManager.CreateEntityFromModelForPersAccount <TOPerationModel, Operation>(operationToAdd); } else { using (_unitOfWork = DIManager.UnitOfWork) { var operationId = _unitOfWork.PersonalAccountantContext.Set <Operation>().Add(operationToAdd as Operation).Id; if (templateParam != null && templateParam.IsTemplateCreated) { _unitOfWork.PersonalAccountantContext.Set <template_Operations>().Add(new template_Operations { OperationId = operationId, Name = templateParam.Name }); } _unitOfWork.Save(); } } return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// 实例化 /// </summary> /// <param name="data">模板数据</param> public PrintController(TemplateModel data) { dataList = new TemplateModel[] { data }; }
/// <summary> /// Formats the specified format. /// </summary> /// <param name="format">The format.</param> /// <param name="model">The model.</param> /// <returns>System.String.</returns> /// TODO Edit XML Comment Template for Format private static string Format(string format, TemplateModel model) { var currentPos = 0; var sbResult = new StringBuilder(); var sbItem = new StringBuilder(); var inside = false; var len = format.Length; while (true) { var c = format[currentPos]; switch (c) { case '{': if (inside) { FormatError(); } else if (currentPos < len - 1 && format[currentPos + 1] == '{') //escape char { sbResult.Append('{'); currentPos++; } else { inside = true; } break; case '}': if (currentPos < len - 1 && format[currentPos + 1] == '}') { sbResult.Append('}'); currentPos++; } else { if (!inside) { FormatError(); } inside = false; var name = sbItem.ToString(); Console.WriteLine(name); sbItem.Clear(); sbResult.Append(EvaluateParameter(name, model)); } break; default: if (inside) { sbItem.Append(c); } else { sbResult.Append(c); } break; } currentPos++; if (currentPos == format.Length) { break; } } if (inside) { FormatError(); } return(sbResult.ToString()); }
/// <summary> /// Render the html and adds it to the cache. /// </summary> /// <param name="helper">The helper.</param> /// <param name="partialRequest">The partial request.</param> /// <param name="content">The content.</param> /// <param name="templateModel">The template model.</param> /// <param name="settings">The settings.</param> /// <param name="cacheKey">The cache key.</param> protected virtual void RenderAndAddToCache(HtmlHelper helper, PartialRequest partialRequest, IContent content, TemplateModel templateModel, ICacheableSettings settings, string cacheKey) { using (var cacheWriter = new StringWriter()) { var currentWriter = helper.ViewContext.Writer; helper.ViewContext.Writer = cacheWriter; DefaultRenderer.Render(helper, partialRequest, content, templateModel); var html = cacheWriter.ToString(); currentWriter.Write(html); helper.ViewContext.Writer = currentWriter; if (helper.ViewContext.HttpContext.Error == null) { InsertToCache(html); } } void InsertToCache(string html) { if (settings.MaxTimeInCache == TimeSpan.Zero) { Cache.Insert(cacheKey, html, new CacheEvictionPolicy(null, MasterCacheKeys)); } else { Cache.Insert(cacheKey, html, new CacheEvictionPolicy(settings.MaxTimeInCache, CacheTimeoutType.Absolute, null, MasterCacheKeys)); } } }
public void LoadTemplate(string template, TemplateModel parameters) { PassbookGeneratorSection section = System.Configuration.ConfigurationManager.GetSection("passbookGenerator") as PassbookGeneratorSection; if (section == null) throw new System.Configuration.ConfigurationErrorsException("\"passbookGenerator\" section could not be loaded."); String path = TemplateModel.MapPath(section.AppleWWDRCACertificate); if (File.Exists(path)) this.AppleWWDRCACertificate = File.ReadAllBytes(path); TemplateElement templateConfig = section .Templates .OfType<TemplateElement>() .FirstOrDefault(t => String.Equals(t.Name, template, StringComparison.OrdinalIgnoreCase)); if (templateConfig == null) throw new System.Configuration.ConfigurationErrorsException(String.Format("Configuration for template \"{0}\" could not be loaded.", template)); this.Style = templateConfig.PassStyle; if (this.Style == PassStyle.BoardingPass) this.TransitType = templateConfig.TransitType; // Certificates this.CertificatePassword = templateConfig.CertificatePassword; this.CertThumbprint = templateConfig.CertificateThumbprint; path = TemplateModel.MapPath(templateConfig.Certificate); if (File.Exists(path)) this.Certificate = File.ReadAllBytes(path); if (String.IsNullOrEmpty(this.CertThumbprint) && this.Certificate == null) throw new System.Configuration.ConfigurationErrorsException("Either Certificate or CertificateThumbprint is not configured correctly."); // Standard Keys this.Description = templateConfig.Description.Value; this.OrganizationName = templateConfig.OrganizationName.Value; this.PassTypeIdentifier = templateConfig.PassTypeIdentifier.Value; this.TeamIdentifier = templateConfig.TeamIdentifier.Value; // Associated App Keys if (templateConfig.AppLaunchURL != null && !String.IsNullOrEmpty(templateConfig.AppLaunchURL.Value)) this.AppLaunchURL = templateConfig.AppLaunchURL.Value; this.AssociatedStoreIdentifiers.AddRange(templateConfig.AssociatedStoreIdentifiers.OfType<ConfigurationProperty<int>>().Select(s => s.Value)); // Visual Appearance Keys this.BackgroundColor = templateConfig.BackgroundColor.Value; this.ForegroundColor = templateConfig.ForegroundColor.Value; this.GroupingIdentifier = templateConfig.GroupingIdentifier.Value; this.LabelColor = templateConfig.LabelColor.Value; this.LogoText = templateConfig.LogoText.Value; this.SuppressStripShine = templateConfig.SuppressStripShine.Value; // Web Service Keys this.AuthenticationToken = templateConfig.AuthenticationToken.Value; this.WebServiceUrl = templateConfig.WebServiceURL.Value; // Fields this.AuxiliaryFields.AddRange(TemplateFields(templateConfig.AuxiliaryFields, parameters)); this.BackFields.AddRange(TemplateFields(templateConfig.BackFields, parameters)); this.HeaderFields.AddRange(TemplateFields(templateConfig.HeaderFields, parameters)); this.PrimaryFields.AddRange(TemplateFields(templateConfig.PrimaryFields, parameters)); this.SecondaryFields.AddRange(TemplateFields(templateConfig.SecondaryFields, parameters)); // Template Images foreach (ImageElement image in templateConfig.Images) { String imagePath = TemplateModel.MapPath(image.FileName); if (File.Exists(imagePath)) this.Images[image.Type] = File.ReadAllBytes(imagePath); } // Model Images (Overwriting template images) foreach (KeyValuePair<PassbookImage, byte[]> image in parameters.GetImages()) { this.Images[image.Key] = image.Value; } // Localization foreach (LanguageElement localization in templateConfig.Localizations) { Dictionary<string, string> values; if (!Localizations.TryGetValue(localization.Code, out values)) { values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); Localizations.Add(localization.Code, values); } foreach (LocalizedEntry entry in localization.Localizations) { values[entry.Key] = entry.Value; } } }
/// <summary> /// Processes the specified template. /// </summary> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>System.String.</returns> /// TODO Edit XML Comment Template for Process public string Process(string template, TemplateModel model) { return(string.IsNullOrWhiteSpace(template) ? "" : Format(template, model)); }
public void BeforeFileProcessing(TemplateModel template, List <string> files) { ExecuteTasks(task => task.BeforeFileProcessing(template, files)); }