public void GeneratedScript_ZipsNodeModules_IfZipNodeProperty_IsZip()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "6.0.0");
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";
            context.Properties["compress_node_modules"] = "zip";

            var expected = new NodeBashBuildSnippetProperties
            {
                PackageInstallCommand               = NpmInstallCommand,
                PackageInstallerVersionCommand      = NodeConstants.NpmVersionCommand,
                NpmRunBuildCommand                  = "npm run build",
                NpmRunBuildAzureCommand             = "npm run build:azure",
                HasProductionOnlyDependencies       = true,
                ProductionOnlyPackageInstallCommand = string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                CompressedNodeModulesFileName = "node_modules.zip",
                CompressNodeModulesCommand    = "zip -y -q -r",
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Contains("echo Zipping existing 'node_modules' folder", snippet.BashBuildScriptSnippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
Example #2
0
        private FrameworkElement CreateConditionFormatContent()
        {
            SetEnabled();
            if (!IsEnabled)
            {
                return(null);
            }

            var content = TemplateHelper.LoadFromTemplate <FrameworkElement>((DataTemplate)View.FindResource(new ConditionalFormattingThemeKeyExtension {
                ResourceKey = TemplateKey
            }));

            IEnumerable groups;

            switch (TemplateKey)
            {
            case ConditionalFormattingThemeKeys.ColorScaleMenuItemContent:
                groups = GetGroupedFormatItems <DataBarFormatCondition>(View.PredefinedColorScaleFormats, x => new[] { x.Icon });
                break;

            case ConditionalFormattingThemeKeys.DataBarMenuItemContent:
                groups = GetGroupedFormatItems <DataBarFormatCondition>(View.PredefinedDataBarFormats, x => new[] { x.Icon });
                break;

            case ConditionalFormattingThemeKeys.IconSetMenuItemContent:
                groups = GetGroupedFormatItems <DataBarFormatCondition>(View.PredefinedIconSetFormats,
                                                                        x => ((IconSetFormat)x.Format).Elements.Select(y => y.Icon));
                break;

            default:
                throw new DeveloperException("Undefined FormatConditionType '{0}'.", TemplateKey);
            }

            //content.DataContext = new GridColumnMenuInfo.FormatsViewModel(groups);
            content.DataContext = new FormatsViewModel(groups);
            return(content);
        }
Example #3
0
        private void SendEmail()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.Zone))
                {
                    using (SPWeb _web = _site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        if (_web != null)
                        {
                            _site.AllowUnsafeUpdates = true;
                            _web.AllowUnsafeUpdates  = true;

                            if (!SPUtility.IsEmailServerSet(_web))
                            {
                                TemplateHelper helper = new TemplateHelper(_ctlPasswordRecovery.SuccessTemplateContainer);
                                helper.SetText("Success", "Password can not be reset since email server is not configutred for this sharepoint application.");
                                return;
                            }

                            PasswordRecovery prc             = _ctlPasswordRecovery;
                            MembershipUser currentUser       = Utils.BaseMembershipProvider(_web.Site).GetUser(prc.UserName, false);
                            MembershipRequest membershipitem = MembershipRequest.GetMembershipRequest(currentUser, _web);

                            membershipitem.PasswordQuestion = currentUser.PasswordQuestion;
                            membershipitem.Password         = currentUser.ResetPassword(prc.Answer);

                            if (!MembershipRequest.SendPasswordRecoveryEmail(membershipitem, _web))
                            {
                                TemplateHelper helper = new TemplateHelper(_ctlPasswordRecovery.SuccessTemplateContainer);
                                helper.SetText("Success", LocalizedString.GetString("FBAPackPasswordRecoveryWebPart", "ErrorSendingEmail"));
                            }
                        }
                    }
                }
            });
        }
Example #4
0
        private static void GenerateTemplate_Model(GeneratorConfig allConfig)
        {
            Console.WriteLine("===============生成Model==================");
            DisplayTemplateName(allConfig.modelTemplate);
            var templateText = TemplateHelper.ReadTemplate(allConfig.modelTemplate);
            var db           = new MySqlSchema(allConfig.dbConfig);

            foreach (var tableName in allConfig.tableList)
            {
                var table = db.GetTableMetadata(tableName);

                if (!string.IsNullOrEmpty(allConfig.trimTablePre))
                {
                    table.ClassName = TrimPre(tableName, allConfig.trimTablePre);
                }
                if (!string.IsNullOrEmpty(allConfig.baseColumn))
                {
                    table.BaseColumns = allConfig.baseColumn.Split(',').ToList();
                }
                table.TableName = tableName;

                //if (table.PKs.Count == 0) throw new Exception(string.Format("表{0}:没有设置主键!", tableName));
                Display(tableName, table);
                dynamic viewbag = new DynamicViewBag();
                viewbag.classnameVal = table.ClassName;
                viewbag.namespaceVal = allConfig.modelNamespaceVal;
                allConfig.table      = table;
                var outputText = TemplateHelper.Parse(TemplateKey.Model, templateText, allConfig, viewbag);
                outputText = TemplateHelper.Clean(outputText, RegexPub.H1());

                var path = allConfig.modelSavePath + "\\" + allConfig.moduleName;

                FileHelper.Save(string.Format(@"{0}\{1}.cs", path, viewbag.classnameVal), outputText);
            }

            Console.WriteLine("===============生成Model完成==================");
        }
        public async Task SendMails()
        {
            var newsEntities = new NewletterEntities();
            var customers    = newsEntities.Customers;

            foreach (var item in customers)
            {
                var customerproducts = (from p in newsEntities.Products
                                        join crt in newsEntities.Carts
                                        on p.ProductId equals crt.ProductId
                                        join cust in newsEntities.Customers
                                        on crt.CartId equals cust.CustomerId.ToString()
                                        where cust.CustomerId == item.CustomerId
                                        select new
                {
                    productName = p.ProductName,
                    productImage = p.ProductImage,
                    productPrice = p.Price
                }).ToList();

                StringBuilder orders = new StringBuilder();
                if (customerproducts.Any())
                {
                    foreach (var prod in customerproducts)
                    {
                        var productTemplate = TemplateHelper.BuildProductListTemplate(prod.productName, prod.productPrice, prod.productImage);

                        orders.Append(productTemplate);
                    }

                    var emailBody = TemplateHelper.BuildEmailTemplate(orders.ToString(), item.CustomerName);

                    var mailService  = new EmailHelper();
                    var mailResponse = await mailService.Send("Order Reminder", item.Email, emailBody);
                }
            }
        }
