public Template[] getTemplates() { List <Template> ts = new List <Template>(); Templates t = new Templates(); foreach (Resource resource in hapConfig.Current.BookingSystem.Resources.Values) { Template t1 = new Template(); t1.ID = resource.Name; if (t.ContainsKey(resource.Name)) { t1 = (t[resource.Name]); } else { t1.Subject = t["general"].Subject; t1.Content = t["general"].Content; } ts.Add(t1); Template t2 = new Template(); t2.ID = resource.Name + "admin"; if (t.ContainsKey(resource.Name + "admin")) { t2 = t[resource.Name + "admin"]; } else { t2.Subject = t["generaladmin"].Subject; t2.Content = t["generaladmin"].Content; } ts.Add(t2); } return(ts.ToArray()); }
public void Register(Type baseType, Type subType, params object[] arguments) { lock (Lock) { if (baseType == null) { throw new ArgumentNullException(nameof(baseType)); } if (subType == null) { throw new ArgumentNullException(nameof(subType)); } if (Templates.ContainsKey(baseType)) { throw new InjectorException($"This Injector already contains the type {baseType.Name}!"); } if (!baseType.IsAssignableFrom(subType)) { throw new ArgumentException($"The type {baseType.Name} is not assignable from {baseType.Name}!"); } var types = arguments?.Select(a => a.GetType()).ToArray() ?? Type.EmptyTypes; var ctor = subType.GetConstructor(types); if (ctor == null) { throw new ArgumentException( $"The type {subType.Name} does not have a public constructor with {types.Length} parameters to call!"); } Templates.Add(baseType, () => ctor.Invoke(arguments)); } }
public object Initialize(Type type) { lock (Lock) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (!Templates.ContainsKey(type)) { throw new ArgumentException( $"No implementations for the type {type.Name} could be found in the {nameof(Injector)}!"); } var result = Templates[type](); if (result != null && type.IsInstanceOfType(result)) { return(result); } throw new InjectorException( $"Could not initialize type `{type.Name}`, the lambda returned an invalid type! ({result?.GetType()})"); } }
public MailContent BuildMessage(string templateName, Dictionary <string, string> replaceDictionary) { if (!Templates.ContainsKey(templateName)) { throw new Exception($"Mail template {templateName} not found"); } string subject = Templates[templateName].subject; string body = Templates[templateName].template; foreach (var(key, value) in replaceDictionary) { subject = subject.Replace(key, value); body = body.Replace(key, value); } body = Layout.Replace("[content]", body); MailContent mailContent = new MailContent { subject = subject, template = body }; return(mailContent); }
private void Register(string name, Type t, Action <object> template) { if (!Templates.ContainsKey(t)) { Templates.Add(t, new Dictionary <string, Action <object> >()); } Templates[t].Add(name ?? DefaultKey, template); }
public TemplateManifest GetTemplateManifest(FileUri template) { if (Templates != null && Templates.ContainsKey(template.FileNameWithoutExtension)) { return(Templates[template.FileNameWithoutExtension]); } return(null); }
public TemplateManifest GetTemplateManifest(string templateKey) { if (Templates != null && Templates.ContainsKey(templateKey)) { return(Templates[templateKey]); } return(null); }
private void setTemplate(string key, string template) { if (Templates.ContainsKey(key)) { Templates.Remove(key); } Templates.Add(key, template); }
private async Task <FormatedDirectory> xmlReadRecurisive(XmlReader initial, CancellationToken token) { token.ThrowIfCancellationRequested(); FormatedDirectory output = new FormatedDirectory(); string outputName = initial.GetAttribute("name"); if (Insertion.IsMatch(outputName ?? String.Empty)) { outputName = outputName.Substring(1, outputName.Length - 2); if (Values.ContainsKey(outputName)) { outputName = Values[outputName].ToString(); } } output.Name = outputName; List <FormatedDirectory> subFolders = new List <FormatedDirectory>(); List <FormatedFile> subFiles = new List <FormatedFile>(); while (initial.Read()) { if (initial.Name == "Directory") { using (XmlReader inner = initial.ReadSubtree()) { subFolders.Add(await xmlReadRecurisive(inner, token)); } } if (initial.Name == "File") { string name = initial.GetAttribute("name"); if (Insertion.IsMatch(name)) { name = name.Substring(1, outputName.Length - 2); if (Values.ContainsKey(name)) { name = Values[name].ToString(); } } string template = initial.GetAttribute("template"); if (!String.IsNullOrWhiteSpace(template) && Templates.ContainsKey(template)) { subFiles.Add(await new TemplateFileParser(new Dictionary <string, object> { { "fileName", name } }).FromFile(Templates[template])); } else { subFiles.Add(new FormatedFile(name)); } } } return(output); }
private void ReadTemplates(IEnumerable <ObjectElement> allTemplateElements) { List <ObjectElement> templateList = allTemplateElements as List <ObjectElement> ?? allTemplateElements.ToList(); IEnumerable <IGrouping <string, ObjectElement> > groups = templateList.GroupBy(t => t.Heading.Name); IGrouping <string, ObjectElement>[] duplicates = groups .Where(g => g.Count() > 1) .ToArray(); foreach (IGrouping <string, ObjectElement> duplicate in duplicates) { Log.Error( "Duplicate template name '{0}' detected. Template names must be unique. See the template headings below:", duplicate.First()); Log.IndentedCollection(duplicate, Log.Error); } if (duplicates.Length > 0) { ObjectElement[] duplicate = duplicates.First().ToArray(); throw new DuplicateTemplateNameException(duplicate[0], duplicate[1]); } // Basic technique for processing templates in dependency order and catch cyclic dependency // A template can only be processed after the template it inherits has been processed. while (templateList.Count > 0) { var readTemplates = new List <ObjectElement>(); foreach (ObjectElement template in templateList) { if (string.IsNullOrEmpty(template.Heading.InheritedObjectName) || Templates.ContainsKey(template.Heading.InheritedObjectName)) { Templates[template.Heading.Name] = templateReader.Read(template); readTemplates.Add(template); } } if (readTemplates.Count > 0) { templateList.RemoveAll(t => readTemplates.Contains(t)); } else if (templateList.Count > 0) { throw new InvalidOperationException( "A cyclic dependency was detected in template inheritance. These templates could not be read: " + string.Join(", ", templateList)); } } }
public void Register <TBase>(TBase instance) { lock (Lock) { var type = typeof(TBase); if (Templates.ContainsKey(type)) { throw new InjectorException($"This Injector already contains the type {type.Name}!"); } Templates.Add(type, () => instance); } }
public ItemTemplate(string id) { if (string.IsNullOrEmpty(id)) { throw new ArgumentException($"{nameof(id)} is null or empty.", nameof(id)); } if (Templates.ContainsKey(id)) { throw new ArgumentException($"{id} has already been registered.", nameof(id)); } Templates[id] = this; this.ID = id; }
public static void SetTemplate(DustTemplate template) { Args.ThrowIf <ArgumentNullException>(string.IsNullOrEmpty(template.Name), "template.Name must be specified"); string name = template.Name.ToLowerInvariant(); if (!Templates.ContainsKey(name)) { Templates.Add(name, template); } else { Templates[name] = template; } }
protected void etemplates_ItemCommand(object source, RepeaterCommandEventArgs e) { Templates t = new Templates(); if (t.ContainsKey((string)e.CommandArgument)) { t.Remove((string)e.CommandArgument); } Template t1 = new Template(); t1.Content = ((TextBox)e.Item.FindControl("eeditor")).Text; t1.ID = (string)e.CommandArgument; t1.Subject = ((TextBox)e.Item.FindControl("esubject")).Text; t.Add(t1.ID, t1); t.Save(); Response.Redirect("./#email-templates"); }
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container) { if (item != null) { var content = (string)((ListBoxItem)item).Content; if (Templates.Count > 0) { for (int i = 0; i < Templates.Count; i++) { if (Templates.ContainsKey(content)) { return((System.Windows.DataTemplate)Templates[content]); } } } } return((System.Windows.DataTemplate)Templates["Inbox"]); }
public object ApplyTemplate(Type t, object item, string name = null) { if (!Templates.ContainsKey(t) && name == null) { return(item); } if (!Templates.ContainsKey(t) && name != null) { throw new Exception($"There are no templates registered for {t.Name}. The template {name} does not exist for type {t.Name}"); } if (!Templates[t].ContainsKey(name ?? DefaultKey) && name != null) { throw new GherkinException($"The template {name ?? "null"} fores not exist for type {t.Name}, registered templates are {Templates[t].Keys.LogFormat()}"); } if (!Templates.ContainsKey(t) || !Templates[t].ContainsKey(name ?? DefaultKey)) { return(item); } Templates[t][name ?? DefaultKey](item); return(item); }
public void Register(Type baseType, Func <object> initializer) { lock (Lock) { if (baseType == null) { throw new ArgumentNullException(nameof(baseType)); } if (initializer == null) { throw new ArgumentNullException(nameof(initializer)); } if (Templates.ContainsKey(baseType)) { throw new InjectorException($"This Injector already contains the type {baseType.Name}!"); } Templates.Add(baseType, initializer); } }
public async Task <List <FormatedFile> > GetFiles(CancellationToken token = default) { if (formatedFiles != null && !filesChanged) { return(formatedFiles); } TemplateFileParser fileParser = new TemplateFileParser(); List <FormatedFile> output = new List <FormatedFile>(); if (files != null) { foreach (File format in files) { token.ThrowIfCancellationRequested(); Values["fileName"] = format.Name; if (Templates.ContainsKey(format.Template)) { output.Add(await fileParser.FromFile(Templates[format.Template], token)); } else { FileInfo info = new FileInfo(format.Template); if (info.Exists) { output.Add(await fileParser.FromFile(info, token)); } else { throw new IllegalTemplateException("Invalid format specified"); } } } } formatedFiles = output; filesChanged = false; return(formatedFiles); }
public Template GetTemplate(int startingOffset) { if (Templates.ContainsKey(startingOffset)) { return(Templates[startingOffset]); } var index = startingOffset; //verify we actually have a template sitting here if (ChunkBytes[index] != 0x0C) { //if the template list is fubar, it may still be ok! if (ChunkBytes[index - 10] != 0x0C) { return(null); } //in some cases the $(*&*&$#&*$ template offset list is full of garbage, so this is a fallback { index = startingOffset - 10; } } index += 1; //go past op code var unusedVersion = ChunkBytes[index]; index += 1; var templateId = BitConverter.ToInt32(ChunkBytes, index); index += 4; var templateOffset = BitConverter.ToInt32(ChunkBytes, index); index += 4; if (templateOffset == 0x0) { return(null); } var nextTemplateOffset = BitConverter.ToInt32(ChunkBytes, index); index += 4; var gb = new byte[16]; Buffer.BlockCopy(ChunkBytes, index, gb, 0, 16); index += 16; var g = new Guid(gb); var length = BitConverter.ToInt32(ChunkBytes, index); index += 4; var templateBytes = new byte[length]; Buffer.BlockCopy(ChunkBytes, index, templateBytes, 0, length); var br = new BinaryReader(new MemoryStream(templateBytes)); var l = LogManager.GetLogger("T"); l.Trace( $"\r\n-------------- NEW TEMPLATE at 0x{AbsoluteOffset + templateOffset - 10:X} ID: 0x{templateId:X} templateOffset: 0x{templateOffset:X} ---------------------"); //the offset + 18 gets us to the start of the actual template (0x0f 0x01, etc) return(new Template(templateId, templateOffset + 0x18, g, br, nextTemplateOffset, AbsoluteOffset + templateOffset, this)); }
/// <summary> /// /// </summary> /// <param name="text"></param> /// <returns>true if the text is in either the images dictionary or templates dictionary</returns> public bool ImagesContainKey(string text) { return(Images.ContainsKey(text) || Templates.ContainsKey(text)); }
public async Task <string> ParseTemplate(string template, IEntityStore entityStore, APEntity entity, Registers regs = null) { if (regs == null) { regs = new Registers(); } if (!Templates.ContainsKey(template)) { throw new InvalidOperationException($"Template {template} does not exist!"); } var templ = Templates[template]; var builder = new StringBuilder(); var end = ""; for (int i = 0; i < templ.Count; i++) { var item = templ[i]; switch (item.Type) { case "wrap": builder.Append($"<{item.Data} data-id=\"{entity.Id}\" data-template=\"{template}\">"); end = $"</{item.Data.Split(' ')[0]}>"; break; case "text": builder.Append(item.Data); break; case "if": case "while": if (!await _parseCondition(entity, entityStore, item.Data.Split(new[] { ' ' }, 2)[1], regs)) { i = item.Offset - 1; } break; case "jump": i = item.Offset - 1; break; case "end": var begin = templ[item.Offset]; if (begin.Type == "while") { i = item.Offset - 1; } break; case "command": if (item.Data.Contains("%")) { builder.Append("<span>"); } builder.Append(await _parseCommand(entity, entityStore, item.Data, regs) ?? ""); if (item.Data.Contains("%")) { builder.Append("</span>"); } break; } } builder.Append(end); return(builder.ToString()); }
public static void Generate(Booking booking, DateTime date) { if (string.IsNullOrEmpty(booking.User.Email)) { return; } hapConfig config = hapConfig.Current; StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); DateTime startDate = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(booking.Lesson).StartTime.Hour, config.BookingSystem.Lessons.Get(booking.Lesson).StartTime.Minute, 0); DateTime endDate = new DateTime(date.Year, date.Month, date.Day, config.BookingSystem.Lessons.Get(booking.Lesson).EndTime.Hour, config.BookingSystem.Lessons.Get(booking.Lesson).EndTime.Minute, 0); string location = ""; Resource resource = config.BookingSystem.Resources[booking.Room]; Templates t = new Templates(); Template template = t["general"]; if (t.ContainsKey(resource.Name)) { template = t[resource.Name]; } string ltcount = ""; if (resource.Type == ResourceType.Room) { location = booking.Room; } else if (resource.Type == ResourceType.Laptops) { location = booking.LTRoom; ltcount = booking.Count.ToString(); } else if (resource.Type == ResourceType.Equipment) { location = booking.EquipRoom; } string summary = string.Format(template.Subject, booking.Username, booking.User.DisplayName, booking.Room, booking.Name, booking.Date.ToShortDateString(), booking.Day, booking.Lesson, location, ltcount); string description = string.Format(template.Content, booking.Username, booking.User.DisplayName, booking.Room, booking.Name, booking.Date.ToShortDateString(), booking.Day, booking.Lesson, location, ltcount); sb.AppendLine("BEGIN:VCALENDAR"); sb.AppendLine("VERSION:2.0"); sb.AppendLine("PRODID:-//chsit/CalendarAppointment"); sb.AppendLine("CALSCALE:GREGORIAN"); sb.AppendLine("METHOD:REQUEST"); sb.AppendLine("BEGIN:VEVENT"); sb.AppendLine("DTSTART:" + startDate.ToUniversalTime().ToString(DateFormat)); sb.AppendLine("DTEND:" + endDate.ToUniversalTime().ToString(DateFormat)); sb.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;CN=" + booking.User.DisplayName + ":MAILTO:" + booking.User.Email); sb.AppendLine("ORGANIZER;CN=" + booking.User.DisplayName + ":MAILTO:" + booking.User.Email); sb.AppendLine("LOCATION:" + location); sb.AppendLine("UID:" + booking.uid); sb.AppendLine("DTSTAMP:" + DateTime.Now.ToString(DateFormat)); sb.AppendLine("SUMMARY:" + summary); sb.AppendLine("DESCRIPTION:" + description); sb.AppendLine("BEGIN:VALARM"); sb.AppendLine("ACTION:DISPLAY"); sb.AppendLine("DESCRIPTION:" + description); sb.AppendLine("TRIGGER:-PT5M"); sb.AppendLine("END:VALARM"); sb.AppendLine("END:VEVENT"); sb.AppendLine("END:VCALENDAR"); FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("~/App_Data/ITBooking.ics")); if (file.Exists) { file.Delete(); } StreamWriter sr = file.CreateText(); sr.Write(sb.ToString()); sr.Flush(); sr.Close(); sr.Dispose(); MailMessage mes = new MailMessage(); IFormatProvider culture = new CultureInfo("en-gb"); mes.Subject = summary; mes.From = mes.Sender = new MailAddress(config.SMTP.FromEmail, config.SMTP.FromUser); mes.ReplyToList.Add(mes.From); mes.To.Add(new MailAddress(booking.User.Email, booking.User.DisplayName)); mes.Body = description; AlternateView av = AlternateView.CreateAlternateViewFromString(sb.ToString(), new ContentType("text/calendar; method=REQUEST; name=ITBooking.ics")); av.TransferEncoding = TransferEncoding.SevenBit; mes.AlternateViews.Add(av); //mes.Attachments.Add(new Attachment(file.FullName, "text/calendar; method=REQUEST; name=ITBooking.ics")); SmtpClient client = new SmtpClient(config.SMTP.Server); if (!string.IsNullOrEmpty(config.SMTP.User)) { client.Credentials = new NetworkCredential(config.SMTP.User, config.SMTP.Password); } client.EnableSsl = config.SMTP.SSL; client.Port = config.SMTP.Port; client.Send(mes); }