protected override void Execute(CodeActivityContext context) { Application app = new Application(); app.ActiveWindow(); Outlook.MailItem mail; if (!(TemplatePath.Get(context).Contains(".oft") || TemplatePath.Get(context).Contains(".msg"))) { throw new System.Exception("Invalid template format, please use a '.oft' or '.msg' template."); } mail = TemplatePath.Get(context) != ""?(app.CreateItemFromTemplate(TemplatePath.Get(context).Contains(":\\") ? TemplatePath.Get(context) : System.IO.Directory.GetCurrentDirectory() + '\\' + TemplatePath.Get(context)) as Outlook.MailItem):new MailItem(); mail.Subject = String.IsNullOrEmpty(Subject.Get(context))?(String.IsNullOrEmpty(mail.Subject)?"Untitled":mail.Subject):Subject.Get(context); mail.To = String.IsNullOrEmpty(To.Get(context))?mail.To:To.Get(context); mail.CC = String.IsNullOrEmpty(Cc.Get(context))?mail.CC:Cc.Get(context); mail.BCC = String.IsNullOrEmpty(Bcc.Get(context))?mail.BCC:Bcc.Get(context); if (String.IsNullOrEmpty(mail.To) && String.IsNullOrEmpty(mail.CC) && String.IsNullOrEmpty(mail.BCC)) { throw new System.Exception("Error, there is no recepients specified"); } mail.HTMLBody = mail.HTMLBody.Replace("{message}", Body.Get(context)); mail.HTMLBody = mail.HTMLBody.Replace("{table}", DT.Get(context) != null?(DT.Get(context).Rows.Count > 0?GetHTMLTable(DT.Get(context)):""):""); mail.Send(); app.GetNamespace("MAPI").SendAndReceive(true); var releaseResult = Marshal.ReleaseComObject(app); }
///-------------------------------------------------------------------------------- /// <summary>This method determines whether or not any metadata is /// different between the input instance and the current instance.</summary> /// /// <param name="inputSpecificationSource">The specificationsource to compare metadata.</param> ///-------------------------------------------------------------------------------- public bool IsIdenticalMetadata(SpecificationSource inputSpecificationSource) { if (SolutionID.GetGuid() != inputSpecificationSource.SolutionID.GetGuid()) { return(false); } if (TemplatePath.GetString() != inputSpecificationSource.TemplatePath.GetString()) { return(false); } if (Order.GetInt() != inputSpecificationSource.Order.GetInt()) { return(false); } if (IsAutoUpdated.GetBool() != inputSpecificationSource.IsAutoUpdated.GetBool()) { return(false); } if (Description.GetString() != inputSpecificationSource.Description.GetString()) { return(false); } #region protected #endregion protected return(true); }
/// <summary> /// Transforms a text template that is specified in the TemplatePath property by calling the Visual Studio STextTemplatingService. /// </summary> /// <param name="context">The state of the current activity.</param> protected override void Execute(NativeActivityContext context) { // inject the template path at runtime if an explicit one doesn't exist. if (TemplatePath.Get(context) == null) { var symbolResolver = context.GetExtension <SymbolResolver>(); var edmParameterBag = symbolResolver[typeof(EdmParameterBag).Name] as EdmParameterBag; var ddlTemplatePath = edmParameterBag.GetParameter <string>(EdmParameterBag.ParameterName.DDLTemplatePath); if (String.IsNullOrEmpty(ddlTemplatePath)) { // TemplatePath must either be specified at design-time in the workflow file or at runtime, passed in through EdmParameterBag. throw new ArgumentException( String.Format(CultureInfo.CurrentCulture, Resources.DatabaseCreation_NoDDLTemplatePathSpecified, DisplayName)); } TemplatePath.Set(context, ddlTemplatePath); } base.Execute(context); Debug.Assert(!String.IsNullOrEmpty(TemplateOutput), "DDL returned from SsdlToDdl template is null or empty..."); if (TemplateOutput == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorTemplateOutputNotSet, DisplayName)); } DdlOutput.Set(context, TemplateOutput); }
protected override void Execute(CodeActivityContext context) { String TO, CC, BCC, SUBJECT, BODY; if (TemplatePath.Get(context).Contains(".eml")) { Message emlMessage = ReadMessage(TemplatePath.Get(context).Contains(":\\") ? TemplatePath.Get(context) : System.IO.Directory.GetCurrentDirectory() + '\\' + TemplatePath.Get(context)); TO = emlMessage.To; CC = emlMessage.CC; BCC = emlMessage.BCC; SUBJECT = emlMessage.Subject; BODY = String.IsNullOrEmpty(emlMessage.HTMLBody)?emlMessage.TextBody:emlMessage.HTMLBody; } else if (TemplatePath.Get(context).Contains(".oft") || TemplatePath.Get(context).Contains(".msg")) { try { Outlook.Application app = new Outlook.Application(); Outlook.MailItem template = app.CreateItemFromTemplate(TemplatePath.Get(context).Contains(":\\") ? TemplatePath.Get(context) : System.IO.Directory.GetCurrentDirectory() + '\\' + TemplatePath.Get(context)) as Outlook.MailItem; TO = template.To; CC = template.CC; BCC = template.BCC; SUBJECT = template.Subject; BODY = String.IsNullOrEmpty(template.HTMLBody) ? template.Body : template.HTMLBody; } catch { throw new System.Exception("Error, .oft and .msg files can only be read if you have Outlook installed, try using a .eml as a template"); } } else { throw new System.Exception("Invalid template format, please use a '.oft', '.msg', or '.eml' template."); } SUBJECT = String.IsNullOrEmpty(Subject.Get(context)) ? (String.IsNullOrEmpty(SUBJECT) ? "Untitled" : SUBJECT) : Subject.Get(context); TO = String.IsNullOrEmpty(To.Get(context)) ? TO : To.Get(context); CC = String.IsNullOrEmpty(Cc.Get(context)) ? CC : Cc.Get(context); BCC = String.IsNullOrEmpty(Bcc.Get(context)) ? BCC : Bcc.Get(context); BODY = BODY.Replace("{message}", String.IsNullOrEmpty(Body.Get(context))?"":Body.Get(context)); BODY = BODY.Replace("{table}", DT.Get(context) != null ? (DT.Get(context).Rows.Count > 0 ? GetHTMLTable(DT.Get(context)) : "") : ""); MailMessage mail = new MailMessage(From.Get(context), TO, SUBJECT, BODY); mail.Bcc.Add(BCC); mail.IsBodyHtml = true; mail.CC.Add(CC); SmtpClient client = new SmtpClient { Port = Port.Get(context), DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, EnableSsl = EnableSSL, Host = Server.Get(context), Credentials = new System.Net.NetworkCredential(Email.Get(context), Password.Get(context)), Timeout = 30000 }; client.Send(mail); }
/// <summary> /// 附加文件目录 /// </summary> public void AttachFiles(string basePath) { foreach (KeyValuePair <string, string> item in Attachs) { string source = TemplatePath.Remove(TemplatePath.LastIndexOf(@"\")) + @"\" + item.Key; string target = basePath.EndsWith(@"\") ? basePath : (basePath + @"\") + item.Value; IOHelper.CopyDir(source, target); } }
protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken, Application client) { List <string> inputs = Attachments.Select(x => x.Get(context)).ToList(); var app = new Application(TemplatePath.Get(context), Subject?.Get(context), To?.Get(context), Cc?.Get(context), Bcc?.Get(context), Body?.Get(context), From?.Get(context), Port.Get(context), DT?.Get(context), EnableSSL, Server.Get(context), Email.Get(context), Password.Get(context), inputs); await Task.Run(() => app.SendMail()); return(f => { }); }
protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken, Application client) { List <string> inputs = Attachments.Select(x => x.Get(context)).ToList(); if (!(TemplatePath.Get(context).Contains(".oft") || TemplatePath.Get(context).Contains(".msg"))) { throw new System.Exception("Invalid template format, please use a '.oft' or '.msg' template."); } Application app = new Application(); app.SendOutlook(TemplatePath.Get(context), Subject.Get(context), To.Get(context), Cc.Get(context), Bcc.Get(context), Body.Get(context), DT.Get(context), inputs); return(ctx => { }); }
private void LoadTask(FolderCleanerConfigTask task) { try { _isLoading = true; _currentTask = task; // clear fields lblTaskName.Text = ""; pathSource.Text = ""; txtFilter.Text = ""; foreach (var ctl in pnlDestinations.Controls.Cast <Control>().ToArray()) { ctl.Dispose(); } if (_currentTask == null) { return; } lblTaskName.Text = _currentTask.Name; pathSource.Text = _currentTask.Source.Path; txtFilter.Text = _currentTask.Source.Filter; SourceUpdated(); foreach (var dest in _currentTask.Destination) { TemplatePath dstPath = new TemplatePath(dest); dstPath.Changed += (s, e) => SetDirty(); pnlDestinations.Controls.Add(dstPath); dstPath.Dock = DockStyle.Top; } } catch (Exception ex) { ErrorHandler.Handle(ex, "Error while loading task."); } finally { _isLoading = false; } }
protected override void Execute(CodeActivityContext context) { var templateString = TemplateString.Get(context); var templatePath = TemplatePath.Get(context); var obj = InputObject.Get(context); var stubble = new StubbleBuilder().Build(); string output; if (!string.IsNullOrEmpty(templateString)) { output = stubble.Render(templateString, obj); } else { using (StreamReader streamReader = new StreamReader(templatePath, Encoding.UTF8)) { output = stubble.Render(streamReader.ReadToEnd(), obj); } } Output.Set(context, output); }
/// <summary> /// 实例化控件 /// </summary> /// <param name="ctl"></param> /// <param name="templateHtml"></param> /// <param name="dic"></param> /// <returns></returns> private Control InstanceControl(Control ctl, string templateHtml, Dictionary <string, templetaInfo> dic) { if (dic != null && dic.Count != 0) { foreach (var item in dic) { //System.Diagnostics.Stopwatch swtime = new System.Diagnostics.Stopwatch(); //swtime.Start(); #region 处理过程 try { //LoadControl(LoadControl(item.Key).GetType(), item.Value.Parameter); Type t = LoadControl(item.Key).GetType(); object instance = t.Assembly.CreateInstance(t.FullName); foreach (var field in item.Value.Parameter) //遍历字段赋值 { FieldInfo fieldinfo = t.GetField(field.Key, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.SetField); //取得字段信息 if (fieldinfo != null) { object c = Convert.ChangeType(field.Value, fieldinfo.FieldType); //动态转换类型 fieldinfo.SetValue(instance, c); //赋值 } } } catch (Exception ex) { item.Value.Error = ex.Message; //错误消息 ErrorDic.Add(item.Key, item.Value); //添加错误部件字典 We7.Framework.LogHelper.WriteLog(this.GetType(), ex); } #endregion //swtime.Stop(); //We7.Framework.LogHelper.WriteFileLog("showpageTimeTest.txt", "部件加载时间测试", "部件路径:" + item.Key + "\n部件运行加载时间:" + swtime.ElapsedMilliseconds.ToString() + "毫秒"); } if (ErrorDic == null || ErrorDic.Count == 0) //如果没有发生错误,则走正常流程 { ctl = LoadControl(TemplatePath); } else //错误处理流程 { string ErroAscx = string.Empty; foreach (var item in ErrorDic) { ErroAscx = Regex.Replace(templateHtml, ContentPattentn.Replace("{0}", item.Value.Wew).Replace("{1}", item.Value.Tagname).Replace("{2}", item.Value.Src), "<span style='color:Red' title='" + item.Value.Error + "'>此部件发生错误</span>"); //显示错误信息 ErroAscx = Regex.Replace(ErroAscx, RegisterPattetn.Replace("{0}", item.Value.Src).Replace("{1}", item.Value.Tagname).Replace("{2}", item.Value.Wew), string.Empty); //去掉错误部件注册信息 } string errorPath = TemplatePath.Insert(TemplatePath.LastIndexOf('.'), ".error");; //错误模板副本路径 if (AppCtx.Cache.RetrieveObject <string>(errorPath) != null && AppCtx.Cache.RetrieveObject <string>(errorPath).Equals(ErroAscx)) //如果有缓存 { ctl = LoadControl(errorPath); } else { FileHelper.WriteFileEx(Context.Server.MapPath(errorPath), ErroAscx, false); //写错误模板副本 AppCtx.Cache.AddObjectWithFileChange(errorPath, ErroAscx, new string[] { Context.Server.MapPath(errorPath) }); //添加缓存 ctl = LoadControl(errorPath); } } } return(ctl); }
/// <summary> /// 设置模板类型 /// </summary> public void SetTemplateType() { this.TemplateType = TemplatePath.Contains("CodeFirst") ? TemplateType.CodeFirst : TemplatePath.Contains("DbFirst") ? TemplateType.DbFirst : TemplatePath.Contains("Global") ? TemplateType.Global : TemplateType.UnKnow; }
protected override void OnInit(EventArgs e) { try { if (String.IsNullOrEmpty(ScriptName)) { _exception = new InvalidEnumArgumentException("Property ScripName is empty!"); } else if (String.IsNullOrEmpty(ScriptClass)) { _exception = new InvalidEnumArgumentException("Property ScripClass is empty!"); } if (_exception != null) { return; } Guid hiveId = String.IsNullOrEmpty(ScriptHiveId) ? Guid.Empty : new Guid(ScriptHiveId); //IronRuntime ironRuntime = IronRuntime.GetIronRuntime(SPContext.Current.Site, hiveId); IronRuntime ironRuntime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site); engine = ironRuntime.GetEngineByExtension(Path.GetExtension(ScriptName)); if (engine != null) { ctrl = engine.CreateDynamicInstance(ScriptClass, ScriptName) as Control; var dynamicControl = ctrl as IIronControl; if (dynamicControl != null) { dynamicControl.WebPart = null; dynamicControl.Data = null; dynamicControl.Config = Config; } if (Template != null) { Template.InstantiateIn(ctrl); } else { if (!String.IsNullOrEmpty(TemplatePath)) { var path = TemplatePath.Replace("~site", SPContext.Current.Site.ServerRelativeUrl) .Replace("~web", SPContext.Current.Web.ServerRelativeUrl) .Replace("~hiveSite", engine.IronRuntime.IronHive.Site.ServerRelativeUrl) .Replace("~hiveWeb", engine.IronRuntime.IronHive.Web.ServerRelativeUrl) .Replace("~hiveFolder", engine.IronRuntime.IronHive.Folder.ServerRelativeUrl); Template = this.LoadTemplate(path); Template.InstantiateIn(ctrl); } } this.Controls.Add(ctrl); } } catch (Exception ex) { IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[IronCategoryDiagnosticsId.Controls], TraceSeverity.Unexpected, String.Format("Error: {0}; Stack: {1}", ex.Message, ex.StackTrace)); _exception = ex; } base.OnInit(e); }
/// <summary> /// 重写Render方法 /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { if (!string.IsNullOrEmpty(Request["Createhtml"]) && Request["Createhtml"] == "1") { StringWriter strWriter = new StringWriter(); HtmlTextWriter tempWriter = new HtmlTextWriter(strWriter); try { base.Render(tempWriter); } catch (Exception ex) { strWriter.Write(""); }; //读取原始模板内容 HtmlDocument doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = true; doc.OptionCheckSyntax = true; doc.OptionOutputOriginalCase = true; try { doc.Load(Server.MapPath(TemplatePath), Encoding.UTF8); } catch { throw new Exception("格式化HTML错误"); } string strContent = doc.DocumentNode.InnerText; //提取控件注册信息 string pat = @"<%@[^>]*>"; Regex reg = new Regex(pat); MatchCollection m = reg.Matches(strContent); StringBuilder sb = new StringBuilder(); for (int i = 0; i < m.Count; i++) { string temp = m[i].Value; if (!m[i].ToString().Contains("Src=\"/")) { temp = m[i].Value.Replace("Src=\"", "Src=\"" + TemplatePath.Remove(TemplatePath.LastIndexOf("/")) + "/"); } sb.Append(temp + "\r\n"); } //给生成后模板添加控件注册信息 string content = strWriter.ToString(); string pat1 = @"<html[^>]*>"; string RegAndHtml = sb.ToString() + "\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"; content = Regex.Replace(content, pat1, RegAndHtml, RegexOptions.IgnoreCase); content = content.Replace("<head>", "<head runat=\"server\">"); writer.Write(content); string channelUrl = ChannelHelper.GetChannelUrlFromUrl(Context.Request.RawUrl, Context.Request.ApplicationPath); string fileName = ""; if (string.IsNullOrEmpty(ColumnMode)) { fileName = "index.ascx"; } else { fileName = ColumnMode + ".ascx"; } string resultPath = Server.MapPath(TemplatePath.Remove(TemplatePath.LastIndexOf("/")) + "/HtmlTemplate/" + channelUrl + fileName); FileHelper.WriteFileEx(resultPath, content, false); } else { base.Render(writer); } }
public override void OnExecute(ICommandContext context, CommandConfig config, CommandResult result) { var viewResult = result as MailResult; var viewModel = new RazorContentViewModel { Parameters = Parameters.CreateDictionary(context) }; try { if (string.IsNullOrEmpty(TemplatePath)) { throw LangTexts.Current.GetLangText("9013", "模板没有设置").CreateException(); } if (TemplatePath.Contains("{@")) { viewResult.Content = TemplatePath.ReplaceContextParameters(context, viewModel); } else { var template = ContentLib.Current.FolderRoot.GetFile(TemplatePath); if (template == null || (!(template is RazorTemplate))) { throw LangTexts.Current.GetFormatLangText("9011", "模板[{0}]加载失败", TemplatePath).CreateException(); } var razorTemplate = template as RazorTemplate; viewResult.Content = razorTemplate.Render(viewModel); } var title = Title.ReplaceContextParameters(context, viewModel); var sendTo = SendTo.ReplaceContextParameters(context, viewModel); var server = GetMailServer(); if (string.IsNullOrEmpty(sendTo)) { throw new Exception("邮件接收者不能为空"); } viewResult.Title = title; viewResult.SendTo = sendTo; viewResult.Encoding = Encoding; //在Action配置中增加可否为订阅事件的标识,如果有,则在该Action中增加一个MailAction,在该成功执行之后再执行 if (sendTo.IndexOf(',') > 0 && SendOneByOne) { foreach (var to in sendTo.Split(',')) { server.SendMail(title, viewResult.Content, to); } } else if (!string.IsNullOrEmpty(sendTo)) { server.SendMail(title, viewResult.Content, sendTo); } } catch { throw; } result.End(NextCommand); context.Execute(NextCommand); }