Example #6
0
        public void GeneratedScript_UsesYarnInstallAndRunsNpmBuild_IfYarnLockIsPresent_AndHasBuildNodeUnderScripts()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "6.0.0");
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            repo.AddFile("Yarn lock file content here", NodeConstants.YarnLockFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";

            var expected = new NodeBashBuildSnippetProperties
            {
                PackageInstallCommand               = YarnInstallCommand,
                PackageInstallerVersionCommand      = NodeConstants.YarnVersionCommand,
                NpmRunBuildCommand                  = "yarn run build",
                NpmRunBuildAzureCommand             = "yarn run build:azure",
                HasProductionOnlyDependencies       = true,
                ProductionOnlyPackageInstallCommand = string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    YarnInstallCommand),
                CompressedNodeModulesFileName = null,
                CompressNodeModulesCommand    = null,
                ConfigureYarnCache            = true,
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
Example #7
0
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DataEntities ent = new DataEntities();
            int          id  = WS.RequestInt("id");
            TemplateVar  tl  = new TemplateVar();

            try
            {
                tl = (from l in ent.TemplateVar where l.ID == id select l).First();
            }
            catch { }

            tl.VarName = txt_VarName.Text;
            tl.Content = txt_Content.Text.Replace("'", "''");

            if (tl.ID == null || tl.ID <= 0)
            {
                ent.AddToTemplateVar(tl);
            }
            ent.SaveChanges();

            var            pages = (from l in ent.TemplatePage where l.CreateWith == 5 select l).ToList();
            TemplateHelper th    = new TemplateHelper();

            foreach (var p in pages)
            {
                try
                {
                    string html = th.GetStatisPage(p.id);
                    Voodoo.IO.File.Write(Server.MapPath(p.FileName), html);
                }
                catch { }
            }

            ent.Dispose();
            Js.AlertAndChangUrl("保存成功!", "VarTemplateList.aspx");
        }
Example #8
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(BuildScriptGeneratorContext ctx)
        {
            var buildProperties = new Dictionary<string, string>();

            // Write the version to the manifest file
            var key = $"{PhpConstants.PhpName}_version";
            buildProperties[key] = ctx.PhpVersion;

            _logger.LogDebug("Selected PHP version: {phpVer}", ctx.PhpVersion);
            bool composerFileExists = false;

            if (ctx.SourceRepo.FileExists(PhpConstants.ComposerFileName))
            {
                composerFileExists = true;

                try
                {
                    dynamic composerFile = ctx.SourceRepo.ReadJsonObjectFromFile(PhpConstants.ComposerFileName);
                    if (composerFile?.require != null)
                    {
                        Newtonsoft.Json.Linq.JObject deps = composerFile?.require;
                        var depSpecs = deps.ToObject<IDictionary<string, string>>();
                        _logger.LogDependencies(this.Name, ctx.PhpVersion, depSpecs.Select(kv => kv.Key + kv.Value));
                    }
                }
                catch (Exception exc)
                {
                    // Leave malformed composer.json files for Composer to handle.
                    // This prevents Oryx from erroring out when Composer itself might be able to tolerate the file.
                    _logger.LogWarning(exc, $"Exception caught while trying to deserialize {PhpConstants.ComposerFileName.Hash()}");
                }
            }

            var props = new PhpBashBuildSnippetProperties { ComposerFileExists = composerFileExists };
            string snippet = TemplateHelper.Render(TemplateHelper.TemplateResource.PhpBuildSnippet, props, _logger);
            return new BuildScriptSnippet { BashBuildScriptSnippet = snippet, BuildProperties = buildProperties };
        }
        public async Task ExecutionOfAQueryPlan_WithValidDefaultObject_forSubscription_YieldsResult()
        {
            var server = new TestServerBuilder()
                         .AddGraphType <SubQueryController>()
                         .AddSubscriptionServer()
                         .Build();

            var template = TemplateHelper.CreateActionMethodTemplate <SubQueryController>(nameof(SubQueryController.RetrieveObject));

            var sourceObject = new TwoPropertyObject()
            {
                Property1 = "testA",
                Property2 = 5,
            };

            // Add a default value for the "retrieveObject" method, which is a subscription action
            // this mimics recieving an subscription event data source and executing the default, normal pipeline
            // to produce a final result that can be returned along the client connection
            var builder = server.CreateQueryContextBuilder()
                          .AddQueryText("subscription  { subscriptionData {  retrieveObject { property1 } } }")
                          .AddDefaultValue(template.Route, sourceObject);

            var result = await server.RenderResult(builder);

            var expectedOutput =
                @"{
                            ""data"" : {
                                ""subscriptionData"" : {
                                    ""retrieveObject"" : {
                                        ""property1"" : ""testA""
                                    }
                                }
                            }
                        }";

            CommonAssertions.AreEqualJsonStrings(expectedOutput, result);
        }
Example #10
0
        private ActionResult RenderAsHtml(IReport report, bool download, bool printing,
                                          ref byte[] renderedBytes)
        {
            var designAttr = report.GetType().GetAttribute <ReportDesignAttribute>();

            if (designAttr == null)
            {
                throw new Exception(String.Format("Report design attribute for type '{0}' is not found!",
                                                  report.GetType().FullName));
            }

            var data     = report.GetData();
            var viewData = download ? new ViewDataDictionary(data) : ViewData;

            var iadditional = report as IReportWithAdditionalData;

            if (iadditional == null)
            {
                viewData["AdditionalData"] = new Dictionary <string, object>();
            }
            else
            {
                viewData["AdditionalData"] = iadditional.GetAdditionalData();
            }

            viewData["Printing"] = printing;

            if (!download)
            {
                return(View(viewName: designAttr.Design, model: data));
            }

            var html = TemplateHelper.RenderViewToString(designAttr.Design, viewData);

            renderedBytes = Encoding.UTF8.GetBytes(html);
            return(null);
        }
Example #11
0
        bool AddTemplateGroupItem()
        {
            //子模板不记录到模板组XML
            if (TypeList.SelectedValue != Boolean.TrueString)
            {
                TemplateGroup.Item item = null;

                TemplateGroup tg = TemplateHelper.GetTemplateGroup(TemplateGroupFileName);

                foreach (TemplateGroup.Item it in tg.Items)
                {
                    if (it.Alias == AliasWordsTextBox.Text && it.IsDetailTemplate.ToString() == IsDetailTemplateDropDownList.SelectedValue)
                    {
                        item = it;
                    }
                }
                if (item == null)
                {
                    item                  = new TemplateGroup.Item();
                    item.Alias            = AliasWordsTextBox.Text;
                    item.Template         = FileNameTextBox.Text;
                    item.TemplateText     = TemplateHelper.GetTemplateName(item.Template);
                    item.IsDetailTemplate = IsDetailTemplateDropDownList.SelectedValue == Boolean.TrueString;

                    tg.Items.Add(item);

                    string fn = TemplateHelper.SaveTemplateGroupAndPreviewFile(tg, Path.GetFileNameWithoutExtension(TemplateGroupFileName));
                    return(true);
                }
                else
                {
                    Messages.ShowError("无法增加模板记录到模板组,该别名已被使用;请使用其他别名再试!");
                }
            }
            return(false);
        }
