示例#1
0
        protected static int SendSystemNotification(string settingsName, ContractAccount recipient, Hashtable items,
            string htmlKeyName, string textKeyName)
        {
            // load e-mail template
            StoreSettings settings = StorehouseController.GetStoreSettings(ES.SecurityContext.User.UserId,
                settingsName);
            //
            bool htmlMail = (recipient[ContractAccount.MAIL_FORMAT] == "HTML");
            string email = recipient[ContractAccount.EMAIL];
            //
            string messageBody = htmlMail ? settings[htmlKeyName] : settings[textKeyName];

            Template tmp = new Template(messageBody);

            if (items != null)
            {
                foreach (string key in items.Keys)
                    tmp[key] = items[key];
            }

            StringWriter writer = new StringWriter();
            try
            {
                tmp.Evaluate(writer);
            }
            catch (ParserException ex)
            {
                writer.WriteLine(String.Format("Error in template (Line {0}, Column {1}): {2}",
                    ex.Line, ex.Column, ex.Message));
            }
            // evaluate message body
            messageBody = writer.ToString();

            return ES.MailHelper.SendMessage(settings["From"], email, settings["CC"], settings["Subject"],
                messageBody, htmlMail);
        }
		public static BytesResult GetWebDeployPublishingProfile(int siteItemId)
		{
			var result = new BytesResult();
			try
			{
				TaskManager.StartTask(LOG_SOURCE_WEB, "GetWebDeployPublishingProfile");
				TaskManager.WriteParameter("SiteItemId", siteItemId);

				// load site item
				WebSite item = (WebSite)PackageController.GetPackageItem(siteItemId);
				//
				var siteItem = GetWebSite(siteItemId);

				//
				if (item == null)
				{
					TaskManager.WriteWarning("Web site not found");
					return result;
				}

				//
				int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
				if (accountCheck < 0)
				{
					TaskManager.WriteWarning("Current user is either demo or inactive");
					return result;
				}

				// check package
				int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
				if (packageCheck < 0)
				{
					TaskManager.WriteWarning("Current user is either not allowed to access the package or the package inactive");
					return result;
				}

				//
				string accountName = item.WebDeployPublishingAccount;
				//
				if (String.IsNullOrEmpty(accountName))
				{
					TaskManager.WriteWarning("Web Deploy Publishing Access account name is either not set or empty");
					return result;
				}
				//
				var packageInfo = PackageController.GetPackage(item.PackageId);
				//
				var userInfo = UserController.GetUser(packageInfo.UserId);
				//
				var items = new Hashtable()
				{
					{ "WebSite", siteItem },
					{ "User",  userInfo },
				};

				// Retrieve service item ids from the profile
				var serviceItemIds = Array.ConvertAll<string, int>(
					item.WebDeploySitePublishingProfile.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries),
					(string x) => { return Convert.ToInt32(x.Trim()); });

				//
				foreach (var serviceItemId in serviceItemIds)
				{
					var packageItem = PackageController.GetPackageItem(serviceItemId);
					// Handle SQL databases
					if (packageItem is SqlDatabase)
					{
						var dbItemKey = packageItem.GroupName.StartsWith("MsSQL") ? "MsSqlDatabase" : "MySqlDatabase";
						var dbServerKeyExt = packageItem.GroupName.StartsWith("MsSQL") ? "MsSqlServerExternalAddress" : "MySqlServerExternalAddress";
						var dbServerKeyInt = packageItem.GroupName.StartsWith("MsSQL") ? "MsSqlServerInternalAddress" : "MySqlServerInternalAddress";
						//
						items.Add(dbItemKey, DatabaseServerController.GetSqlDatabase(serviceItemId));
						// Retrieve settings
						var sqlSettings = ServerController.GetServiceSettings(packageItem.ServiceId);
						items[dbServerKeyExt] = sqlSettings["ExternalAddress"];
						items[dbServerKeyInt] = sqlSettings["InternalAddress"]; 
					}
					else if (packageItem is SqlUser)
					{
						var itemKey = packageItem.GroupName.StartsWith("MsSQL") ? "MsSqlUser" : "MySqlUser";
						//
						items.Add(itemKey, DatabaseServerController.GetSqlUser(serviceItemId));
					}
					else if (packageItem is FtpAccount)
					{
						//
						items.Add("FtpAccount", FtpServerController.GetFtpAccount(serviceItemId));
						// Get FTP DNS records
						List<GlobalDnsRecord> ftpRecords = ServerController.GetDnsRecordsByService(packageItem.ServiceId);
						if (ftpRecords.Count > 0)
						{
							GlobalDnsRecord ftpRecord = ftpRecords[0];
							string ftpIp = ftpRecord.ExternalIP;
							if (String.IsNullOrEmpty(ftpIp))
								ftpIp = ftpRecord.RecordData;
							// Assign FTP service address variable
							items["FtpServiceAddress"] = ftpIp;
						}
					}
				}

				// Decrypt publishing password & copy related settings
				siteItem.WebDeployPublishingPassword = CryptoUtils.Decrypt(item.WebDeployPublishingPassword);
				siteItem.WebDeployPublishingAccount = item.WebDeployPublishingAccount;
				siteItem.WebDeploySitePublishingEnabled = item.WebDeploySitePublishingEnabled;
				siteItem.WebDeploySitePublishingProfile = item.WebDeploySitePublishingProfile;
				
				// Retrieve publishing profile template from the Web Policy settings
				var webPolicy = UserController.GetUserSettings(packageInfo.UserId, UserSettings.WEB_POLICY);
				// Instantiate template, it's content and related items and then evaluate it
				var template = new Template(webPolicy["PublishingProfile"]);
				// Receive bytes for the evaluated template
				result.Value = Encoding.UTF8.GetBytes(template.Evaluate(items));
				//
				result.IsSuccess = true;
			}
			catch (Exception ex)
			{
				TaskManager.WriteError(ex);
				//
				result.IsSuccess = false;
			}
			finally
			{
				TaskManager.CompleteTask();
			}
			//
			return result;
		}
        public static string EvaluateTemplate(string template, Hashtable items)
        {
            StringWriter writer = new StringWriter();

            try
            {
                Template tmp = new Template(template);

                if (items != null)
                {
                    foreach (string key in items.Keys)
                        tmp[key] = items[key];
                }

                tmp.Evaluate(writer);
            }
            catch (ParserException ex)
            {
                return String.Format("Error in template (Line {0}, Column {1}): {2}",
                    ex.Line, ex.Column, ex.Message);
            }
            return writer.ToString();
        }
        internal static RoutineResult SetNotificationTemplate(int userId, string settingsName, string fromEmail, string ccEmail, string subject,
            string htmlBody, string textBody)
        {
            //
            RoutineResult result = new RoutineResult();
            //
            SecurityResult sec_result = CheckAccountNotDemoAndActive();
            //
            if (!sec_result.Success)
            {
                result.Succeed = false;
                result.ResultCode = sec_result.ResultCode;
                //
                return result;
            }

            // 1. Check notification subject correctness
            //
            try
            {
                Template tm = new Template(subject);
                tm.CheckSyntax();
            }
            catch (ParserException parserEx)
            {
                result.Succeed = false;
                //
                result.ResultCode = EcommerceErrorCodes.ERROR_NTFY_SUBJECT_TEMPLATE;
                //
                result.Message = "Line: " + parserEx.Line + "; Column: " + parserEx.Column + ";";
                //
                return result;
            }

            // 2. Check notification HTML body correctness
            try
            {
                Template tm = new Template(htmlBody);
                tm.CheckSyntax();
            }
            catch (ParserException parserEx)
            {
                result.Succeed = false;
                //
                result.ResultCode = EcommerceErrorCodes.ERROR_NTFY_HTML_TEMPLATE;
                //
                result.Message = "Line: " + parserEx.Line + "; Column: " + parserEx.Column + ";";
                //
                return result;
            }

            // 3. Check notification Plain Text body correctness
            try
            {
                Template tm = new Template(textBody);
                tm.CheckSyntax();
            }
            catch (ParserException parserEx)
            {
                result.Succeed = false;
                //
                result.ResultCode = EcommerceErrorCodes.ERROR_NTFY_TEXT_TEMPLATE;
                //
                result.Message = "Line: " + parserEx.Line + "; Column: " + parserEx.Column + ";";
                //
                return result;
            }

            //
            StoreSettings settings = new StoreSettings();
            //
            settings["From"] = fromEmail;
            //
            settings["CC"] = ccEmail;
            //
            settings["Subject"] = subject;
            //
            settings["HtmlBody"] = htmlBody;
            //
            settings["TextBody"] = textBody;

            //
            result.ResultCode = SetStoreSettings(userId, settingsName, settings);
            //
            if (result.ResultCode < 0)
                result.Succeed = false;
            else
                result.Succeed = true;
            //
            return result;
        }
