Ejemplo n.º 1
0
        private IdentityMessage PrepareMessage(Donor donor)
        {
            if (donor == null)
            {
                return(null);
            }
            var viewBag = new DynamicViewBag();

            viewBag.AddValue("CallbackUrl", Url.Action("Activate", "Donor", new { userId = donor.Id, code = donor.GetHashCode() }, protocol: Request.Url.Scheme));

            return(new IdentityMessage
            {
                Body = RazorTemplateService.RenderTemplate("DonorActivation.cshtml", donor, viewBag),
                Subject = "Confirm email",
                Destination = donor.Email
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Compiles and executes view template.
        /// </summary>
        /// <returns>Rendered result.</returns>
        public string Execute()
        {
            using (DataContext dataContext = new DataContext(Database, razorEngine: DataContextEngine, exceptionHandler: ExceptionHandler))
            {
                if ((object)PagedViewModelDataType != null && (object)PagedViewModelHubType != null)
                {
                    dataContext.ConfigureView(PagedViewModelDataType, PagedViewModelHubType, null as string, m_viewBag);
                }

                m_viewBag.AddValue("DataContext", dataContext);
                return(m_razorEngine.RunCompile(TemplateName, ModelType, Model, m_viewBag));
            }
        }
Ejemplo n.º 3
0
        public void Write(string outputDirectory, IPokemonSaveInfo saveInfo)
        {
            AppDomain domain = null;

            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;

                domain = AppDomain.CreateDomain(
                    "PokeSiteDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted));
            }

            Directory.CreateDirectory(outputDirectory);
            string outputFile = Path.Combine(outputDirectory, "index.html");
            string template   = File.ReadAllText("Resources/template.cshtml");

            DynamicViewBag viewBag = new DynamicViewBag(new Dictionary <string, object>()
            {
                ["Title"] = Title
            });

            IEnumerable <string> cssFiles = CopyCSS(outputDirectory);

            viewBag.AddValue("CSSFiles", cssFiles.ToList());

            // Compile and run Razor template
            using (StreamWriter outputWriter = new StreamWriter(outputFile))
            {
                Engine.Razor.RunCompile(template, "test", outputWriter, saveInfo.GetType(),
                                        saveInfo, viewBag);
            }

            if (domain != null)
            {
                // RazorEngine will cleanup.
                AppDomain.Unload(domain);
            }
        }
Ejemplo n.º 4
0
        public static void SendReminder(Reminder reminder)
        {
            var dbs = new DatabaseService();
            var ads = new ActiveDirectoryService();

            // Email Server Configuration
            var fromEmailAddress     = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
            var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
            var fromEmailPassword    = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
            var smtpHost             = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            var smtpPort             = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            var toEmailAddress       = ads.GetEmail(reminder.User.Guid);
            var toEmailDisplayName   = reminder.User.FirstName + " " + reminder.User.LastName;

            // Get next meeting date
            var nextMeetingDate = dbs.GetMeeting();
            var ViewBag         = new DynamicViewBag();

            ViewBag.AddValue("NextMeeting", nextMeetingDate.GetReadable() + " " + nextMeetingDate.ToString("MMMM"));

            try
            {
                var templateService = new TemplateService();

                string      body    = templateService.Parse(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/EmailTemplates/ReminderEmail.cshtml"), reminder, ViewBag, null);
                MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(toEmailAddress, toEmailDisplayName));
                message.Subject    = "Coffee Reminder";
                message.IsBodyHtml = true;
                message.Body       = body;

                var client = new SmtpClient();
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential(fromEmailAddress, fromEmailPassword);
                client.Host      = smtpHost;
                client.EnableSsl = true;
                client.Port      = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
                client.Send(message);
            }
            catch (Exception ex)
            {
                throw (new Exception("Message failed to send to " + toEmailAddress + ".", ex));
            }
        }
Ejemplo n.º 5
0
        public static string GeneratorCode(this string tempaltePath, object viewModel, Type viewModelType, string oldCustomCode)
        {
            string result;

            try
            {
                DynamicViewBag dynamicViewBag = new DynamicViewBag();
                dynamicViewBag.AddValue("OldCustomCode", oldCustomCode);
                if (!RazorEngineEx.CreateEngineAfter)
                {
                    RazorEngineEx.CreateEngine();
                }
                string templateSource = File.ReadAllText(tempaltePath, EncodingEx.Utf8WithoutBom);
                result = Engine.Razor.RunCompile(templateSource, tempaltePath, viewModelType, viewModel, dynamicViewBag);
                result = result.Replace("&#39;", "'").Replace("&gt;", ">").Replace("&quot;", "\"").Replace("&lt;", "<").Replace("<pre>", "").Replace("</pre>", "");
            }
            catch (Exception)
            {
                throw;
            }
            return(result);
        }
Ejemplo n.º 6
0
        public string CompileTemplate <TModel>(string templateText, TModel model, IDictionary <string, string> properties = null)
        {
            var config = new TemplateServiceConfiguration
            {
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            DynamicViewBag bag = new DynamicViewBag();

            if (properties != null)
            {
                foreach (var property in properties)
                {
                    bag.AddValue(property.Key, property.Value);
                }
            }

            var service = RazorEngineService.Create(config);
            var result  = service.RunCompile(templateText, "key", typeof(TModel), model, bag);

            return(result);
        }
Ejemplo n.º 7
0
            public string GetResult([NotNull] HttpRequestMessage request, [CanBeNull] object model)
            {
                var lastWriteTimeUtc = File.GetLastWriteTimeUtc(templatePath);

                if (cachedLastWriteTimeUtc != lastWriteTimeUtc)
                {
                    lock (locker)
                    {
                        if (cachedLastWriteTimeUtc != lastWriteTimeUtc)
                        {
                            var template       = File.ReadAllText(templatePath);
                            var templateSource = new LoadedTemplateSource(template, templatePath);
                            templateKey = new NameOnlyTemplateKey(templatePath + Guid.NewGuid(), ResolveType.Global, null);
                            razor.AddTemplate(templateKey, templateSource);
                            razor.Compile(templateKey, modelType);
                            cachedLastWriteTimeUtc = lastWriteTimeUtc;
                        }
                    }
                }
                var viewBag = new DynamicViewBag();

                viewBag.AddValue("__request", request);
                return(razor.Run(templateKey, modelType, model, viewBag));
            }
Ejemplo n.º 8
0
        public void Init()
        {
            //load file setting with config in header
            RazorTemplate = FileTemplateManager.LoadFileTemplate(_filePath, _fileContent);
            //create config for razor engine
            //http://antaris.github.io/RazorEngine/
            var config = new TemplateServiceConfiguration();

            config.EncodedStringFactory = new RawStringFactory();
            config.BaseTemplateType     = typeof(CustomTemplateBase <>);
            config.TemplateManager      = new DelegateTemplateManager();
            var referenceResolver = new MyIReferenceResolver();

            referenceResolver.DllFolder = RazorTemplate.InputDllFolder;
            config.ReferenceResolver    = referenceResolver;
            _engine      = RazorEngineService.Create(config);
            _templateKey = Engine.Razor.GetKey(MyTemplateKey.MAIN_TEMPLATE);
            //setup viewbag input Folder for render partial
            _viewBag = new DynamicViewBag();
            _viewBag.AddValue("InputFolder", RazorTemplate.InputFolder);
            //check template is compile
            if (!_engine.IsTemplateCached(_templateKey, null))
            {
                //add include template file
                var includeTemplate = new StringBuilder();
                foreach (var filepath in RazorTemplate.ListImportFile)
                {
                    includeTemplate.Append(FileUtils.ReadFileContent(filepath));
                }
                var data = RazorTemplate.TemplateData;
                data            = includeTemplate.ToString() + data;
                _templateSource = new LoadedTemplateSource(data);
                _engine.AddTemplate(_templateKey, _templateSource);
                _engine.Compile(_templateKey, _modeldata.GetType());
            }
        }
Ejemplo n.º 9
0
        public void ExchangeRateSendEmail(string toEmail, string ccEmail, string ContactName, string Attachment, int OperationZoneId)
        {
            //Update Mail Status
            new ExchangeRateRepository().UpdateSendMailStatus(OperationZoneId);

            string logoImage  = AppSettings.EmailServicePath + "/Images/FrayteLogo.png";
            string trackImage = AppSettings.EmailServicePath + "/Images/ExchangeRate.png";

            List <string> ImagePath = new List <string>();

            ImagePath.Add(logoImage);
            ImagePath.Add(trackImage);

            DynamicViewBag viewBag = new DynamicViewBag();

            viewBag.AddValue("Staff", ContactName);
            viewBag.AddValue("StaffEmail", "*****@*****.**");
            viewBag.AddValue("ImageHeader", "FrayteLogo");
            viewBag.AddValue("TrackButton", "ExchangeRate");
            if (OperationZoneId == 1)
            {
                viewBag.AddValue("ExchangeRatePath", "http://app.frayte.com/");
            }
            else
            {
                viewBag.AddValue("ExchangeRatePath", "http://app.frayte.co.uk/");
            }

            string template        = File.ReadAllText(AppSettings.EmailServicePath + "/EmailTeamplate/ExchangeRate.cshtml");
            var    templateService = new TemplateService();

            var EmailBody    = templateService.Parse(template, "", viewBag, null);
            var EmailSubject = "Update Exchange Rate - FRAYTE Logistics Ltd";

            FrayteEmail.SendMail(toEmail, ccEmail, EmailSubject, EmailBody, Attachment, ImagePath, "ExchangeRate", OperationZoneId);
        }
        public void Issue26_ViewBagInitializationOutsideOfTemplate()
        {
            using (var service = new TemplateService())
            {
                const string template = "@ViewBag.TestValue";
                const string expected = "This is a test";

                DynamicViewBag viewBag = new DynamicViewBag();
                viewBag.AddValue("TestValue", "This is a test");

                string result = service.Parse(template, null, viewBag, null);

                Assert.That(result == expected, "Result does not match expected: " + result);
            }
        }
Ejemplo n.º 11
0
        private static void Main(string[] args)
        {
            bool ignoreCache = false;
            var  options     = new OptionSet {
                { "i|ignore", v => ignoreCache = true }
            };
            var folders = options.Parse(args);

            if (folders.Count == 0)
            {
                folders = new List <string> {
                    "."
                };
            }

            AnalysisCache cache;

            if (ignoreCache)
            {
                cache = new AnalysisCache();
            }
            else
            {
                cache = new AnalysisCache(Settings.RunStatsCacheFile);
            }

            var analyzer = new RunAnalyzer(cache);

            var  assembly              = Assembly.GetExecutingAssembly();
            var  pageTemplate          = "";
            bool individualRunCompiled = false;
            bool monthlyCompiled       = false;
            bool weeklyCompiled        = false;

            using (var stream = assembly.GetManifestResourceStream("GpxRunParser.Templates.IndividualRun.cshtml")) {
                using (var reader = new StreamReader(stream)) {
                    pageTemplate = reader.ReadToEnd();
                }
            }

            // Workaround for https://github.com/Antaris/RazorEngine/issues/244 - note that this is not the recommended method!
            var config = new TemplateServiceConfiguration {
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { }),
                //Debug = true
            };

            Engine.Razor = RazorEngineService.Create(config);

            var extRegexp = new Regex(@"\.gpx$", RegexOptions.IgnoreCase);

            var runs = new List <RunInfo>();

            foreach (var dirName in folders)
            {
                var gpxFiles = Directory.EnumerateFiles(dirName, Settings.FilePattern);

                foreach (var fileName in gpxFiles)
                {
                    RunStatistics runStats;
                    var           newResults     = analyzer.Analyze(fileName, out runStats);
                    var           baseFileName   = extRegexp.Replace(fileName, "");
                    var           outputFileName = baseFileName + ".html";
                    runs.Add(new RunInfo(outputFileName, runStats));

                    if (newResults)
                    {
                        var viewBag = new DynamicViewBag();
                        viewBag.AddValue("FileName", baseFileName);
                        viewBag.AddValue("HeartRateZones", Settings.HeartRateZones);
                        viewBag.AddValue("PaceBins", Settings.PaceBins);
                        viewBag.AddValue("SlowestDisplayedPace", Settings.SlowestDisplayedPace);
                        viewBag.AddValue("ExerciseTitle", Settings.ExerciseTitle);
                        viewBag.AddValue("DisplayPace", Settings.DisplayPace);
                        viewBag.AddValue("DisplaySpeed", Settings.DisplaySpeed);
                        string page;
                        if (!individualRunCompiled)
                        {
                            page = Engine.Razor.RunCompile(pageTemplate, "IndividualRun", typeof(RunStatistics), runStats, viewBag);
                            individualRunCompiled = true;
                        }
                        else
                        {
                            page = Engine.Razor.Run("IndividualRun", typeof(RunStatistics), runStats, viewBag);
                        }
                        page = MinifyPage(page, fileName);
                        using (var output = File.CreateText(outputFileName)) {
                            output.Write(page);
                        }
                    }
                }
            }

            using (var stream = assembly.GetManifestResourceStream("GpxRunParser.Templates.MonthlyStatistics.cshtml")) {
                using (var reader = new StreamReader(stream)) {
                    pageTemplate = reader.ReadToEnd();
                }
            }

            foreach (var month in analyzer.MonthlyStats.Keys)
            {
                var outputFileName = String.Format("Monthly-{0:yyyy-MM}.html", month);
                var viewBag        = new DynamicViewBag();
                viewBag.AddValue("HeartRateZones", Settings.HeartRateZones);
                viewBag.AddValue("PaceBins", Settings.PaceBins);
                viewBag.AddValue("SlowestDisplayedPace", Settings.SlowestDisplayedPace);
                viewBag.AddValue("DisplayPace", Settings.DisplayPace);
                viewBag.AddValue("DisplaySpeed", Settings.DisplaySpeed);
                string page;
                if (!monthlyCompiled)
                {
                    page            = Engine.Razor.RunCompile(pageTemplate, "MonthlyStatistics", typeof(AggregateStatistics), analyzer.MonthlyStats[month], viewBag);
                    monthlyCompiled = true;
                }
                else
                {
                    page = Engine.Razor.Run("MonthlyStatistics", typeof(AggregateStatistics), analyzer.MonthlyStats[month], viewBag);
                }
                page = MinifyPage(page, String.Format("the monthly report {0:yyyy-MM}", month));
                using (var output = File.CreateText(outputFileName)) {
                    output.Write(page);
                }
            }

            using (var stream = assembly.GetManifestResourceStream("GpxRunParser.Templates.WeeklyStatistics.cshtml")) {
                using (var reader = new StreamReader(stream)) {
                    pageTemplate = reader.ReadToEnd();
                }
            }

            foreach (var week in analyzer.WeeklyStats.Keys)
            {
                var calendar       = CultureInfo.CurrentUICulture.Calendar;
                var outputFileName = String.Format("Weekly-{0:yyyy}-{1:D2}.html",
                                                   week,
                                                   calendar.GetWeekOfYear(week, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));
                var viewBag = new DynamicViewBag();
                viewBag.AddValue("HeartRateZones", Settings.HeartRateZones);
                viewBag.AddValue("PaceBins", Settings.PaceBins);
                viewBag.AddValue("SlowestDisplayedPace", Settings.SlowestDisplayedPace);
                viewBag.AddValue("DisplayPace", Settings.DisplayPace);
                viewBag.AddValue("DisplaySpeed", Settings.DisplaySpeed);
                string page;
                if (!weeklyCompiled)
                {
                    page           = Engine.Razor.RunCompile(pageTemplate, "WeeklyStatistics", typeof(AggregateStatistics), analyzer.WeeklyStats[week], viewBag);
                    weeklyCompiled = true;
                }
                else
                {
                    page = Engine.Razor.Run("WeeklyStatistics", typeof(AggregateStatistics), analyzer.WeeklyStats[week], viewBag);
                }
                page = MinifyPage(page, String.Format("weekly report {0:D2}/{1:yyyy}",
                                                      calendar.GetWeekOfYear(week, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday), week));
                using (var output = File.CreateText(outputFileName)) {
                    output.Write(page);
                }
            }

            if (runs.Count > 0)
            {
                using (var stream = assembly.GetManifestResourceStream("GpxRunParser.Templates.Index.cshtml")) {
                    using (var reader = new StreamReader(stream)) {
                        pageTemplate = reader.ReadToEnd();
                    }
                }

                var startDate = runs.Min(r => r.StartTime);
                startDate = new DateTime(startDate.Year, startDate.Month, 1);
                var endDate = runs.Max(r => r.StartTime);
                endDate = new DateTime(endDate.Year, endDate.Month, 1).AddMonths(1).AddDays(-1);
                var viewBag = new DynamicViewBag();
                viewBag.AddValue("StartDate", startDate);
                viewBag.AddValue("EndDate", endDate);
                var indexPage = Engine.Razor.RunCompile(pageTemplate, "Index", typeof(IList <RunInfo>), runs, viewBag);
                indexPage = MinifyPage(indexPage, "the index page");
                using (var output = File.CreateText("Index.html")) {
                    output.Write(indexPage);
                }
            }

            cache.SaveCache(Settings.RunStatsCacheFile);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates template based select field based on reflected modeled table field attributes with values derived from ValueList table.
        /// </summary>
        /// <typeparam name="T">Modeled table for select field.</typeparam>
        /// <param name="groupName">Value list group name as defined in ValueListGroup table.</param>
        /// <param name="fieldName">Field name for value of select field.</param>
        /// <param name="fieldLabel">Label name for select field, pulls from <see cref="LabelAttribute"/> if defined, otherwise defaults to <paramref name="fieldName"/>.</param>
        /// <param name="fieldID">ID to use for select field; defaults to select + <paramref name="fieldName"/>.</param>
        /// <param name="groupDataBinding">Data-bind operations to apply to outer form-group div, if any.</param>
        /// <param name="labelDataBinding">Data-bind operations to apply to label, if any.</param>
        /// <param name="customDataBinding">Extra custom data-binding operations to apply to field, if any.</param>
        /// <param name="dependencyFieldName">Defines default "enabled" subordinate data-bindings based a single boolean field, e.g., a check-box.</param>
        /// <param name="optionDataBinding">Data-bind operations to apply to each option value, if any.</param>
        /// <param name="toolTip">Tool tip text to apply to field, if any.</param>
        /// <returns>Generated HTML for new text field based on modeled table field attributes.</returns>
        public static string AddDirectoryBrowser(string fieldName, bool required, int maxLength = 0, string inputType = null, string fieldLabel = null, string fieldID = null, string groupDataBinding = null, string labelDataBinding = null, string requiredDataBinding = null, string customDataBinding = null, string dependencyFieldName = null, string toolTip = null)
        {
            IRazorEngine   m_razorEngine         = RazorEngine <CSharpEmbeddedResource> .Default;
            RazorView      addInputFieldTemplate = new RazorView(m_razorEngine, $"DirectoryBrowser.cshtml", null);
            DynamicViewBag viewBag = addInputFieldTemplate.ViewBag;

            if (string.IsNullOrEmpty(fieldID))
            {
                fieldID = $"input{fieldName}";
            }

            viewBag.AddValue("FieldName", fieldName);
            viewBag.AddValue("Required", required);
            viewBag.AddValue("MaxLength", maxLength);
            viewBag.AddValue("InputType", inputType ?? "text");
            viewBag.AddValue("FieldLabel", fieldLabel ?? fieldName);
            viewBag.AddValue("FieldID", fieldID);
            viewBag.AddValue("GroupDataBinding", groupDataBinding);
            viewBag.AddValue("LabelDataBinding", labelDataBinding);
            viewBag.AddValue("RequiredDataBinding", requiredDataBinding);
            viewBag.AddValue("CustomDataBinding", customDataBinding);
            viewBag.AddValue("DependencyFieldName", dependencyFieldName);
            viewBag.AddValue("ToolTip", toolTip);

            return(addInputFieldTemplate.Execute());
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> Send(EmailModels mail, HttpPostedFileBase fileUploader = null, object modal = null, string email_template = null)
        {
            //NOTES:  You can call this in the example below.  (This example is in the QuoteMasterController.cs)
            //
            //var email = new EmailController();
            //var message = new EmailModels();
            //message.To = dto.tbl_rep.rep_email;
            //message.Subject = string.Format("Quote {0} has been confirmed", dto.qthdr_qn_basis + "-" + dto.qthdr_rev);
            //Task.Run(() => email.Send(message, null, dto, "quoteConfirmRepEmail.html"));
            //
            //You can also call this without sending models
            //message.Body = "some body string";
            //Task.Run(() => email.Send(message));

            _logger.Debug(string.Format("Start Send Email"));

            if (ModelState.IsValid)
            {
                var message = new MailMessage();
                try
                {
                    if (mail.To.ToString() != null)
                    {
                        foreach (string to in mail.To.ToString().Split(';'))
                        {
                            if (!string.IsNullOrEmpty(to))
                            {
                                message.To.Add(new MailAddress(to));
                                _logger.Debug(string.Format("Sending Email to {0}", to));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("Either no To set or error setting To");
                }
                try
                {
                    if (mail.CC.ToString() != null)
                    {
                        foreach (string cc in mail.CC.ToString().Split(';'))
                        {
                            if (!string.IsNullOrEmpty(cc))
                            {
                                message.CC.Add(new MailAddress(cc));
                                _logger.Debug(string.Format("Sending Email CC to {0}", cc));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("Either no CC set or error setting CC");
                }


                message.Subject = mail.Subject;

                string template     = "";
                string templatefile = "";
                string templatePath = "~/Content/Templates/";
                string body         = "";
                string siteURL      = System.Configuration.ConfigurationManager.AppSettings["SiteURL"];

                if (email_template == null)
                {
                    body = mail.Body;
                }
                else
                {
                    try
                    {
                        template = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath(templatePath + email_template));
                    }
                    catch (Exception)
                    {
                        string currentfolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                        templatefile = currentfolder + "\\Content\\templates\\" + email_template;
                        template     = System.IO.File.ReadAllText(templatefile);
                    }
                    try
                    {
                        object templateModal = new object();
                        var    viewBag       = new DynamicViewBag();
                        viewBag.AddValue("SiteURL", siteURL);

                        if (modal == null)
                        {
                            templateModal = mail;
                        }
                        else
                        {
                            templateModal = modal;
                        }

                        if (Engine.Razor.IsTemplateCached(email_template, null))
                        {
                            body = Engine.Razor.Run(email_template, null, modal, viewBag);
                        }
                        else
                        {
                            body = Engine.Razor.RunCompile(template, email_template, null, modal, viewBag);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Error Sending Email: {0}", ex.ToString()));
                        body = ex.ToString();
                    }
                }

                message.Body       = body;
                message.IsBodyHtml = true;
                if (mail.Attachment != null && mail.Attachment.ContentLength > 0)
                {
                    message.Attachments.Add(new Attachment(mail.Attachment.InputStream, Path.GetFileName(mail.Attachment.FileName)));
                }
                using (var smtp = new SmtpClient())
                {
                    try
                    {
                        await smtp.SendMailAsync(message);

                        return(RedirectToAction("Sent"));
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Error Sending Email: {0}", ex.ToString()));
                        return(RedirectToAction("Error"));
                    }
                }
            }
            return(View(mail));
        }
Ejemplo n.º 14
0
        public void RunFinished()
        {
            if (!isSln)
            {
                return;
            }
            string unexpectedDir = Path.GetDirectoryName(Path.GetDirectoryName(this.dte2.Solution.Projects.Item(1).FullName));

            List <string> projectNames = new List <string>();

            foreach (Project prj in this.dte2.Solution.Projects)
            {
                projectNames.Add(prj.FullName);
            }

            foreach (string prjName in projectNames)
            {
                this.AdjustProjectLoaction(prjName);
            }

            foreach (string prjName in projectNames)
            {
                Directory.Delete(Path.GetDirectoryName(prjName), true);

                if (Path.GetDirectoryName(prjName).EndsWith(".Models.EF"))
                {
                    string slnPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(prjName)));

                    var batPath = Path.Combine(slnPath, Path.GetDirectoryName(prjName).Split(new char[] { '/', '\\' }).Last(), "scaffold.bat");

                    if (!initEFCore)
                    {
                        continue;
                    }
                    var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                    {
                        FileName         = batPath,
                        WorkingDirectory = Path.GetDirectoryName(batPath)
                    });
                    proc.WaitForExit();
                    if (proc.ExitCode != 0)
                    {
                        MessageBox.Show(
                            "EFCore Models 更新失敗",
                            "更新失敗,請檢查批次檔內的資料庫連線字串",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return;
                    }

                    // 產生控制器
                    Assembly currentAssembly = Assembly.GetExecutingAssembly();

                    Stream stream   = currentAssembly.GetManifestResourceStream(currentAssembly.GetName().Name + ".Templates.Controller.txt");
                    var    template = new StreamReader(stream).ReadToEnd();

                    foreach (var model in Directory.GetFiles(Path.GetDirectoryName(batPath), "*.cs", SearchOption.TopDirectoryOnly))
                    {
                        var filename = Path.GetFileNameWithoutExtension(model);
                        if (filename.EndsWith("Context") && filename != "Context")
                        {
                            continue;
                        }

                        var viewBag = new DynamicViewBag();
                        foreach (var kv in replacementsDictionary)
                        {
                            viewBag.AddValue(kv.Key.Replace("$", ""), kv.Value);
                        }
                        viewBag.AddValue("ModelName", filename);
                        viewBag.AddValue("SlnName", Path.GetFileName(slnPath));


                        #region Get Id Type
                        var modelClass = File.ReadAllText(model);

                        Regex propertyRegex = new Regex(@"(?>public|internal)\s+(?!class)((virtual|static|readonly)\s)?(?<Type>[^\s]+)\s+(?<Name>[^\s]+)");

                        var properties = propertyRegex.Matches(modelClass);

                        bool hasKeyType = false;
                        foreach (Match property in properties)
                        {
                            if (property.Groups["Name"].Value?.ToUpper() == "Id".ToUpper())
                            {
                                viewBag.AddValue("ModelKeyType", property.Groups["Type"].Value);
                                hasKeyType = true;

                                break;
                            }
                        }

                        if (!hasKeyType)
                        {
                            viewBag.AddValue("ModelKeyType", "object");
                        }
                        #endregion


                        var output =
                            Engine.Razor.RunCompile(
                                template,
                                "ControllerTemplate",
                                viewBag: viewBag);

                        File.WriteAllText(Path.Combine(slnPath, Path.GetFileName(slnPath), "Controllers", $"{filename}Controller.cs"), output);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public void SendMailToReceivers(ManifestTrackingReceiver MTM)
        {
            string xsUserFolder = @"C:\FMS\" + "FrayteSchedularlog.txt";

            BaseLog.Instance.SetLogFile(xsUserFolder);
            Logger _log = Get_Log();
            //Get Customer Name and Customer User Detail
            var customerDetail = (from u in dbContext.Users
                                  join ua in dbContext.UserAdditionals on u.UserId equals ua.UserId
                                  join ua1 in dbContext.UserAdditionals on ua.OperationUserId equals ua1.UserId
                                  join u1 in dbContext.Users on ua1.UserId equals u1.UserId
                                  join tz in dbContext.Timezones on u.TimezoneId equals tz.TimezoneId
                                  where u.UserId == MTM.CustomerId
                                  select new
            {
                CustomerName = u.ContactName,
                CustomerEmail = u.Email,
                CompanyName = u.CompanyName,
                UserName = u1.ContactName,
                UserPosition = u1.Position,
                UserEmail = u1.Email,
                UserPhone = u1.TelephoneNo,
                UserSkype = u1.Skype,
                UserFax = u1.FaxNumber,
                TimeZoneDetail = new TimeZoneModal
                {
                    Name = tz.Name,
                    Offset = tz.Offset,
                    OffsetShort = tz.OffsetShort,
                    TimezoneId = tz.TimezoneId
                }
            }).FirstOrDefault();
            var            operationzone = UtilityRepository.GetOperationZone();
            string         logoImage     = AppSettings.EmailServicePath + "/Images/FrayteLogo.png";
            DynamicViewBag viewBag       = new DynamicViewBag();

            if (customerDetail.TimeZoneDetail != null)
            {
                viewBag.AddValue("CreatedOn", UtilityRepository.GetTimeZoneCurrentDateTime(customerDetail.TimeZoneDetail.Name).ToString("dd-MMM-yyyy hh:mm"));;
                viewBag.AddValue("TimeZone", customerDetail.TimeZoneDetail.OffsetShort);
            }
            else
            {
                viewBag.AddValue("CreatedOn", DateTime.Now.ToString("dd-MMM-yyyy hh:mm"));
            }

            viewBag.AddValue("TrackingDescription", MTM.TrackingDescription);
            viewBag.AddValue("TrackingNo", MTM.ReceiverTrackingNo);
            viewBag.AddValue("CustomerName", MTM.ReceiverName);
            viewBag.AddValue("UserEmail", customerDetail.CustomerEmail);
            viewBag.AddValue("UserPhone", customerDetail.UserPhone);
            viewBag.AddValue("ImageHeader", "FrayteLogo");

            if (operationzone.OperationZoneId == 1)
            {
                viewBag.AddValue("SiteAddress", AppSettings.TrackingUrl);
            }
            else
            {
                viewBag.AddValue("SiteAddress", AppSettings.TrackingUrl);
            }

            string template        = File.ReadAllText(AppSettings.EmailServicePath + "/EmailTeamplate/eCommerceManifestTracking.cshtml");
            var    templateService = new TemplateService();
            var    EmailBody       = templateService.Parse(template, MTM, viewBag, null);
            string EmailSubject    = "Manifest Tracking";

            //var To = MTM.ReceiverMail;
            _log.Error(MTM.ReceiverMail);
            var    To     = "*****@*****.**";
            var    CC     = customerDetail.UserEmail;
            string Status = "Confirmation";

            //Send mail to Customer
            //SendMail_New(To, CC, "FRAYTE (" + UtilityRepository.OperationZoneName(operationzone.OperationZoneId) + ")", EmailSubject, EmailBody, Attachment, Status);
            FrayteEmail.SendMail(To, CC, EmailSubject, EmailBody, logoImage);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// 使用key-value方式给ViewBag赋值
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public virtual void SetViewBagValue(string key, object value)
 {
     _viewBag.AddValue(key, value);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 视图背包添加成员
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 public void Add_default(string key, string value)
 {
     viewBag.AddValue(key, value);
 }
Ejemplo n.º 18
0
        public void SendPaymentEmail(OnlinePaymentModel item, string TransactionNo, string sendFrom, string Status)
        {
            if (item != null && item.PaymentInfo != null)
            {
                // var date = DateTime.SpecifyKind(DateTime.Now,;
                //  OnlinePayment obj = new OnlinePayment();
                DynamicViewBag viewBag = new DynamicViewBag();
                viewBag.AddValue("CustomerFirstName", item.PaymentInfo.FirstName);
                viewBag.AddValue("CustomerLastName", item.PaymentInfo.LastName);
                viewBag.AddValue("CustomerCompany", item.PaymentInfo.CompanyName);
                viewBag.AddValue("PaymentCompany", item.PaymentCompany);
                viewBag.AddValue("Date", item.PaymentInfo.PaymentDate);
                viewBag.AddValue("Time", item.PaymentInfo.PaymentTime);
                viewBag.AddValue("ShippingOrderNo", item.PaymentInfo.Invoice_no);
                viewBag.AddValue("PaymentNo", TransactionNo);
                viewBag.AddValue("Currency", item.PaymentInfo.Currency.CurrencyCode);
                viewBag.AddValue("Amount", Math.Round(item.Amount, 2));

                string toEmail      = string.Empty;
                var    EmailSubject = string.Empty;
                string toCC         = string.Empty;
                if (item.PaymentCompany == OnlinePaymentCompany.Whytecllif)
                {
                    viewBag.AddValue("FromRegards", "WHTYTECLIFF Customer Service Team");
                    viewBag.AddValue("FromCompany", "WHYTECLIFF GROUP Ltd.");
                    viewBag.AddValue("FromSite", "www.WHYTECLIFF.com");
                    viewBag.AddValue("FromPhone", "(+852) 2148 4881");
                    viewBag.AddValue("FromEmail", "*****@*****.**");
                    //EmailSubject = "Payment Confirmation - WHTYTECLIFF Group Ltd.";
                    EmailSubject = "Payment Completed – Whytecliff Group";
                }
                else if (item.PaymentCompany == OnlinePaymentCompany.VytalSupport)
                {
                    viewBag.AddValue("FromRegards", "VYTAL SUPPORT Customer Service Team");
                    viewBag.AddValue("FromCompany", "VYTAL SUPPORT (Hong Kong) Ltd.");
                    viewBag.AddValue("FromSite", "www.VYTALSUPPORT.com");
                    viewBag.AddValue("FromPhone", "(+852) 2148 4881");
                    viewBag.AddValue("FromEmail", " [email protected]");
                    //EmailSubject = "Payment Confirmation - VYTAL SUPPORT (Hong Kong) Co. Ltd.";
                    EmailSubject = "Payment Completed – Vytal Support (Hong Kong)";
                }
                else if (item.PaymentCompany == OnlinePaymentCompany.CliffPremus)
                {
                    viewBag.AddValue("FromRegards", "CLIFF PREMIUMS Customer Service Team");
                    viewBag.AddValue("FromCompany", "CLIFF PREMIUMS Ltd.");
                    viewBag.AddValue("FromSite", "www.CLIFFPREMIUMS.com");
                    viewBag.AddValue("FromPhone", "(+852) 2148 4881");
                    viewBag.AddValue("FromEmail", "[email protected] ");
                    EmailSubject = "Payment Completed – Cliff Premiums";
                }
                else if (item.PaymentCompany == OnlinePaymentCompany.FrayteCom)
                {
                    viewBag.AddValue("FromRegards", "FRAYTE Logistic Customer Service Team");
                    viewBag.AddValue("FromCompany", "FRAYTE GLOBAL");
                    viewBag.AddValue("FromSite", "www.FRAYTE.com");
                    viewBag.AddValue("FromPhone", "(+852) 2148 4880");
                    viewBag.AddValue("FromEmail", "*****@*****.**");
                    EmailSubject = "Payment Completed - FRAYTE GLOBAL";
                }
                else if (item.PaymentCompany == OnlinePaymentCompany.FrayteCoUk)
                {
                    viewBag.AddValue("FromRegards", "FRAYTE Logistic Customer Service Team");
                    viewBag.AddValue("FromCompany", "FRAYTE GLOBAL");
                    viewBag.AddValue("FromSite", "www.FRAYTE.co.uk");
                    viewBag.AddValue("FromPhone", "(+44) 01792 277295");
                    viewBag.AddValue("FromEmail", "*****@*****.**");
                    EmailSubject = "Payment Completed - FRAYTE GLOBAL";
                }
                string template        = File.ReadAllText(AppSettings.EmailServicePath + "/EmailTemplate/Payment.cshtml");
                var    templateService = new TemplateService();

                var EmailBody = templateService.Parse(template, "", viewBag, null);

                var Issend = false;
                if (Status == OnlinePaymentStatus.Success)
                {
                    //Issend = new  ShipmentEmailRepository().SendMail(toEmail, EmailSubject, EmailBody, "", "", item.PaymentCompany);
                }
                if (Issend == true)
                {
                    // obj.IsEmailSent = true;
                    //   dbContext.OnlinePayments.Add(obj);
                    dbContext.SaveChanges();
                }
                else
                {
                    //  obj.IsEmailSent = false;
                    //dbContext.OnlinePayments.Add(obj);
                    dbContext.SaveChanges();
                }
            }
        }
Ejemplo n.º 19
0
        public void CompileCategoryContent(int categoryId)
        {
            //逐条生成

            //获取栏目实体
            var categoryModel = _cmsCoreDB.Category.FirstOrDefault(p => p.ID == categoryId);

            if (categoryModel != null)
            {
                //自定义内容模型
                if (categoryModel.ModelType == 1)
                {
                    var customContentModel = _cmsCoreDB.ContentModel.FirstOrDefault(p => p.ID == categoryModel.ModelId);
                    if (customContentModel != null)
                    {
                        var pageSize         = categoryModel.ShowPageSize;
                        var pageIndex        = 0;
                        var templateFilePath = string.Format("{0}\\Templates\\{1}\\{2}",
                                                             AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'),
                                                             categoryModel.DefaultStyle,
                                                             categoryModel.ShowTemplate.Replace("/", "\\"));

                        //按分页遍历生成
                        var dataModelManage = new DataModelManage();

                        //GOTO返回获取数据标志
RELOADPAGELIST:

                        #region GOTO循环获取分页数据,直至分页为0

                        var pageListModel = dataModelManage.GetPageList(customContentModel.TableName, categoryId, pageIndex, pageSize);

                        //如果存在数据
                        var listModel = pageListModel as dynamic[] ?? pageListModel.ToArray();
                        if (listModel.Any())
                        {
                            //逐个渲染模型
                            foreach (var m in listModel)
                            {
                                var viewBag = new DynamicViewBag();

                                viewBag.AddValue("Data", m);

                                //渲染
                                var parseResult = ParsePathContent(templateFilePath, viewBag);

                                //发布
                                if (!string.IsNullOrEmpty(parseResult))
                                {
                                    var publishResult = new PublishResult
                                    {
                                        Context = parseResult,
                                        Path    = categoryModel.CatPath, //递归路径
                                    };

                                    publishResult.FileName = m.ID.ToString();

                                    _publishEngine.Push(publishResult);
                                }
                            }

                            //当前分页索引递增至下一页
                            pageIndex++;

                            //重新获取下一分页数据
                            goto RELOADPAGELIST;
                        }

                        #endregion
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Compiles and executes view template.
        /// </summary>
        /// <returns>Rendered result.</returns>
        public string Execute()
        {
            try
            {
                using (DataContext dataContext = new DataContext(Database, razorEngine: DataContextEngine, exceptionHandler: ExceptionHandler))
                {
                    if ((object)PagedViewModelDataType != null && (object)PagedViewModelHubType != null)
                    {
                        dataContext.ConfigureView(PagedViewModelDataType, PagedViewModelHubType, null as string, m_viewBag);
                    }

                    m_viewBag.AddValue("DataContext", dataContext);
                    return(m_razorEngine.RunCompile(TemplateName, ModelType, Model, m_viewBag));
                }
            }
            catch (Exception ex)
            {
                string errorTemplateName = WebServerOptions?.ErrorTemplateName;

                if (string.IsNullOrWhiteSpace(errorTemplateName))
                {
                    throw;
                }

                return(RenderErrorTemplate(errorTemplateName, ex));
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            ////////////////////////////////////////////////////
            string localData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            if (!System.IO.Directory.Exists(localData + "\\ResTBDesktop"))
            {
                System.IO.Directory.CreateDirectory(localData + "\\ResTBDesktop");
            }
            //string scriptPath = localData + "\\ResTBDesktop\\Script";
            //if (!System.IO.Directory.Exists(scriptPath))
            //    System.IO.Directory.CreateDirectory(scriptPath);
            string htmlPath = localData + "\\ResTBDesktop\\result.html";


            //Console.WriteLine($"output html: {htmlPath}");
            ////////////////////////////////////////////////////

            int  projectId   = -1;
            bool showDetails = false;
            bool onlySummary = false;
            bool isOnline    = false;

            string cultureString = "en";
            var    p             = new FluentCommandLineParser();

            p.Setup <int>('p', "project")
            .Callback(record => projectId = record)
            .WithDescription("Project ID (int)")
            .Required();

            p.Setup <bool>('d', "detail")
            .Callback(record => showDetails = record)
            .WithDescription("Show Details in Summary")
            .SetDefault(false);

            p.Setup <bool>('s', "summaryonly")
            .Callback(record => onlySummary = record)
            .WithDescription("Show Summary Only")
            .SetDefault(false);

            p.Setup <string>('c', "culture")
            .Callback(record => cultureString = record)
            .WithDescription("Language Setting")
            .SetDefault("es-HN");

            p.Setup <bool>('o', "online")
            .Callback(record => isOnline = record)
            .WithDescription("DB is online")
            .SetDefault(false);

            var parsedArgs = p.Parse(args);

            if (parsedArgs.HasErrors == true)
            {
                Console.WriteLine(parsedArgs.ErrorText);
                return;
            }

            Globals.ISONLINE = isOnline;    //set for Connection string

            CultureInfo culture;

            try
            {
                //CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureString);
                culture = new CultureInfo(cultureString);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                //CultureInfo.DefaultThreadCurrentUICulture = culture;
                //CultureInfo.DefaultThreadCurrentCulture = culture;
            }
            catch (Exception)
            {
                Console.WriteLine($"ERROR: culture invalid. Provided value: {cultureString}");
                return;
            }

            Console.WriteLine("Kernel started...");
            Console.WriteLine($"\tProject Id = {projectId}, showDetails = {showDetails}, " +
                              $"summaryOnly = {onlySummary}, culture = {cultureString}, isOnline = {isOnline}");
            ////////////////////////////////////////////////////
            // CALCULATION

            if (!onlySummary)
            {
                try
                {
                    ResultWrapper.CreateDamageExtents(projectId);               //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                    Console.WriteLine("\n\tCreate Damage Extents finished.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nError while creating damage extents.\n\n" + ex.ToString());
                    return;
                }
            }

            ProjectResult projectResult = ResultWrapper.ComputeResult(projectId, showDetails);

            Console.WriteLine("\n\tCompute Project Result finished.");

            string fullFileName = @"Kernel/Views/Summary.cshtml";               //REMINDER: Copy CSHTML to output dir

            DynamicViewBag viewBag = new DynamicViewBag();

            viewBag.AddValue("attachCss", true);
            viewBag.AddValue("details", showDetails);
            viewBag.AddValue("print", true);

            var    templateSource = new LoadedTemplateSource(File.ReadAllText(fullFileName), fullFileName);
            string result         = "";

            var t = Task.Run(() =>
            {
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                Console.WriteLine("Task thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
                result =
                    Engine.Razor.RunCompile(templateSource, "templateKey", null, model: projectResult, viewBag: viewBag);   //RENDER HTML with RAZOR ENGINE

                Console.WriteLine($"\tTask: culture = {culture.TwoLetterISOLanguageName} / {culture.Name}");
            });

            t.Wait();

            File.WriteAllText(htmlPath, result);               //TODO: Save HTML to output dir

            Console.WriteLine("\nKernel finished.\n");
        }
Ejemplo n.º 22
0
        private Tuple <string, HashSet <string> > GetApplicationMenu(Application app, Dictionary <TapestryDesignerBlock, Block> blockMapping, int rootMetablockId = 0, int level = 0)
        {
            HashSet <string> rights = new HashSet <string>();

            if (rootMetablockId == 0)
            {
                rootMetablockId = app.TapestryDesignerRootMetablock.Id;
            }

            List <TapestryDesignerMenuItem> items = new List <TapestryDesignerMenuItem>();

            foreach (TapestryDesignerMetablock m in core.Context.TapestryDesignerMetablocks.Include("ParentMetablock").Where(m => m.ParentMetablock.Id == rootMetablockId && m.IsInMenu == true && !m.IsDeleted))
            {
                var menuResult = GetApplicationMenu(app, blockMapping, m.Id, level + 1);
                rights.AddRange(menuResult.Item2);
                items.Add(new TapestryDesignerMenuItem()
                {
                    Id          = m.Id,
                    Name        = m.Name,
                    SubMenu     = menuResult.Item1,
                    IsInitial   = m.IsInitial,
                    IsInMenu    = m.IsInMenu,
                    MenuOrder   = m.MenuOrder,
                    IsMetablock = true,
                    rights      = string.Join(",", menuResult.Item2)
                });
            }

            foreach (TapestryDesignerBlock b in core.Context.TapestryDesignerBlocks.Include("ParentMetablock").Where(b => !b.IsDeleted && b.ParentMetablock.Id == rootMetablockId && b.IsInMenu == true))
            {
                var commit = b.BlockCommits.OrderByDescending(bc => bc.Timestamp).FirstOrDefault();
                if (commit != null && !string.IsNullOrWhiteSpace(commit.RoleWhitelist))
                {
                    rights.AddRange(commit.RoleWhitelist.Split(','));
                }
                else
                {
                    rights.Add("User");
                }
                items.Add(new TapestryDesignerMenuItem()
                {
                    Id        = b.Id,
                    Name      = b.Name,
                    IsInitial = b.IsInitial,
                    IsInMenu  = b.IsInMenu,
                    MenuOrder = b.MenuOrder,
                    IsBlock   = true,
                    BlockName = blockMapping[b].Name,
                    rights    = commit != null && !string.IsNullOrEmpty(commit.RoleWhitelist) ? commit.RoleWhitelist : "User"
                });
            }

            /*ViewDataDictionary ViewData = new ViewDataDictionary();
             * ViewData.Model = items;
             * ViewData["Level"] = level;
             * ViewData["ParentID"] = rootId;
             * ViewData["AppId"] = core.Application.Id;
             */
            //TempDataDictionary TempData = new TempDataDictionary();
            //ControllerContext ControllerContext = new ControllerContext();

            //using (var sw = new StringWriter())
            //{
            //    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "~/Views/Shared/_ApplicationMenu.cshtml");
            //    var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            //    viewResult.View.Render(viewContext, sw);
            //    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            //    return new Tuple<string, HashSet<string>>(sw.GetStringBuilder().ToString(), rights);
            //}


            DynamicViewBag ViewBag = new DynamicViewBag();

            ViewBag.AddValue("Level", level);
            ViewBag.AddValue("AppId", app.Id);
            ViewBag.AddValue("AppName", app.Name);
            ViewBag.AddValue("ParentId", rootMetablockId);

            string source = File.ReadAllText(_menuPath);

            string result = Engine.Razor.RunCompile(source, new Random().Next().ToString(), null, items, ViewBag);

            return(new Tuple <string, HashSet <string> >(result, rights));
        }