Example #12
0
        public void GeneratedSnippet_Contains_BuildCommands_And_PythonVersion_Info()
        {
            // Arrange
            var snippetProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: null,
                virtualEnvironmentModule: null,
                virtualEnvironmentParameters: null,
                packagesDirectory: "packages_dir",
                enableCollectStatic: true,
                compressVirtualEnvCommand: null,
                compressedVirtualEnvFileName: null,
                pythonBuildCommandsFileName: FilePaths.BuildCommandsFileName,
                pythonVersion: "3.6",
                runPythonPackageCommand: false
                );

            // Act
            var text = TemplateHelper.Render(TemplateHelper.TemplateResource.PythonSnippet, snippetProps);

            // Assert
            Assert.NotEmpty(text);
            Assert.NotNull(text);
            Assert.Contains("COMMAND_MANIFEST_FILE=\"oryx-build-commands.txt\"", text);
        }
Example #13
0
        private static void GenerateTemplate_Dao(string templateFileName, List <string> tableList, IDBSchema dbSchema, string daoNamespaceVal, string modelNamespaceVal, string dbNameVal, string savePath)
        {
            DisplayTemplateName(templateFileName);
            var templateText = TemplateHelper.ReadTemplate(templateFileName);

            foreach (var tableName in tableList)
            {
                var table = dbSchema.GetTableMetadata(tableName);
                if (table.PKs.Count == 0)
                {
                    throw new Exception(string.Format("表{0}:没有设置主键!", tableName));
                }
                Display(tableName, table);
                dynamic viewbag = new DynamicViewBag();
                viewbag.classnameVal      = tableName + "Dao";
                viewbag.namespaceVal      = daoNamespaceVal;
                viewbag.modelNamespaceVal = modelNamespaceVal;
                viewbag.dbNameVal         = dbNameVal;
                var outputText = TemplateHelper.Parse(TemplateKey.Dao, templateText, table, viewbag);
                outputText = TemplateHelper.Clean(outputText, RegexPub.H1());
                outputText = TemplateHelper.Clean(outputText, RegexPub.H2());
                FileHelper.Save(string.Format(@"{0}\{1}.cs", savePath, viewbag.classnameVal), outputText);
            }
        }
Example #14
0
        public void Parse_FieldAndDependencies_SetCorrectly()
        {
            var server = new TestServerBuilder().Build();

            var template = TemplateHelper.CreateGraphTypeTemplate <ComplexInputObject>(TypeKind.INPUT_OBJECT) as IInputObjectGraphTypeTemplate;

            var typeResult = this.MakeGraphType(typeof(ComplexInputObject), TypeKind.INPUT_OBJECT);
            var graphType  = typeResult.GraphType as IInputObjectGraphType;

            Assert.IsNotNull(graphType);

            var inputGraphTypeName = GraphTypeNames.ParseName(typeof(OneMarkedProperty), TypeKind.INPUT_OBJECT);

            Assert.AreEqual(2, graphType.Fields.Count);

            var field = graphType.Fields.FirstOrDefault(x => x.TypeExpression.TypeName == inputGraphTypeName);

            Assert.IsNotNull(field);

            // string, OneMarkedProperty
            Assert.AreEqual(2, typeResult.DependentTypes.Count());
            Assert.IsTrue(typeResult.DependentTypes.Any(x => x.Type == typeof(OneMarkedProperty) && x.ExpectedKind == TypeKind.INPUT_OBJECT));
            Assert.IsTrue(typeResult.DependentTypes.Any(x => x.Type == typeof(string) && x.ExpectedKind == TypeKind.SCALAR));
        }
Example #15
0
        static void Main(string[] args)
        {
            TemplateHelper.Init();

            GeneratorConfig allConfig = new GeneratorConfig();

            Console.WriteLine("请输入表名:");
            allConfig.inputTables = Console.ReadLine();
            Console.WriteLine("请输入模块名(空则直接ENTER跳过):");
            allConfig.moduleName = Console.ReadLine();
            //
            DbConfig dbConfig = new DbConfig();

            dbConfig.dataBaseName = "natsucloud";
            dbConfig.userName     = "******";
            dbConfig.port         = 5831;
            dbConfig.password     = "******";
            dbConfig.ip           = "127.0.0.1";
            allConfig.dbConfig    = dbConfig;

            allConfig.modelNamespaceVal = "LINE.SMA.Model";
            allConfig.modelSavePath     = @"D:\SMA";
            allConfig.modelTemplate     = "ModelAuto";
            allConfig.trimTablePre      = "t_";
            allConfig.baseColumn        = "id";

            allConfig.repNamespaceVal = "LINE.SMA.Repositories";
            allConfig.repSavePath     = @"D:\SMA";
            allConfig.repTemplate     = "RepositoryAuto";

            allConfig.iRepNamespaceVal = "LINE.SMA.Repositories";
            allConfig.iRepSavePath     = @"D:\SMA";
            allConfig.iRepTemplate     = "IRepositoryAuto";

            AutoGenerator.startExecute(allConfig);
        }
Example #16
0
        /// <summary>
        /// 模板文件删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteFileButton_Click(object sender, EventArgs e)
        {
            if (DemoSiteMessage)
            {
                return;                 //是否是演示站点
            }
            try
            {
                string tf = FileTextBox.Text;
                TemplateHelper.RemoveTemplateBind(null, FileName, tf);
                string fn        = Server.MapPath(Path.Combine(String.Format("\\{0}\\{1}", Constants.TemplateBasePath, Path.GetFileNameWithoutExtension(FileName)), tf));
                string PreviewFn = Server.MapPath(Path.Combine(String.Format("\\{0}\\{1}", Constants.TemplateBasePath, Path.GetFileNameWithoutExtension("~" + FileName)), tf));
                if (File.Exists(PreviewFn))
                {
                    File.Delete(PreviewFn);
                }
                if (File.Exists(fn))
                {
                    File.Delete(fn);
                }
                if (File.Exists(fn + ".xml"))
                {
                    File.Delete(fn + ".xml");
                }

                //记录日志
                string content = string.Format("删除了模板文件:“{0}”", tf);
                AddLog("模板文件管理", content);
                Messages.ShowMessage("您已成功删除模板文件【" + tf + "】");
            }
            catch (Exception ex)
            {
                //log
            }
            ShowTempalteFile();
        }
Example #17
0
 void DeleteTemplateGroupItem()
 {
     //子模板不记录到模板组XML
     if (TypeList.SelectedValue != Boolean.TrueString)
     {
         TemplateGroup.Item del = null;
         TemplateGroup      tg  = TemplateHelper.GetTemplateGroup(TemplateGroupFileName);
         foreach (TemplateGroup.Item it in tg.Items)
         {
             if (it.Alias == DeleteItemAliasTextBox.Text && it.IsDetailTemplate.ToString() == DeleteItemIsDetailTextBox.Text)
             {
                 del = it;
                 break;
             }
         }
         if (del != null)
         {
             tg.Items.Remove(del);
             string fn = TemplateHelper.SaveTemplateGroupAndPreviewFile(tg, Path.GetFileNameWithoutExtension(TemplateGroupFileName));
         }
         DeleteItemAliasTextBox.Text    = "";
         DeleteItemIsDetailTextBox.Text = "";
     }
 }