示例#5
0
        private static void TestTemplates(string data)
        {
            Template tmp1 = new Template(data);
            tmp1["a"] = 2;
            tmp1["b"] = 5;
            tmp1["d"] = 2;
            tmp1["str"] = "string 111";

            tmp1["str1"] = "Hello, World";
            tmp1["str2"] = "";
            tmp1["str3"] = null;

            tmp1["arr"] = new string[] { "s1", "s2", "s3" };
            tmp1["customer"] = new Customer()
            {
                OrderNumbers = new string[] { "order-1", "order-2", "order-3" }
            };
            tmp1["integersDict"] = new Dictionary<int, string>()
            {
                {101, "str1"},
                {102, "str2"},
                {103, "str3"}
            };

            tmp1["customersDict"] = new Dictionary<string, Customer>()
            {
                {"customer1", new Customer()
                    {
                        Name = "John Smith",
                        OrderNumbers = new string[] { "o-1", "o-2" }
                    } },
                {"customer2", new Customer()
                    {
                        Name = "Jack Brown",
                        OrderNumbers = new string[] { "order-1", "order-2", "order-3", "order-4" }
                    }}
            };

            tmp1["customersList"] = new List<Customer>()
            {
                new Customer()
                    {
                        Name = "John Smith",
                        OrderNumbers = new string[] { "o-1", "o-2" }
                    },
                new Customer()
                    {
                        Name = "Jack Brown",
                        OrderNumbers = new string[] { "o-1", "o-2" }
                    }
            };


            // check syntax
            //tmp1.CheckSyntax();

            string result = tmp1.Evaluate();

            Console.Write(result);

            Console.ReadKey();
        }
        internal static string GetCustomerInvoiceFormattedInternally(Contract contract, int invoiceId, ContractAccount accountSettings, string cultureName)
        {
            //
            Invoice invoiceInfo = GetCustomerInvoiceInternally(invoiceId);
            // impersonate
            ES.SecurityContext.SetThreadPrincipal(contract.ResellerId);
            // load settings
            StoreSettings settings = StorehouseController.GetStoreSettings(contract.ResellerId, StoreSettings.NEW_INVOICE);
            //
            string templateBody = settings["HtmlBody"];
            //
            Taxation invoiceTax = StorehouseController.GetTaxation(contract.ResellerId, invoiceInfo.TaxationId);
            //
            List<InvoiceItem> invoiceLines = GetCustomerInvoiceItems(invoiceId);
            Dictionary<int, Service> invoiceServices = ServiceController.GetServicesDictionary(invoiceLines);
            //
            Template tm = new Template(templateBody);
            tm["Invoice"] = invoiceInfo;
            tm["InvoiceLines"] = invoiceLines;
            tm["InvoiceServices"] = invoiceServices;
            tm["Customer"] = accountSettings;
            tm["Tax"] = invoiceTax;

            StringWriter writer = new StringWriter();
            try
            {
                // Preserve an original thread culture
                CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
                //
                if (!String.IsNullOrEmpty(cultureName))
                {
                    try
                    {
                        CultureInfo formattingCulture = new CultureInfo(cultureName);
						// Empty currency symbol to supporty 3-letters ISO format 
						// hardcorded in HTML templates
						formattingCulture.NumberFormat.CurrencySymbol = String.Empty;
                        // Set formatting culture
                        Thread.CurrentThread.CurrentCulture = formattingCulture;
                    }
                    catch (Exception ex)
                    {
                        TaskManager.WriteWarning("Wrong culture name has been provided. Culture name: {0}.", cultureName);
                        TaskManager.WriteWarning(ex.StackTrace);
                        TaskManager.WriteWarning(ex.Message);
                    }
                }

                // Process template
                tm.Evaluate(writer);
                templateBody = writer.ToString();

                // Revert the original thread's culture back
                Thread.CurrentThread.CurrentCulture = originalCulture;
            }
            catch (ParserException ex)
            {
                return String.Format("Error in template (Line {0}, Column {1}): {2}",
                    ex.Line, ex.Column, ex.Message);
            }

            return templateBody;
        }