protected bool verify_access() { bool access = false; string currentPage = new System.IO.FileInfo(HttpContext.Current.Request.Url.LocalPath).Name; //DeBug_Footer.Text = "Current: " + currentPage; if (currentPage.ToLower().Contains("access.aspx") || currentPage.ToLower().Contains("default.aspx") || currentPage.ToLower().Contains("user_profile.aspx")) { access = true; } else { foreach (MenuItem mi in Menu1.Items) { if (verify_access_items(mi, currentPage)) { access = true; break; } //DeBug_Footer.Text += "<br />" + mi.NavigateUrl.ToLower(); } } //DeBug_Footer.Text += "<br />URL: " + HttpContext.Current.Request.Url.AbsolutePath; //DeBug_Footer.Text += "<br />IsFile: " + HttpContext.Current.Request.Url.IsFile.ToString(); //DeBug_Footer.Text += "<br />Access: " + access.ToString(); return(access); }
public static void ExportData(this PrintableControlLink control, string path) { string fileExtenstion = new FileInfo(path).Extension; switch (fileExtenstion.ToLower()) { case ".xls": control.ExportToXls(path); break; case ".xlsx": control.ExportToXlsx(path, new XlsxExportOptions(TextExportMode.Text, true, true)); break; case ".rtf": control.ExportToRtf(path); break; case ".pdf": control.ExportToPdf(path); break; case ".html": control.ExportToHtml(path); break; case ".mht": control.ExportToMht(path); break; default: break; } }
public static ImageType CreateFromFileName(string fileName) { string fileExtension = new FileInfo(fileName).Extension; switch (fileExtension.ToLower()) { case ".png": return ImageType.Png; case ".gif": return ImageType.Gif; case ".jpg": case ".jpeg": return ImageType.Jpeg; } throw new NotSupportedException("Image type " + fileExtension + " is not supported."); }
private static void GenerateVirtualFlac(string file) { Init("Creating..."); string fileName = new FileInfo(file).Name; string aplDirectory = Directory.GetParent(file).FullName; string[] files = Directory.GetFiles(aplDirectory, "*.apl"); foreach (string f in files) { AplFile apl = new AplFile(f); if (apl.ImageFile.ToLower() != fileName.ToLower()) { Console.WriteLine(apl.ImageFile); Console.WriteLine(fileName); throw new VfgException("Invalid apl/ image combination"); } aplFiles_.Add(apl); } new VirtualFlacCreator(file, fileName, aplFiles_.ToArray()); Done(); }
/// <summary> Returns true if the directory path (not including a filename) is valid. /// /// </summary> /// <param name="context">The validation context.</param> /// <param name="input">The directory to validate.</param> /// <returns>Boolean value indicating whether the data is valid.</returns> /// <seealso cref="Owasp.Esapi.Interfaces.IValidator.GetValidDirectoryPath(string, string, bool)"> /// </seealso> public string GetValidDirectoryPath(string context, string input, bool allowNull) { String canonical = ""; try { if (IsEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + " is required", "(" + context + ") input is required"); } canonical = Esapi.Encoder().Canonicalize(input); // do basic validation Regex directoryNamePattern = ((SecurityConfiguration)Esapi.SecurityConfiguration()).GetValidationPattern("DirectoryName"); if (!directoryNamePattern.Match(canonical).Success) { throw new ValidationException(context + " is an invalid directory name", "Attempt to use a directory name (" + canonical + ") that violates the global rule in ESAPI.properties (" + directoryNamePattern.ToString() + ")"); } // get the canonical path without the drive letter if present String cpath = new FileInfo(canonical).Name.Replace("\\\\", "/"); String temp = cpath.ToLower(); if (temp.Length >= 2 && temp[0] >= 'a' && temp[0] <= 'z' && temp[1] == ':') { cpath = cpath.Substring(2); } // prepare the input without the drive letter if present String escaped = canonical.Replace("\\\\", "/"); temp = escaped.ToLower(); if (temp.Length >= 2 && temp[0] >= 'a' && temp[0] <= 'z' && temp[1] == ':') { escaped = escaped.Substring(2); } // the path is valid if the input matches the canonical path if (!escaped.Equals(cpath.ToLower())) { throw new ValidationException(context + " is an invalid directory name", "The input path does not match the canonical path (" + canonical + ")"); } } catch (IOException e) { throw new ValidationException(context + " is an invalid directory name", "Attempt to use a directory name (" + canonical + ") that does not exist"); } catch (EncodingException ee) { throw new IntrusionException(context + " is an invalid directory name", "Exception during directory validation", ee); } return canonical; }
/// <summary> /// This relative URL will be the key in the $templateCache entry. /// </summary> /// <param name="file"></param> /// <param name="serverRootPath"></param> /// <returns></returns> private string MakeRelativeUrl(String file, String serverRootPath) { //Make the path lowercase, but preserve casing for the file (apparently, that's how angular makes keys) var dir = new FileInfo(file).DirectoryName; file = file.Replace(dir, dir.ToLower()); return file.Substring(serverRootPath.Length).Replace("\\", "/"); //return file.Substring(serverRootPath.Length - templateRoot.Length).Replace("\\", "/"); }
static void CreateNode(string[] folder) { string dirName = new FileInfo(folder[0]).Name; dirName = dirName.ToUpper(); for (int c = 0; c < dirName.Length; c++) { if (c == 4) break; nodes[numNodesDone].type = nodes[numNodesDone].type + dirName[c]; } nodes[numNodesDone].filenameOffset = (uint)stringTable.Length; stringTable = stringTable + dirName.ToLower() + (char)0x00; string[] numFiles = Directory.GetFileSystemEntries(folder[0]); nodes[numNodesDone].numFileEntries = (ushort)(numFiles.Length + 2); nodes[numNodesDone].firstFileEntryOffset = (uint)totalNumFilesAdded; dirName = new FileInfo(folder[0]).Name; nodes[numNodesDone].foldernameHash = Hash(dirName); numNodesDone++; }
public ConverterTXT(string arquivo) { Auxiliar oAux = new Auxiliar(); NFe.ConvertTxt.ConversaoTXT oUniTxtToXml = new NFe.ConvertTxt.ConversaoTXT(); string pasta = new FileInfo(arquivo).DirectoryName; pasta = pasta.Substring(0, pasta.Length - 5); //Retirar a pasta \Temp do final - Wandrey 03/08/2011 string ccMessage = string.Empty; string ccExtension = "-nfe.err"; try { int emp = Empresas.FindEmpresaByThread(); /// /// exclui o arquivo de erro /// Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileName(Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.Nfe_TXT) + ccExtension)); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileName(Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.Nfe_TXT) + "-nfe-ret.xml")); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + Path.GetFileName(arquivo)); /// /// exclui o arquivo TXT original /// Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileNameWithoutExtension(arquivo) + "-orig.txt"); /// /// processa a conversão /// oUniTxtToXml.Converter(arquivo, pasta);//Empresas.Configuracoes[emp].PastaRetorno); //Deu tudo certo com a conversão? if (string.IsNullOrEmpty(oUniTxtToXml.cMensagemErro)) { /// /// danasa 8-2009 /// if (oUniTxtToXml.cRetorno.Count == 0) { ccMessage = "cStat=02\r\n" + "xMotivo=Falha na conversão. Sem informações para converter o arquivo texto"; oAux.MoveArqErro(arquivo, ".txt"); } else { // // salva o arquivo texto original // if (pasta.ToLower().Equals(Empresas.Configuracoes[emp].PastaXmlEnvio.ToLower()) || pasta.ToLower().Equals(Empresas.Configuracoes[emp].PastaValidar.ToLower())) { FileInfo ArqOrig = new FileInfo(arquivo); string vvNomeArquivoDestino = Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileNameWithoutExtension(arquivo) + "-orig.txt"; ArqOrig.MoveTo(vvNomeArquivoDestino); } ccExtension = "-nfe.txt"; ccMessage = "cStat=01\r\n" + "xMotivo=Convertido com sucesso. Foi(ram) convertida(s) " + oUniTxtToXml.cRetorno.Count.ToString() + " nota(s) fiscal(is)"; foreach (NFe.ConvertTxt.txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno) { /// /// monta o texto que será gravado no arquivo de aviso ao ERP /// ccMessage += Environment.NewLine + "Nota fiscal: " + txtClass.NotaFiscal.ToString("000000000") + " Série: " + txtClass.Serie.ToString("000") + " - ChaveNFe: " + txtClass.ChaveNFe; // move o arquivo XML criado na pasta Envio\Convertidos para a pasta Envio // ou // move o arquivo XML criado na pasta Validar\Convertidos para a pasta Validar string nomeArquivoDestino = Path.Combine(pasta, Path.GetFileName(txtClass.XMLFileName)); Functions.Move(txtClass.XMLFileName, nomeArquivoDestino); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + txtClass.ChaveNFe + Propriedade.ExtEnvio.Nfe); } } } else { /// /// danasa 8-2009 /// ccMessage = "cStat=99\r\n" + "xMotivo=Falha na conversão\r\n" + "MensagemErro=" + oUniTxtToXml.cMensagemErro; } } catch (Exception ex) { ccMessage = ex.Message; ccExtension = "-nfe.err"; } if (!string.IsNullOrEmpty(ccMessage)) { oAux.MoveArqErro(arquivo, ".txt"); if (ccMessage.StartsWith("cStat=02") || ccMessage.StartsWith("cStat=99")) { /// /// exclui todos os XML gerados na pasta Envio\convertidos somente se houve erro na conversão /// foreach (NFe.ConvertTxt.txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno) { Functions.DeletarArquivo(pasta + "\\convertidos\\" + Path.GetFileName(txtClass.XMLFileName)); } } /// /// danasa 8-2009 /// /// Gravar o retorno para o ERP em formato TXT com o erro ocorrido /// oAux.GravarArqErroERP(Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.Nfe_TXT) + ccExtension, ccMessage); } }
public void DownloadFile(documento doc, Forms.MyAccount form) { Thread t = new Thread(() => { if (!String.IsNullOrEmpty(doc.hash)) { if (String.IsNullOrEmpty(doc.name)) { doc.name = "Sem nome"; } if (AbcDoc != null) { String oldName = string.Empty; try { //recebe o arquivo do abcdoc oldName = AbcDoc.receberArquivo(doc.hash, Dir.TempDirectory); } catch { oldName = string.Empty; } if (!String.IsNullOrEmpty(oldName)) { String newFileName = Util.User.GetDirDownload() + doc.name; String newFileExtension = new FileInfo(oldName).Extension; String newName = newFileName + newFileExtension; if (File.Exists(newName)) { //cria um versionamento pro arquivo, pois ele ja existe Int32 count = 1; while (File.Exists(newFileName + "(" + count.ToString() + ")" + newFileExtension)) { count++; } newName = newFileName + "(" + count.ToString() + ")" + newFileExtension; } if (File.Exists(oldName) && !File.Exists(newName)) { File.Move(oldName, newName); if (File.Exists(newName)) { if (Addin.CurrentAccount.openDocument) { //faz a uniao das extensoes de documentos, planilhas e apresentacoes var union = Forms.MyAccount.wextensions .Concat(Forms.MyAccount.eextensions) .Concat(Forms.MyAccount.pextensions) .Concat(Forms.MyAccount.iextensions); if(union.Any(ext => ext.ToLower().Equals(newFileExtension.ToLower()))) { Process.Start(newName); } } } try { File.Delete(oldName); } catch { } } else { MessageBox.Show("Não foi possível completar o download. O arquivo é inválido."); } } else { MessageBox.Show("Não foi possível completar o download. Verifique sua conexão com a internet."); } } else { MessageBox.Show("Não foi possível completar o download. Verifique sua conexão com a internet."); } } else { MessageBox.Show("Não foi possível completar o download. O documento selecionado é inválido."); } form.Invoke((MethodInvoker)(() => form.buttonDownloadDocument.Enabled = true)); }); t.Start(); }
private void InitIcons(string text,string filename,string iconname,int index) { ListViewItem lvi = listView1.Items.Add(text); lvi.Tag = new FileInfo(filename).FullName; string ext = new FileInfo(filename).Extension; //MessageBox.Show(ext); Image ico = InitExtIcon(ext, iconname,index); if (ico != null && imageList2.Images.Keys.IndexOf(ext.ToLower() != ".exe" ? ext.Substring(1) : (iconname + "_" + index.ToString())) == -1) { imageList2.Images.Add(ext.ToLower() != ".exe" ? ext.Substring(1) : (iconname+"_"+index.ToString()), ico); } if (ext == "" || imageList2.Images.Keys.IndexOf(ext.ToLower() != ".exe" ? ext.Substring(1) : (iconname + "_" + index.ToString())) == -1) { lvi.ImageKey = "file"; } else { lvi.ImageKey = ext.ToLower() != ".exe" ? ext.Substring(1) : (iconname + "_" + index.ToString()); } listView1.DoubleClick += listView1_DoubleClick; }
/// <summary> /// Encrypts specified filepath /// </summary> /// <param name="filepath">the filepath to encrypt, file must be in the same directory as the PARAM.PFD</param> /// <returns>true if file is succesfully encrypted</returns> public bool Encrypt(string filepath) { try { if (!File.Exists(filepath)) { DoProgress(filepath + " Does not exist!", MessageType.Error); return false; } string name = new FileInfo(filepath).Name; if (!EntryExists(name)) { DoProgress("There is no \"" + name + "\" inside the PARAM.PFD Entries!", MessageType.Error); return false; } DoProgress("Initializing file stream..", MessageType.Info); byte[] data = null; using (FileStream fs = File.Open(filepath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { for (int i = 0; i < PFDEntries.entries.Count; i++) { if (PFDEntries.entries[i].file_name.ToLower() == name.ToLower()) { PFDEntry t = PFDEntries.entries[i]; t.file_size = (ulong) fs.Length; PFDEntries.entries[i] = t; break; } } data = Encrypt(fs, name); //DoProgress("Rehashing PARAM.PFD..", MessageType.Info); //bool x = ValidEntryHash(fs, name, true) && ValidFileCID(true) && ValidDHKCID2(true) && ValidBottomHash(true); fs.Dispose(); } if (data == null) return false; DoProgress("Writing Encrypted data to : " + filepath, MessageType.Info); File.WriteAllBytes(filepath, data); DoProgress(name + " is succesfully encrypted", MessageType.Info); return true; } catch (Exception ex) { DoProgress(ex.Message, MessageType.Error); return false; } }
public static string GetSolutionFileFullName(string fullPath) { string rootDir = new FileInfo(_dte.Solution.FullName).Directory.FullName; return fullPath.ToLower().Replace(rootDir.ToLower() + "\\", ""); }
protected void Page_Load(object sender, EventArgs e) { SecureCheck(); if (Session["userstatus"] == null) { Response.Redirect("logout.aspx", false); } if (Session["userid"] == null || Session["UserFullName"] == null) { identity_get_user(); } if (Session["UserFullName"] != null) { UserFullName.Text = Session["UserFullName"].ToString(); } else { UserFullName.Text = "n/a"; } ghFunctions.portalVersion = System.Configuration.ConfigurationManager.AppSettings["portal_version"]; #region dtUserOffSet if (ghFunctions.dtUserOffSet == 0) { /// Switch this to a user determined variable /// Possibly in the MasterPage Int32 dtOffSet = 5; DateTime dtCurrent = DateTime.Now; System.TimeZone localZone = System.TimeZone.CurrentTimeZone; if (localZone.IsDaylightSavingTime(dtCurrent)) { dtOffSet = 4; } else { dtOffSet = 5; } ghFunctions.dtUserOffSet = dtOffSet; } #endregion dtUserOffSet #region ARC Color lblMasterHeader.Text = "Portal - ARC"; masterColor = "#EEEEEE"; if (System.Configuration.ConfigurationManager.AppSettings["DBMode"] == "Stage") { lblMasterHeader.Text = "Stage - Portal - ARC"; masterColor = "orange"; } #endregion ARC Color if (!IsPostBack) { //Literal1.Text = Page.User.Identity.IsAuthenticated.ToString(); //Literal2.Text = Page.User.Identity.Name; #region Perform certain action if user is authenticated if (Page.User.Identity.IsAuthenticated) { Literal3.Text = ""; #region Load the Menu //Menue_Load(); PopulateMenu(this.Page.User.Identity.Name); #endregion Load the Menu #region If User is a Sys Admin we add more menu options #endregion If User is a Sys Admin we add more menu options if (Page.User.IsInRole("System Administrator") == true) { Literal3.Text += "System Administrator<br />"; Session["UserRole"] = "System Administrator"; Panel1.Visible = true; } if (Page.User.IsInRole("Administrator") == true) { Literal3.Text += "Administrator<br />"; Session["UserRole"] = "Administrator"; } if (Page.User.IsInRole("Manager") == true) { Literal3.Text += "Manager<br />"; Session["UserRole"] = "Manager"; } if (Page.User.IsInRole("Advisor") == true) { Literal3.Text += "Advisor<br />"; Session["UserRole"] = "Advisor"; } if (Page.User.IsInRole("Agent") == true) { Literal3.Text += "Agent<br />"; Session["UserRole"] = "Agent"; } if (Page.User.IsInRole("Client") == true) { Literal3.Text += "Client"; Session["UserRole"] = "Client"; if (Page.User.IsInRole("Capella") == true) { Literal3.Text += " | Capella"; Session["UserClient"] = "Capella"; } else if (Page.User.IsInRole("Troy") == true) { Literal3.Text += " | Troy"; Session["UserClient"] = "Troy"; } else if (Page.User.IsInRole("Strayer") == true) { Literal3.Text += " | Strayer"; Session["UserClient"] = "Strayer"; } else if (Page.User.IsInRole("Full Sail") == true) { Literal3.Text += " | Full Sail"; Session["UserClient"] = "Full Sail"; } Literal3.Text += "<br />"; } DBMode.Text = Connection.GetDBMode(); if (DBMode.Text == "Stage") { DBMode.ForeColor = System.Drawing.Color.Red; } else { DBMode.ForeColor = System.Drawing.Color.Green; } DBMode.Text += "|" + Connection.GetConnectionType(); } #endregion Perform certain action if user is authenticated //Simple Menu //G:\Documents and Settings\All Users\Desktop\Admin\Software\Web\dotNet\CSSFriendly_Adapter_1.0\CSSFriendly_1.0\Web\WalkThru //MenuLoad(); //PopulateMenu(DeBug_Footer, Menu1, mi); // The header bar that labels the menu MessageLabel.Text = String.Format("Page: {0} - {1}" , MyTitle , PageTitle ); // Highlight Active Menu..? lblTitleHeader.Text = " - " + PageTitle; Menu_Selected_Check(Menu1, PageTitle); /// This will verify that the user has access to the page /// This is done by checking that the page is in the Menu /// Change this so it's done through a query: is user allowed to see page /// This way we do not need to have the item in the menu section in order for the user to see it if (!verify_access() && Page.User.IsInRole("System Administrator") == false) { // Response.Redirect("access.aspx"); Response.Redirect("~/access.aspx?p=" + PageTitle, true); // Server.Transfer("~/access.aspx", false); // This crashes } string currentPage = new System.IO.FileInfo(HttpContext.Current.Request.Url.LocalPath).Name; if (!(currentPage.ToLower().Contains("user_profile.aspx")) && Session["userstatus"] != null && Session["userstatus"].ToString() == "5") { Response.Redirect("user_profile.aspx", false); Context.ApplicationInstance.CompleteRequest(); } } }
protected void Page_Load(object sender, EventArgs e) { // Modify the Nav Bar menus based on application status // Use Bootstrap icon: // glyphicon glyphicon-ok // glyphicon glyphicon-remove // glyphicon glyphicon-exclamation-sign Label navPage02 = (Label)LoginView1.FindControl("navPage02"); if (navPage02 != null) { // navPage02.CssClass = "glyphicon glyphicon-ok"; navPage02.CssClass = ""; } string currentPage = new System.IO.FileInfo(HttpContext.Current.Request.Url.LocalPath).Name; if ((currentPage.ToLower().Contains("page01") || currentPage.ToLower().Contains("page02") || currentPage.ToLower().Contains("page03") || currentPage.ToLower().Contains("page04") || currentPage.ToLower().Contains("page05") || currentPage.ToLower().Contains("page99") || currentPage.ToLower().Contains("submitted") || currentPage.ToLower().Contains("part01") || currentPage.ToLower().Contains("part02") || currentPage.ToLower().Contains("part03") || currentPage.ToLower().Contains("part04") || currentPage.ToLower().Contains("part05") )) { // Is this dangerous? What if we have an application cookie but no [userid] variable? if (Request.Cookies["application"] == null || Server.HtmlEncode(Request.Cookies["application"]["userid"]) != Context.User.Identity.GetUserId <int>().ToString()) { Response.Redirect("~/Default.aspx?err=MissingAppID"); } else { } } if (!IsPostBack) { // Hello, <%: Context.User.Identity.GetUserName() %>! | <%: GetUserRole() %> Label lblUserName = (Label)LoginView1.FindControl("lblUserName"); if (lblUserName != null) { UserManager manager = new UserManager(); var user = manager.FindById(Context.User.Identity.GetUserId <int>()); lblUserName.Text = user.FirstName; } //// //if (Context.User.IsInRole("Administrators") || Context.User.IsInRole("Managers") || Context.User.IsInRole("Call Center Managers")) //{ // Control navViewEmails = LoginView1.FindControl("navViewEmails"); if (navViewEmails != null) { navViewEmails.Visible = true; } // Control navViewUsers = LoginView1.FindControl("navViewUsers"); if (navViewUsers != null) { navViewUsers.Visible = true; } // if (Context.User.IsInRole("Administrators") || Context.User.IsInRole("Managers")) // { // Control nvaViewCenters = LoginView1.FindControl("nvaViewCenters"); if (nvaViewCenters != null) { nvaViewCenters.Visible = true; } // } // if (Context.User.IsInRole("Administrators")) // { // Control navViewUsersEmails = LoginView1.FindControl("navViewUsersEmails"); if (navViewUsersEmails != null) { navViewUsersEmails.Visible = true; } // Control navViewAgentEmail = LoginView1.FindControl("navViewAgentEmail"); if (navViewAgentEmail != null) { navViewAgentEmail.Visible = true; } // Control navViewHistoryLog = LoginView1.FindControl("navViewHistoryLog"); if (navViewHistoryLog != null) { navViewHistoryLog.Visible = true; } // //navViewHistoryLog // } //} Navigation_Menu(); Navigation_Menu_Add_Admin_Right(); } }
public async Task<bool> EnableBuildTimeConfigTransformations() { if (!CanEnableBuildTimeTransformations) return false; var dialogResult = MessageBox.Show(_ownerWindow, "Are you sure you want to enable build-time transformations?", "Enable build-time transformations? (Confirmation)", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dialogResult == DialogResult.Cancel) return false; _logger.LogInfo("Enabling config transformations."); Environment.CurrentDirectory = Project.GetDirectory(); if (!Project.Saved) Project.Save(); // 1. determine if web.config vs app.config var originalConfigFile = Project.GetConfigFile(); if (string.IsNullOrEmpty(ProjectProperties.AppCfgType)) { Guid? projectKind = !string.IsNullOrEmpty(Project.Kind) ? Guid.Parse(Project.Kind) : (Guid?)null; var webProjectTypes = new[] { ProjectTypes.WebSite, ProjectTypes.AspNetMvc10, ProjectTypes.AspNetMvc20, ProjectTypes.AspNetMvc30, ProjectTypes.AspNetMvc40, ProjectTypes.WebApplication }; var projectTypes = Project.GetProjectTypeGuids().Split(';').Select(Guid.Parse); if (projectKind.HasValue && (webProjectTypes.Contains(projectKind.Value) || projectTypes.Any(t => webProjectTypes.Contains(t)))) { ProjectProperties.AppCfgType = "Web"; } else ProjectProperties.AppCfgType = "App"; } if (string.IsNullOrEmpty(originalConfigFile)) { originalConfigFile = Path.Combine(Project.GetDirectory(), ProjectProperties.AppCfgType + ".config"); } var originalConfigFileName = new FileInfo(originalConfigFile).Name; // 2. determine if need to use inline transformations or bin transformations // >> if web or clickonce, inline is mandatory var inlineTransformations = ProjectProperties.InlineTransformations ?? originalConfigFileName.ToLower() == "web.config" ? true : false; if (!inlineTransformations && !string.IsNullOrEmpty(ProjectProperties.GetPropertyValue("PublishUrl"))) inlineTransformations = true; ProjectProperties.InlineTransformations = inlineTransformations; bool prepresult; // in nested: // 3. if inline transformations, determine config folder // 4. if inline transformations, move and/or create web.config and related transforms to config folder // 4b. update project XML for moved files // 4c. inject warning xml to base if (inlineTransformations) prepresult = await PrepEnableInlineBuildTimeConfigTransformations(); // create missing web.config and related transforms to config folder // also make sure that the project has the proper task added (as with the case of app.config non-clickonce) else prepresult = await PrepEnableBuildTimeConfigTransformationsForBin(); if (prepresult == false) return false; ProjectProperties.BuildTimeTransformsEnabled = true; // 5. inject target definition to project /* web app (this should already be in the project so don't add it): * <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> */ /* non-web app: * <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll"/> */ EnsureTransformXmlTaskInProject(); // ensure target is invoked on build // >> two parts for this: // >> 6) add a target that invokes the TransformXml task EnsureTransformXmlTarget(); // >> 7) ensure that the target gets invoked (either with Before/AfterBuild or DefaultTargets) // 8. save changes and reload project await Project.SaveProjectRoot(); return true; }