Example #18
0
        public void BuildSnippets_ShouldBeIncluded_InOrder()
        {
            // Arrange
            const string script1     = "abcdefg";
            const string script2     = "123456";
            var          scriptProps = new BaseBashBuildScriptProperties()
            {
                BuildScriptSnippets = new List <string>()
                {
                    script1, script2
                }
            };

            // Act
            var script = TemplateHelper.Render(TemplateHelper.TemplateResource.BaseBashScript, scriptProps);

            // Assert
            var indexOfScript1 = script.IndexOf(script1);
            var indexOfScript2 = script.IndexOf(script2);

            Assert.True(indexOfScript1 < indexOfScript2);
            Assert.DoesNotContain("Executing pre-build script", script);
            Assert.DoesNotContain("Executing post-build script", script);
        }
Example #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadSearchPars();
            str_Salary        = bindItems(JobAction.SalaryDegree, salary, "s");
            str_UpdateTime    = bindItems(JobAction.UpdateTime, updatetime, "t");
            str_Edu           = bindItems(JobAction.Edu, edu, "e");
            str_EmployeeCount = GetEmplyeeCountItems(employeeCount);
            str_Exp           = GetExpItems(exp);
            BindIndustry();

            salary = null;
            newUrl();
            str_Salary_Bx = string.Format("<a href=\"{0}\">不限</a>", curUrl);
            LoadSearchPars();

            edu = null;
            newUrl();
            str_Edu_Bx = string.Format("<a href=\"{0}\">不限</a>", curUrl);
            LoadSearchPars();

            updatetime = null;
            newUrl();
            str_UpdateTime_Bx = string.Format("<a href=\"{0}\">不限</a>", curUrl);
            LoadSearchPars();

            industry = null;
            newUrl();
            str_Industry_Bx = string.Format("<a href=\"{0}\">不限</a>", curUrl);
            LoadSearchPars();

            TemplateHelper helper = new TemplateHelper();

            htmlFooter = helper.GetPublicTemplate("indexbottom");

            BindList();
        }
        //private void scrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
        //{
        //    double h = e.NewSize.Height;


        //    //canvasMinHeight = this.ActualHeight - 60;
        //    //SetHeight();

        //    System.Diagnostics.Debug.WriteLine(e.NewSize.Height+" "+e.NewSize.Width + " "+rootTag + " "+currentTag);
        //    RedrawGraph();
        //}

        private void miNewFile_Click(object sender, RoutedEventArgs e)
        {
            UpdateCurrentTagByContextMenu();
            string         initDir = CfgPath.GetDirByTag(SelectedTag.Title, true);//新建文件,保证目录存在
            SaveFileDialog sf      = new SaveFileDialog();

            sf.InitialDirectory = initDir;

            sf.Filter = TemplateHelper.GetTemplateFileFilter();//"One文件(*.one)|*.one|Mind文件(*.xmind)|*.xmind";
            if (sf.ShowDialog() == true)
            {
                if (File.Exists(sf.FileName))
                {
                    MessageBox.Show("该文件已经存在" + sf.FileName, "文件名冲突", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                else
                {
                    FileInfo fi          = new FileInfo(sf.FileName);
                    string   tmplateFile = TemplateHelper.GetTemplateByExtension(fi.Extension);
                    if (tmplateFile != null && File.Exists(tmplateFile))
                    {
                        File.Copy(tmplateFile, sf.FileName);
                        AddUri(new List <string>()
                        {
                            sf.FileName
                        });
                        FileShell.OpenFile(sf.FileName);
                    }
                    else
                    {
                        File.Create(sf.FileName).Close();
                    }
                }
            }
        }
Example #21
0
        public void GeneratedScript_DoesNotConfigureAppInsights_IfAppInsightsEnvironmentVariable_NotSet(
            string nodeVersion)
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNodeVersion: nodeVersion);
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.NodeVersion = nodeVersion;
            var expected = new NodeBashBuildSnippetProperties(
                packageInstallCommand: NpmInstallCommand,
                runBuildCommand: "npm run build",
                runBuildAzureCommand: "npm run build:azure",
                hasProductionOnlyDependencies: true,
                productionOnlyPackageInstallCommand: string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                compressedNodeModulesFileName: null,
                compressNodeModulesCommand: null,
                appInsightsInjectCommand: null,
                appInsightsPackageName: "applicationinsights",
                appInsightsLoaderFileName: "oryx-appinsightsloader.js");

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.DoesNotContain("applicationinsights", snippet.BashBuildScriptSnippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
        public void GeneratedScript_DoesNotZipNodeModules_IfZipNodeModulesEnvironmentVariable_False()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "6.0.0");
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithBuildScript, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";

            var expected = new NodeBashBuildSnippetProperties
            {
                PackageInstallCommand               = NpmInstallCommand,
                PackageInstallerVersionCommand      = NodeConstants.NpmVersionCommand,
                NpmRunBuildCommand                  = "npm run build",
                NpmRunBuildAzureCommand             = "npm run build:azure",
                HasProdDependencies                 = true,
                HasDevDependencies                  = true,
                ProductionOnlyPackageInstallCommand = string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                CompressedNodeModulesFileName = null,
                CompressNodeModulesCommand    = null,
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
Example #23
0
        private bool IsChanged(ListViewItem item, Row row, SharedStringTable stringTable)
        {
            var changed = false;

            var displayName = TemplateHelper.GetCellValue(row, 1, stringTable);

            if (item.SubItems[1].Text != displayName && !string.IsNullOrEmpty(displayName))
            {
                item.SubItems[1].Text      = displayName;
                item.SubItems[1].ForeColor = ColorUpdate;
                changed = true;
            }

            var requiredLevel = TemplateHelper.GetCellValue(row, 4, stringTable);

            if (item.SubItems[4].Text != requiredLevel && !string.IsNullOrEmpty(requiredLevel))
            {
                item.SubItems[4].Text      = requiredLevel;
                item.SubItems[4].ForeColor = ColorUpdate;
                changed = true;
            }

            return(changed);
        }
Example #24
0
        public void GeneratedScript_HasNpmVersion_SpecifiedInPackageJson()
        {
            // Arrange
            var scriptGenerator = GetNodePlatformInstance(defaultNpmVersion: "6.0.0");
            var repo            = new MemorySourceRepo();

            repo.AddFile(PackageJsonWithNpmVersion, NodeConstants.PackageJsonFileName);
            var context = CreateScriptGeneratorContext(repo);

            context.LanguageVersion = "8.2.1";

            var expected = new NodeBashBuildSnippetProperties
            {
                PackageInstallCommand               = NpmInstallCommand,
                PackageInstallerVersionCommand      = NodeConstants.NpmVersionCommand,
                NpmRunBuildCommand                  = null,
                NpmRunBuildAzureCommand             = null,
                HasProductionOnlyDependencies       = false,
                ProductionOnlyPackageInstallCommand = string.Format(
                    NodeConstants.ProductionOnlyPackageInstallCommandTemplate,
                    NpmInstallCommand),
                CompressedNodeModulesFileName = null,
                CompressNodeModulesCommand    = null,
            };

            // Act
            var snippet = scriptGenerator.GenerateBashBuildScriptSnippet(context);

            // Assert
            Assert.NotNull(snippet);
            Assert.Equal(
                TemplateHelper.Render(TemplateHelper.TemplateResource.NodeBuildSnippet, expected),
                snippet.BashBuildScriptSnippet);
            Assert.DoesNotContain(".npmrc", snippet.BashBuildScriptSnippet); // No custom registry was specified
            Assert.True(scriptGenerator.IsCleanRepo(repo));
        }
Example #25
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var pythonPlatformDetectorResult = detectorResult as PythonPlatformDetectorResult;

            if (pythonPlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(PythonPlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            if (IsCondaEnvironment(pythonPlatformDetectorResult))
            {
                return(GetBuildScriptSnippetForConda(context, pythonPlatformDetectorResult));
            }

            var manifestFileProperties = new Dictionary <string, string>();

            // Write the platform name and version to the manifest file
            manifestFileProperties[ManifestFilePropertyKeys.PythonVersion] = pythonPlatformDetectorResult.PlatformVersion;

            var packageDir     = GetPackageDirectory(context);
            var virtualEnvName = GetVirtualEnvironmentName(context);
            var isPythonPackageCommandEnabled = _commonOptions.ShouldPackage;
            var pythonPackageWheelType        = GetPythonPackageWheelType(context);

            if (!isPythonPackageCommandEnabled && !string.IsNullOrWhiteSpace(pythonPackageWheelType))
            {
                throw new InvalidUsageException($"Option '{PythonPackageWheelPropertyKey}' can't exist" +
                                                $"without package command being enabled. Please provide --package along with wheel type");
            }

            if (isPythonPackageCommandEnabled &&
                !string.IsNullOrWhiteSpace(pythonPackageWheelType))
            {
                if (!string.Equals(pythonPackageWheelType.ToLower(), "universal"))
                {
                    throw new InvalidUsageException($"Option '{PythonPackageWheelPropertyKey}' can only have 'universal' as value.'");
                }

                manifestFileProperties[PythonManifestFilePropertyKeys.PackageWheel] = pythonPackageWheelType;
            }

            if (!string.IsNullOrWhiteSpace(packageDir) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                throw new InvalidUsageException($"Options '{TargetPackageDirectoryPropertyKey}' and " +
                                                $"'{VirtualEnvironmentNamePropertyKey}' are mutually exclusive. Please provide " +
                                                $"only the target package directory or virtual environment name.");
            }

            if (string.IsNullOrWhiteSpace(packageDir))
            {
                // If the package directory was not provided, we default to virtual envs
                if (string.IsNullOrWhiteSpace(virtualEnvName))
                {
                    virtualEnvName = GetDefaultVirtualEnvName(pythonPlatformDetectorResult);
                }

                manifestFileProperties[PythonManifestFilePropertyKeys.VirtualEnvName] = virtualEnvName;
            }
            else
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.PackageDir] = packageDir;
            }

            var virtualEnvModule = string.Empty;
            var virtualEnvParams = string.Empty;

            var pythonVersion = pythonPlatformDetectorResult.PlatformVersion;

            _logger.LogDebug("Selected Python version: {pyVer}", pythonVersion);

            if (!string.IsNullOrEmpty(pythonVersion) && !string.IsNullOrWhiteSpace(virtualEnvName))
            {
                (virtualEnvModule, virtualEnvParams) = GetVirtualEnvModules(pythonVersion);

                _logger.LogDebug(
                    "Using virtual environment {venv}, module {venvModule}",
                    virtualEnvName,
                    virtualEnvModule);
            }

            GetVirtualEnvPackOptions(
                context,
                virtualEnvName,
                out var compressVirtualEnvCommand,
                out var compressedVirtualEnvFileName);

            if (!string.IsNullOrWhiteSpace(compressedVirtualEnvFileName))
            {
                manifestFileProperties[PythonManifestFilePropertyKeys.CompressedVirtualEnvFile]
                    = compressedVirtualEnvFileName;
            }

            TryLogDependencies(pythonVersion, context.SourceRepo);

            var scriptProps = new PythonBashBuildSnippetProperties(
                virtualEnvironmentName: virtualEnvName,
                virtualEnvironmentModule: virtualEnvModule,
                virtualEnvironmentParameters: virtualEnvParams,
                packagesDirectory: packageDir,
                enableCollectStatic: _pythonScriptGeneratorOptions.EnableCollectStatic,
                compressVirtualEnvCommand: compressVirtualEnvCommand,
                compressedVirtualEnvFileName: compressedVirtualEnvFileName,
                runPythonPackageCommand: isPythonPackageCommandEnabled,
                pythonPackageWheelProperty: pythonPackageWheelType);
            string script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.PythonSnippet,
                scriptProps,
                _logger);

            return(new BuildScriptSnippet()
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,
            });
        }
Example #26
0
        public Result <ServiceResponse> SignUp(SignUpRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                Check.NotNullOrWhiteSpace(request.Email, "email");
                Check.NotNullOrEmpty(request.Password, "password");
                UserRepository.ValidatePassword(request.Email, request.Password, true);
                Check.NotNullOrWhiteSpace(request.DisplayName, "displayName");

                if (connection.Exists <UserRow>(
                        UserRow.Fields.Username == request.Email |
                        UserRow.Fields.Email == request.Email))
                {
                    throw new ValidationError("EmailInUse", Texts.Validation.CantFindUserWithEmail);
                }

                using (var uow = new UnitOfWork(connection))
                {
                    string salt = null;
                    var hash = UserRepository.GenerateHash(request.Password, ref salt);
                    var displayName = request.DisplayName.TrimToEmpty();
                    var email = request.Email;
                    var username = request.Email;

                    var fld = UserRow.Fields;
                    var userId = (int)connection.InsertAndGetID(new UserRow
                    {
                        Username = username,
                        Source = "sign",
                        DisplayName = displayName,
                        Email = email,
                        PasswordHash = hash,
                        PasswordSalt = salt,
                        IsActive = 0,
                        InsertDate = DateTime.Now,
                        InsertUserId = 1,
                        LastDirectoryUpdate = DateTime.Now
                    });

                    byte[] bytes;
                    using (var ms = new MemoryStream())
                        using (var bw = new BinaryWriter(ms))
                        {
                            bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                            bw.Write(userId);
                            bw.Flush();
                            bytes = ms.ToArray();
                        }

                    var token = Convert.ToBase64String(MachineKey.Protect(bytes, "Activate"));

                    var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ??
                                      Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");

                    var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t=");
                    activateLink = activateLink + Uri.EscapeDataString(token);

                    var emailModel = new ActivateEmailModel();
                    emailModel.Username = username;
                    emailModel.DisplayName = displayName;
                    emailModel.ActivateLink = activateLink;

                    var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString();
                    var emailBody = TemplateHelper.RenderTemplate(
                        MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel);

                    var message = new MailMessage();
                    message.To.Add(email);
                    message.Subject = emailSubject;
                    message.Body = emailBody;
                    message.IsBodyHtml = true;

                    var client = new SmtpClient();

                    if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory &&
                        string.IsNullOrEmpty(client.PickupDirectoryLocation))
                    {
                        var pickupPath = Server.MapPath("~/App_Data");
                        pickupPath = Path.Combine(pickupPath, "Mail");
                        Directory.CreateDirectory(pickupPath);
                        client.PickupDirectoryLocation = pickupPath;
                    }

                    uow.Commit();
                    UserRetrieveService.RemoveCachedUser(userId, username);
                    client.Send(message);

                    return new ServiceResponse();
                }
            }));
        }
Example #27
0
        /// <inheritdoc/>
        public BuildScriptSnippet GenerateBashBuildScriptSnippet(
            BuildScriptGeneratorContext context,
            PlatformDetectorResult detectorResult)
        {
            var dotNetCorePlatformDetectorResult = detectorResult as DotNetCorePlatformDetectorResult;

            if (dotNetCorePlatformDetectorResult == null)
            {
                throw new ArgumentException(
                          $"Expected '{nameof(detectorResult)}' argument to be of type " +
                          $"'{typeof(DotNetCorePlatformDetectorResult)}' but got '{detectorResult.GetType()}'.");
            }

            var versionMap = _versionProvider.GetSupportedVersions();

            string globalJsonSdkVersion = null;

            if (_commonOptions.EnableDynamicInstall)
            {
                var availableSdks = versionMap.Values;
                globalJsonSdkVersion = _globalJsonSdkResolver.GetSatisfyingSdkVersion(
                    context.SourceRepo,
                    detectorResult.PlatformVersion,
                    availableSdks);
            }

            var manifestFileProperties = new Dictionary <string, string>();

            manifestFileProperties[ManifestFilePropertyKeys.OperationId] = context.OperationId;
            manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreRuntimeVersion]
                = detectorResult.PlatformVersion;

            if (string.IsNullOrEmpty(globalJsonSdkVersion))
            {
                manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreSdkVersion]
                    = versionMap[detectorResult.PlatformVersion];
            }
            else
            {
                manifestFileProperties[ManifestFilePropertyKeys.DotNetCoreSdkVersion] = globalJsonSdkVersion;
            }

            var projectFile = dotNetCorePlatformDetectorResult.ProjectFile;

            if (string.IsNullOrEmpty(projectFile))
            {
                return(null);
            }

            var templateProperties = new DotNetCoreBashBuildSnippetProperties
            {
                ProjectFile   = projectFile,
                Configuration = GetBuildConfiguration(),
            };

            var script = TemplateHelper.Render(
                TemplateHelper.TemplateResource.DotNetCoreSnippet,
                templateProperties,
                _logger);

            SetStartupFileNameInfoInManifestFile(context, projectFile, manifestFileProperties);

            return(new BuildScriptSnippet
            {
                BashBuildScriptSnippet = script,
                BuildProperties = manifestFileProperties,

                // Setting this to false to avoid copying files like '.cs' to the destination
                CopySourceDirectoryContentToDestinationDirectory = false,
            });
        }
Example #28
0
        public Result <ServiceResponse> SignUp(SignUpRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                Check.NotNullOrWhiteSpace(request.Email, "email");
                Check.NotNullOrEmpty(request.Password, "password");
                UserRepository.ValidatePassword(request.Email, request.Password, true);
                Check.NotNullOrWhiteSpace(request.DisplayName, "displayName");

                if (connection.Exists <UserRow>(
                        UserRow.Fields.Username == request.Email |
                        UserRow.Fields.Email == request.Email))
                {
                    throw new ValidationError("EmailInUse", Texts.Validation.EmailInUse);
                }

                using (var uow = new UnitOfWork(connection))
                {
                    string salt = null;
                    var hash = UserRepository.GenerateHash(request.Password, ref salt);
                    var displayName = request.DisplayName.TrimToEmpty();
                    var email = request.Email;
                    var username = request.Email;

                    var fld = UserRow.Fields;
                    var userId = (int)connection.InsertAndGetID(new UserRow
                    {
                        Username = username,
                        Source = "sign",
                        DisplayName = displayName,
                        Email = email,
                        PasswordHash = hash,
                        PasswordSalt = salt,
                        IsActive = 0,
                        InsertDate = DateTime.Now,
                        InsertUserId = 1,
                        LastDirectoryUpdate = DateTime.Now
                    });

                    byte[] bytes;
                    using (var ms = new MemoryStream())
                        using (var bw = new BinaryWriter(ms))
                        {
                            bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                            bw.Write(userId);
                            bw.Flush();
                            bytes = ms.ToArray();
                        }

                    var token = Convert.ToBase64String(HttpContext.RequestServices
                                                       .GetDataProtector("Activate").Protect(bytes));

                    var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ??
                                      Request.GetBaseUri().ToString();

                    var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t=");
                    activateLink = activateLink + Uri.EscapeDataString(token);

                    var emailModel = new ActivateEmailModel();
                    emailModel.Username = username;
                    emailModel.DisplayName = displayName;
                    emailModel.ActivateLink = activateLink;

                    var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString();
                    var emailBody = TemplateHelper.RenderViewToString(HttpContext.RequestServices,
                                                                      MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel);

                    Common.EmailHelper.Send(emailSubject, emailBody, email);

                    uow.Commit();
                    UserRetrieveService.RemoveCachedUser(userId, username);

                    return new ServiceResponse();
                }
            }));
        }
        public Result <ServiceResponse> ForgotPassword(ForgotPasswordRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                if (string.IsNullOrEmpty(request.Email))
                {
                    throw new ArgumentNullException("email");
                }

                var user = connection.TryFirst <UserRow>(UserRow.Fields.Email == request.Email);
                if (user == null)
                {
                    throw new ValidationError("CantFindUserWithEmail", Texts.Validation.CantFindUserWithEmail);
                }

                byte[] bytes;
                using (var ms = new MemoryStream())
                    using (var bw = new BinaryWriter(ms))
                    {
                        bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                        bw.Write(user.UserId.Value);
                        bw.Flush();
                        bytes = ms.ToArray();
                    }

                var token = Convert.ToBase64String(MachineKey.Protect(bytes, "ResetPassword"));

                var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ??
                                  Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");

                var resetLink = UriHelper.Combine(externalUrl, "Account/ResetPassword?t=");
                resetLink = resetLink + Uri.EscapeDataString(token);

                var emailModel = new ResetPasswordEmailModel();
                emailModel.Username = user.Username;
                emailModel.DisplayName = user.DisplayName;
                emailModel.ResetLink = resetLink;

                var emailSubject = Texts.Forms.Membership.ResetPassword.EmailSubject.ToString();
                var emailBody = TemplateHelper.RenderTemplate(
                    MVC.Views.Membership.Account.ResetPassword.AccountResetPasswordEmail, emailModel);

                var message = new MailMessage();
                message.To.Add(user.Email);
                message.Subject = emailSubject;
                message.Body = emailBody;
                message.IsBodyHtml = true;

                var client = new SmtpClient();

                if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory &&
                    string.IsNullOrEmpty(client.PickupDirectoryLocation))
                {
                    var pickupPath = Server.MapPath("~/App_Data");
                    pickupPath = Path.Combine(pickupPath, "Mail");
                    Directory.CreateDirectory(pickupPath);
                    client.PickupDirectoryLocation = pickupPath;
                }

                client.Send(message);

                return new ServiceResponse();
            }));
        }
Example #30
0
        private async Task ProcessKill(JsonZKill.ZKillboard kill)
        {
            if (_lastPosted != kill.package.killID)
            {
                var bigKillGlobalValue = SettingsManager.GetLong("liveKillFeed", "bigKill");
                var bigKillGlobalChan  = SettingsManager.GetULong("liveKillFeed", "bigKillChannel");

                var killmailID              = kill.package.killmail.killmail_id;
                var killTime                = kill.package.killmail.killmail_time.ToString("dd.MM.yyyy hh:mm");
                var shipID                  = kill.package.killmail.victim.ship_type_id;
                var value                   = kill.package.zkb.totalValue;
                var victimCharacterID       = kill.package.killmail.victim.character_id;
                var victimCorpID            = kill.package.killmail.victim.corporation_id;
                var victimAllianceID        = kill.package.killmail.victim.alliance_id;
                var attackers               = kill.package.killmail.attackers;
                var finalBlowAttacker       = attackers.FirstOrDefault(a => a.final_blow);
                var finalBlowAttackerCorpId = finalBlowAttacker?.corporation_id;
                var finalBlowAttackerAllyId = finalBlowAttacker?.alliance_id;
                var isNPCKill               = kill.package.zkb.npc;

                var systemId = kill.package.killmail.solar_system_id;
                var npckill  = kill.package.zkb.npc;

                var postedGlobalBigKill = false;

                var rSystem = await APIHelper.ESIAPI.GetSystemData(Reason, systemId, false, !_enableCache);

                if (rSystem == null)
                {
                    //ESI fail - check back later
                    return;
                }

                var rVictimCorp = await APIHelper.ESIAPI.GetCorporationData(Reason, victimCorpID, false, !_enableCache);

                var rAttackerCorp = finalBlowAttackerCorpId.HasValue && finalBlowAttackerCorpId.Value > 0
                    ? await APIHelper.ESIAPI.GetCorporationData(Reason, finalBlowAttackerCorpId, false, !_enableCache)
                    : null;

                if (rAttackerCorp == null)
                {
                    isNPCKill = true;
                }
                var rVictimAlliance = victimAllianceID != 0 ? await APIHelper.ESIAPI.GetAllianceData(Reason, victimAllianceID, false, !_enableCache) : null;

                var rAttackerAlliance = finalBlowAttackerAllyId.HasValue && finalBlowAttackerAllyId.Value > 0
                    ? await APIHelper.ESIAPI.GetAllianceData(Reason, finalBlowAttackerAllyId)
                    : null;

                var sysName   = rSystem.name;
                var rShipType = await APIHelper.ESIAPI.GetTypeId(Reason, shipID);

                var rVictimCharacter = await APIHelper.ESIAPI.GetCharacterData(Reason, victimCharacterID, false, !_enableCache);

                var rAttackerCharacter = await APIHelper.ESIAPI.GetCharacterData(Reason, finalBlowAttacker?.character_id, false, !_enableCache);

                var systemSecurityStatus = Math.Round(rSystem.security_status, 1).ToString("0.0");

                // ulong lastChannel = 0;

                var dic = new Dictionary <string, string>
                {
                    { "{shipID}", shipID.ToString() },
                    { "{shipType}", rShipType?.name },
                    { "{iskValue}", value.ToString("n0") },
                    { "{systemName}", sysName },
                    { "{systemSec}", systemSecurityStatus },
                    { "{victimName}", rVictimCharacter?.name },
                    { "{victimCorpName}", rVictimCorp?.name },
                    { "{victimCorpTicker}", rVictimCorp?.ticker },
                    { "{victimAllyName}", rVictimAlliance?.name },
                    { "{victimAllyTicker}", rVictimAlliance == null ? null : $"<{rVictimAlliance.ticker}>" },
                    { "{attackerName}", rAttackerCharacter?.name },
                    { "{attackerCorpName}", rAttackerCorp?.name },
                    { "{attackerCorpTicker}", rAttackerCorp?.ticker },
                    { "{attackerAllyTicker}", rAttackerAlliance == null ? null : $"<{rAttackerAlliance.ticker}>" },
                    { "{attackerAllyName}", rAttackerAlliance?.name },
                    { "{attackersCount}", attackers.Length.ToString() },
                    { "{kmId}", killmailID.ToString() },
                    { "{isNpcKill}", isNPCKill.ToString() },
                    { "{timestamp}", killTime },
                };

                foreach (var i in SettingsManager.GetSubList("liveKillFeed", "groupsConfig"))
                {
                    var minimumValue     = Convert.ToInt64(i["minimumValue"]);
                    var minimumLossValue = Convert.ToInt64(i["minimumLossValue"]);
                    var allianceID       = Convert.ToInt32(i["allianceID"]);
                    var corpID           = Convert.ToInt32(i["corpID"]);
                    var bigKillValue     = Convert.ToInt64(i["bigKillValue"]);
                    var c = Convert.ToUInt64(i["discordChannel"]);
                    var sendBigToGeneral = Convert.ToBoolean(i["bigKillSendToGeneralToo"]);
                    var bigKillChannel   = Convert.ToUInt64(i["bigKillChannel"]);
                    var discordGroupName = i["name"];

                    if (c == 0)
                    {
                        await LogHelper.LogWarning($"Group {i.Key} has no 'discordChannel' specified! Kills will be skipped.", Category);

                        continue;
                    }

                    if (bigKillGlobalChan != 0 && bigKillGlobalValue != 0 && value >= bigKillGlobalValue && !postedGlobalBigKill)
                    {
                        postedGlobalBigKill = true;

                        if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailBig, dic, bigKillGlobalChan, discordGroupName))
                        {
                            await APIHelper.DiscordAPI.SendEmbedKillMessage(bigKillGlobalChan, new Color(0xFA2FF4), shipID, killmailID, rShipType.name, (long)value,
                                                                            sysName, systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name, rVictimCorp.name,
                                                                            rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                            rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null);
                        }

                        await LogHelper.LogInfo($"Posting Global Big Kill: {kill.package.killID}  Value: {value:n0} ISK", Category);
                    }

                    if (allianceID == 0 && corpID == 0)
                    {
                        if (value >= minimumValue)
                        {
                            if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailGeneral, dic, c, discordGroupName))
                            {
                                await APIHelper.DiscordAPI.SendEmbedKillMessage(c, new Color(0x00FF00), shipID, killmailID, rShipType.name, (long)value, sysName,
                                                                                systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name, rVictimCorp.name,
                                                                                rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null);
                            }

                            await LogHelper.LogInfo($"Posting Global Kills: {kill.package.killID}  Value: {value:n0} ISK", Category);
                        }
                    }
                    else
                    {
                        //ally & corp

                        //Losses
                        //Big
                        if (bigKillChannel != 0 && bigKillValue != 0 && value >= bigKillValue)
                        {
                            if (victimAllianceID == allianceID || victimCorpID == corpID)
                            {
                                dic.Add("{isLoss}", "true");
                                if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailBig, dic, bigKillChannel, discordGroupName))
                                {
                                    await APIHelper.DiscordAPI.SendEmbedKillMessage(bigKillChannel, new Color(0xD00000), shipID, killmailID, rShipType.name, (long)value,
                                                                                    sysName, systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name, rVictimCorp.name,
                                                                                    rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                    rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null, discordGroupName);

                                    if (sendBigToGeneral && c != bigKillChannel)
                                    {
                                        if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailBig, dic, c, discordGroupName))
                                        {
                                            await APIHelper.DiscordAPI.SendEmbedKillMessage(c, new Color(0xD00000), shipID, killmailID, rShipType.name, (long)value,
                                                                                            sysName,
                                                                                            systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name, rVictimCorp.name,
                                                                                            rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                            rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null, discordGroupName);
                                        }
                                    }
                                }

                                await LogHelper.LogInfo($"Posting     Big Loss: {kill.package.killID}  Value: {value:n0} ISK", Category);

                                continue;
                            }
                        }

                        //Common
                        if (minimumLossValue == 0 || minimumLossValue <= value)
                        {
                            if (victimAllianceID != 0 && victimAllianceID == allianceID || victimCorpID == corpID)
                            {
                                dic.Add("{isLoss}", "true");
                                if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailGeneral, dic, c, discordGroupName))
                                {
                                    await APIHelper.DiscordAPI.SendEmbedKillMessage(c, new Color(0xFF0000), shipID, killmailID, rShipType?.name, (long)value, sysName,
                                                                                    systemSecurityStatus, killTime, rVictimCharacter == null?rShipType?.name : rVictimCharacter?.name, rVictimCorp?.name,
                                                                                    rVictimAlliance == null? "" : $"[{rVictimAlliance?.ticker}]", isNPCKill, rAttackerCharacter?.name, rAttackerCorp?.name,
                                                                                    rAttackerAlliance == null?null : $"[{rAttackerAlliance?.ticker}]", attackers.Length, null, discordGroupName);
                                }

                                await LogHelper.LogInfo($"Posting         Loss: {kill.package.killID}  Value: {value:n0} ISK", Category);

                                continue;
                            }
                        }

                        //Kills
                        foreach (var attacker in attackers.ToList())
                        {
                            if (bigKillChannel != 0 && bigKillValue != 0 && value >= bigKillValue && !npckill)
                            {
                                if ((attacker.alliance_id != 0 && attacker.alliance_id == allianceID) || (allianceID == 0 && attacker.corporation_id == corpID))
                                {
                                    dic.Add("{isLoss}", "false");
                                    if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailBig, dic, bigKillChannel, discordGroupName))
                                    {
                                        await APIHelper.DiscordAPI.SendEmbedKillMessage(bigKillChannel, new Color(0x00D000), shipID, killmailID, rShipType.name,
                                                                                        (long)value, sysName, systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name,
                                                                                        rVictimCorp.name,
                                                                                        rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                        rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null, discordGroupName);

                                        if (sendBigToGeneral && c != bigKillChannel)
                                        {
                                            if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailBig, dic, c, discordGroupName))
                                            {
                                                await APIHelper.DiscordAPI.SendEmbedKillMessage(c, new Color(0x00D000), shipID, killmailID, rShipType.name, (long)value,
                                                                                                sysName, systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name,
                                                                                                rVictimCorp.name,
                                                                                                rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                                rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null, discordGroupName);
                                            }
                                        }

                                        await LogHelper.LogInfo($"Posting     Big Kill: {kill.package.killID}  Value: {value:#,##0} ISK", Category);
                                    }

                                    break;
                                }
                            }
                            else if (!npckill && attacker.alliance_id != 0 && allianceID != 0 && attacker.alliance_id == allianceID ||
                                     !npckill && allianceID == 0 && attacker.corporation_id == corpID)
                            {
                                dic.Add("{isLoss}", "false");
                                if (!await TemplateHelper.PostTemplatedMessage(MessageTemplateType.KillMailGeneral, dic, c, discordGroupName))
                                {
                                    await APIHelper.DiscordAPI.SendEmbedKillMessage(c, new Color(0x00FF00), shipID, killmailID, rShipType.name, (long)value, sysName,
                                                                                    systemSecurityStatus, killTime, rVictimCharacter == null?rShipType.name : rVictimCharacter.name, rVictimCorp.name,
                                                                                    rVictimAlliance == null? "" : $"[{rVictimAlliance.ticker}]", isNPCKill, rAttackerCharacter.name, rAttackerCorp.name,
                                                                                    rAttackerAlliance == null?null : $"[{rAttackerAlliance.ticker}]", attackers.Length, null, discordGroupName);
                                }

                                await LogHelper.LogInfo($"Posting         Kill: {kill.package.killID}  Value: {value:#,##0} ISK", Category);

                                break;
                            }
                        }
                    }
                }

                _lastPosted = killmailID;
            }
            else if (kill?.package != null && _lastPosted != 0 && _lastPosted == kill.package.killID)
            {
                await LogHelper.LogInfo($"Skipping kill: {kill.package.killID} as its been posted recently", Category);
            }
        }
Example #31
0
 //public string GetTemplateText(string name, string area = "")
 //{
 //    var fn = GetTemplateFilename(name, area);
 //    if (fn != null)
 //    {
 //        var file = new FileInfo(fn);
 //        return File.ReadAllText(file.FullName);
 //    }
 //    else
 //    {
 //        return null;
 //    }
 //}
 private TemplateHelper GetHelper(string area)
 {
     area = area.ToLower();
     if (!helpers.ContainsKey(area))
     {
         lock (helpers)
         {
             if (!helpers.ContainsKey(area))
             {
                 var helper = new TemplateHelper(area);
                 helper.Load(this.env);
                 helpers[area] = helper;
             }
         }
     }
     return helpers[area];
 }