static void Main()
    {
        StringBuilder hay = new StringBuilder();

        for (int line = 0; line < 4; line++)
        {
            hay.Append(Console.ReadLine().Trim());
            hay.Append("\r\n");
        }

        string small = @">{1}-{5}>{1}";
        string medium = @">{2}-{5}>{1}";
        string large = @">{3}-{5}>{2}";

        int largeCount = Regex.Matches(hay.ToString(), large).Count;
        hay.Replace(">>>----->>", " ");
        int mediumCount = Regex.Matches(hay.ToString(), medium).Count;
        hay.Replace(">>----->", " ");
        int smallCount = Regex.Matches(hay.ToString(), small).Count;

        string decimalCount = "" + smallCount + mediumCount + largeCount;
        string binaryCount = Convert.ToString(int.Parse(decimalCount), 2);
        string binaryReversed = string.Join("", binaryCount.ToCharArray().Reverse());
        string binary = binaryCount + binaryReversed;

        Console.WriteLine(Convert.ToInt32(binary, 2));
    }
Exemple #2
0
 private static void Replace(StringBuilder str)
 {
     str.Replace("<a href=\"", "[URL=");
     str.Replace("\">","]");
     str.Replace("</a>", "[/URL]");
     Console.WriteLine(str.ToString());
 }
 static void Main()
 {
     byte n = byte.Parse(Console.ReadLine());
     StringBuilder carpet = new StringBuilder();
     carpet.Capacity = n + 2;
     carpet.Append('.', n/2 - 1);
     carpet.Append("/\\");
     carpet.Append('.', n/2 - 1);
     Console.WriteLine(carpet);
     for (byte i = 0; i < n/2 - 1; i++)
     {
         if((i & 1) == 0)
         {
             carpet.Insert(n/2, "  ");
         }
         else
         {
             carpet.Insert(n/2, "/\\");
         }
         carpet.Remove(n + 1, 1);
         carpet.Remove(0, 1);
         Console.WriteLine(carpet);
     }
     carpet.Replace('/','\\', 0, n/2);
     carpet.Replace('\\','/', n/2, n/2);
     Console.WriteLine(carpet);
     for (byte i = 0; i < n / 2 - 1; i++)
     {
         carpet.Remove(n / 2 - 1, 2);
         carpet.Append('.', 1);
         carpet.Insert(0, '.');
         Console.WriteLine(carpet);
     }
 }
    /// <summary>
    /// Turns the given full path into a relative one starting just above the given directory.
    /// For example, "GetRelativePath("C:/A/B/C", "B")" returns "B/C".
    /// Returns "null" if the given folder can't be found.
    /// </summary>
    /// <remarks>
    /// As a side effect, all '/' or '\' slashes will be changed
    /// to the correct directory separator char for this platform.
    /// </remarks>
    /// <param name="startFolder">
    /// The folder that will appear at the top of the returned path.
    /// </param>
    public static string GetRelativePath(string fullPath, string startFolder)
    {
        StringBuilder sb = new StringBuilder(fullPath);
        if ('/' != Path.DirectorySeparatorChar)
        {
            sb.Replace('/', Path.DirectorySeparatorChar);
        }
        if ('\\' != Path.DirectorySeparatorChar)
        {
            sb.Replace('\\', Path.DirectorySeparatorChar);
        }

        //Get the start of the given folder in the path string.
        int folderLoc = sb.ToString().IndexOf(Path.DirectorySeparatorChar +
                                              startFolder +
                                              Path.DirectorySeparatorChar);
        if (folderLoc < 0 && sb.ToString().StartsWith(startFolder + Path.DirectorySeparatorChar))
        {
            folderLoc = 0;
        }

        //If the given folder was found, cut out everything before that.
        if (folderLoc >= 0)
        {
            sb.Remove(0, folderLoc);
            if (sb[0] == Path.DirectorySeparatorChar)
                sb.Remove(0, 1);
            return sb.ToString();
        }
        else
        {
            return null;
        }
    }
    static void ExtractHTMLBody(string input)
    {
        StringBuilder bodyText = new StringBuilder();
        int textStart = 0;
        for (int i = textStart; i < input.Length - 1; i++)
        {
            if (input[i] == '<' || (input[i] == '<' && input[i + 1] == '/'))
            {
                while (input[i] != '>')
                {
                    i++;
                }
            }
            else
            {
                bodyText.Append(input[i]);
            }

            if (input[i] != '>' && input[i + 1] == '<')
            {
                bodyText.Append("\n");
            }
        }
        bodyText.Replace("\r\n", " ");
        bodyText.Replace("   ", " ").Replace("  ", " ");
        bodyText.Replace("   ", " ").Replace("  ", " ");

        Console.WriteLine("{0}", bodyText);
    }
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int step = int.Parse(Console.ReadLine());

        StringBuilder bits = new StringBuilder();

        for (int i = 0; i < n; i++)
        {
            int num = int.Parse(Console.ReadLine());
            string currentLineBits = Convert.ToString(num, 2).PadLeft(8, '0');
            bits.Append(currentLineBits);
        }

        for (int i = 0; i < bits.Length; i+=step)
        {
            char currentDigit = bits[i];

            if (currentDigit == '0')
            {
                bits.Replace('0', '1', i, 1);
            }
            else
            {
                bits.Replace('1', '0', i, 1);
            }
        }

        for (int i = 0; i < bits.Length; i+=8)
        {
            string current = bits.ToString().Substring(i, 8);
            int num = Convert.ToInt32(current, 2);
            Console.WriteLine(num);
        }
    }
Exemple #7
0
    public static bool InjectSVGViewer(string SVGPath, string virtualRoot)
    {
        try
        {
            if (System.IO.File.Exists(SVGPath))
            {
                StringBuilder contents = null;
                using (StreamReader sr = new StreamReader(SVGPath))
                {
                    contents = new StringBuilder(sr.ReadToEnd());
                }

                System.IO.File.Delete(SVGPath);

                string searchfor = "http://www.w3.org/1999/xlink\">";
                contents.Replace(searchfor, "http://www.w3.org/1999/xlink\" onload=\"init(evt)\" >");

                searchfor = "</svg>";
                contents.Replace(searchfor, "<script xlink:href=\"" + virtualRoot + "/Scripts/SVGzoom.js\"/>\n<script xlink:href=\"" + virtualRoot + "/Scripts/effect.js\"/>\n" + searchfor);

                using (StreamWriter sw = new StreamWriter(SVGPath, false, Encoding.Default, contents.Length))
                {
                    sw.Write(contents.ToString());
                    sw.Close();
                }
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }
 /// <summary>
 /// Replaces all directory separators with the correct one for the current platform (either / or \).
 /// </summary>
 public static string FixDirectorySeparators(string path)
 {
     StringBuilder sb = new StringBuilder(path);
     sb.Replace('/', Path.DirectorySeparatorChar);
     sb.Replace('\\', Path.DirectorySeparatorChar);
     return sb.ToString();
 }
Exemple #9
0
	/// <summary>
	/// Turns the given full path into a relative one starting just above the given directory.
	/// For example, "GetRelativePath("C:/A/B/C", "B")" returns "B/C".
	/// Returns "null" if the given folder can't be found.
	/// </summary>
	/// <remarks>
	/// As a side effect, all '/' or '\' slashes will be changed
	/// to the correct directory separator char for this platform.
	/// </remarks>
	/// <param name="startFolder">
	/// The folder that will appear at the top of the returned path.
	/// </param>
	public static string GetRelativePath(string fullPath, string startFolder)
	{
		StringBuilder sb = new StringBuilder(fullPath);
		if ('/' != Path.DirectorySeparatorChar)
		{
			sb.Replace('/', Path.DirectorySeparatorChar);
		}
		if ('\\' != Path.DirectorySeparatorChar)
		{
			sb.Replace('\\', Path.DirectorySeparatorChar);
		}
		
		int folderLoc = sb.ToString().IndexOf(Path.DirectorySeparatorChar +
											  startFolder +
											  Path.DirectorySeparatorChar);
		if (folderLoc >= 0)
		{
			sb.Remove(0, folderLoc);
			if (sb[0] == Path.DirectorySeparatorChar)
				sb.Remove(0, 1);
			return sb.ToString();
		}
		else
		{
			return null;
		}
	}
    protected void bt_Export_Click(object sender, EventArgs e)
    {
        BindGrid(true, false);

        string filename = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(lb_ReportTitle.Text.Trim() == "" ? "Export" : lb_ReportTitle.Text.Trim()));
        Response.Charset = "UTF-8";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        Page.EnableViewState = false;

        StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);

        try
        {
            string tmp0 = "<tr align=\"left\" valign=\"middle\" OnMouseOver=\"this.style.cursor='hand';this.originalcolor=this.style.backgroundColor;this.style.backgroundColor='#FFCC66';\" OnMouseOut=\"this.style.backgroundColor=this.originalcolor;\" style=\"height:18px;\">";
            string tmp1 = "<tr align=\"left\" valign=\"middle\" OnMouseOver=\"this.style.cursor='hand';this.originalcolor=this.style.backgroundColor;this.style.backgroundColor='#FFCC66';\" OnMouseOut=\"this.style.backgroundColor=this.originalcolor;\" style=\"background-color:White;height:18px;\">";
            StringBuilder outhtml = new StringBuilder(tw.ToString());
            outhtml = outhtml.Replace(tmp0, "<tr>");
            outhtml = outhtml.Replace(tmp1, "<tr>");
            outhtml = outhtml.Replace("&nbsp;", "");

            Response.Write(outhtml.ToString());
        }
        catch
        {
            Response.Write(tw.ToString());
        }
        Response.End();

        BindGrid(false, false);
    }
    static void Main()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append(Console.ReadLine());

        sb.Replace("-", "");
        sb.Replace(",", "");
        sb.Replace(".", "");

        BigInteger sum = 0;

        do
        {
            sum = 0;
            for (int i = 0; i < sb.Length; i++)
            {
                sum += (BigInteger)Char.GetNumericValue(sb[i]);
            }
            sb.Clear();
            sb.Append(sum);
        } while (sum > 9);

        Console.WriteLine(sum);
    }
 static void Main()
 {
     int numLines = int.Parse(Console.ReadLine());
     string indentation = Console.ReadLine();
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < numLines; i++)
     {
         if (i > 0) sb.Append(Environment.NewLine);
         sb.Append(Console.ReadLine());
     }
     sb.Replace("{", Environment.NewLine + "{" + Environment.NewLine);
     sb.Replace("}", Environment.NewLine + "}" + Environment.NewLine);
     int sbLen = 0;
     do
     {
         sbLen = sb.Length;
         sb.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
         sb.Replace("  "," ");
     } while (sbLen != sb.Length);
     string[] lines = sb.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
     string indent = "";
     for (int i = 0; i < lines.Length; i++)
     {
         lines[i] = lines[i].Trim();
         if (lines[i] == "") continue;
         if (lines[i] == "}")
             indent = indent.Remove(0, indentation.Length);
         Console.Write(indent);
         Console.WriteLine(lines[i]);
         if (lines[i] == "{")
             indent = indent + indentation;
     }
 }
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\text.txt");
        StringBuilder result = new StringBuilder();

        using (reader)
        {
            string line = reader.ReadLine();

            while ( line != null)
            {
                StringBuilder lineToResult = new StringBuilder();
                lineToResult.Append(line);

                int wordIndex = line.IndexOf("start");

                if (wordIndex == -1)
                {
                    line = reader.ReadLine();
                    continue;
                }
                else
                {
                    while (wordIndex != -1)
                    {
                        if (IsPossibleIndex(wordIndex - 1, line.Length) && IsPossibleIndex(wordIndex + 5, line.Length))
                        {
                            if (char.IsLetter(line[wordIndex - 1]) == false && char.IsLetter(line[wordIndex + 5]) == false)
                            {
                                lineToResult.Replace("start", "finish", wordIndex, 7);
                            }
                        }
                        else if (IsPossibleIndex(wordIndex - 1, line.Length))
                        {
                            if (char.IsLetter(line[wordIndex - 1]) == false)
                            {
                                lineToResult.Replace("start", "finish", wordIndex, 6);
                            }
                        }
                        else if (IsPossibleIndex(wordIndex + 5, line.Length))
                        {
                            if (char.IsLetter(line[wordIndex + 5]) == false)
                            {
                                lineToResult.Replace("start", "finish", wordIndex, 6);
                            }
                        }
                        wordIndex = line.IndexOf("start", wordIndex + 4);
                    }
                    result.AppendLine(lineToResult.ToString());
                }
                line = reader.ReadLine();
            }

            StreamWriter writer = new StreamWriter(@"..\..\result.txt");
            using (writer)
            {
                writer.Write(result.ToString());
            }
        }
    }
    static void Main()
    {
        int number = int.Parse(Console.ReadLine());

        List<int> bitsPositions = new List<int>();
        List<string> commands = new List<string>();

        while (true)
        {
            string bitPos = Console.ReadLine();

            if (bitPos == "quit")
            {
                break;
            }

            bitsPositions.Add(int.Parse(bitPos));

            string command = Console.ReadLine();
            commands.Add(command);
        }

        StringBuilder manipulate = new StringBuilder();
        string numberAsBits = Convert.ToString(number, 2).PadLeft(32, '0');
        manipulate.Append(numberAsBits);

        for (int i = 0; i < commands.Count; i++)
        {
            string currentCommand = commands[i];
            int pos = 31 - bitsPositions[i];

            switch (currentCommand)
            {
                case "flip":
                    if (manipulate[pos] == '0')
                    {
                        manipulate.Replace('0', '1', pos, 1);
                    }
                    else
                    {
                        manipulate.Replace('1', '0', pos, 1);
                    }
                    break;
                case "remove":
                    manipulate.Remove(pos, 1);
                    manipulate.Insert(0, '0');
                    break;
                case "insert":
                    manipulate.Remove(0, 1);
                    manipulate.Insert(pos, '1');
                    break;
            }
        }

        ulong result = Convert.ToUInt64(manipulate.ToString(), 2);
        Console.WriteLine(result);
    }
    private static void TagReplacer(string text)
    {
        StringBuilder builder = new StringBuilder(text);

        builder.Replace("<a href=\"", "[URL=");
        builder.Replace("\">", "]");
        builder.Replace("</a>", "[/URL]");
        Console.WriteLine(builder);
    }
    public override void ExecuteBuild()
    {
        var ProjectName = ParseParamValue("project");
        var ProjectPath = ParseParamValue("path");

        {
            var CSProjFileTemplate = ReadAllText(CombinePaths(CmdEnv.LocalRoot, "Engine", "Extras", "UnsupportedTools", "AutomationTemplate", "AutomationTemplate.Automation.xml"));
            StringBuilder CSProjBuilder = new StringBuilder(CSProjFileTemplate);
            CSProjBuilder.Replace("AutomationTemplate", ProjectName);

            {
                const string ProjectGuidTag = "<ProjectGuid>";
                int ProjectGuidStart = CSProjFileTemplate.IndexOf(ProjectGuidTag) + ProjectGuidTag.Length;
                int ProjectGuidEnd = CSProjFileTemplate.IndexOf("</ProjectGuid>", ProjectGuidStart);
                string OldProjectGuid = CSProjFileTemplate.Substring(ProjectGuidStart, ProjectGuidEnd - ProjectGuidStart);
                string NewProjectGuid = Guid.NewGuid().ToString("B");
                CSProjBuilder.Replace(OldProjectGuid, NewProjectGuid);
            }

            {
                const string OutputPathTag = "<OutputPath>";
                var OutputPath = CombinePaths(CmdEnv.LocalRoot, "Engine", "Binaries", "DotNET", "AutomationScripts");
                int PathStart = CSProjFileTemplate.IndexOf(OutputPathTag) + OutputPathTag.Length;
                int PathEnd = CSProjFileTemplate.IndexOf("</OutputPath>", PathStart);
                string OldOutputPath = CSProjFileTemplate.Substring(PathStart, PathEnd - PathStart);
                string NewOutputPath = ConvertSeparators(PathSeparator.Slash, UnrealBuildTool.Utils.MakePathRelativeTo(OutputPath, ProjectPath)) + "/";
                CSProjBuilder.Replace(OldOutputPath, NewOutputPath);
            }

            if (!DirectoryExists(ProjectPath))
            {
                CreateDirectory(ProjectPath);
            }
            WriteAllText(CombinePaths(ProjectPath, ProjectName + ".Automation.csproj"), CSProjBuilder.ToString());
        }

        {
            var PropertiesFileTemplate = ReadAllText(CombinePaths(CmdEnv.LocalRoot, "Engine", "Extras", "UnsupportedTools", "AutomationTemplate", "Properties", "AssemblyInfo.cs"));
            StringBuilder PropertiesBuilder = new StringBuilder(PropertiesFileTemplate);
            PropertiesBuilder.Replace("AutomationTemplate", ProjectName);

            const string AssemblyGuidTag = "[assembly: Guid(\"";
            int AssemblyGuidStart = PropertiesFileTemplate.IndexOf(AssemblyGuidTag) + AssemblyGuidTag.Length;
            int AssemblyGuidEnd = PropertiesFileTemplate.IndexOf("\")]", AssemblyGuidStart);
            string OldAssemblyGuid = PropertiesFileTemplate.Substring(AssemblyGuidStart, AssemblyGuidEnd - AssemblyGuidStart);
            string NewAssemblyGuid = Guid.NewGuid().ToString("D");
            PropertiesBuilder.Replace(OldAssemblyGuid, NewAssemblyGuid);

            string PropertiesPath = CombinePaths(ProjectPath, "Properties");
            if (!DirectoryExists(PropertiesPath))
            {
                CreateDirectory(PropertiesPath);
            }
            WriteAllText(CombinePaths(PropertiesPath, "AssemblyInfo.cs"), PropertiesBuilder.ToString());
        }
    }
 static void Main()
 {
     string html = "<p>Please visit <a href=\"http://academy.telerik.com\">our site</a> to choose a training course. Also visit <a href=\"www.devbg.org\">our forum</a> to discuss the courses.</p>";
         Console.WriteLine(Regex.Replace(html, "<a href=\"(.*?)\">(.*?)</a>", "[URL=$1]$2[/URL]"));
         StringBuilder replaced = new StringBuilder(html);
         replaced.Replace("<a href=\"", "[URL=");
         replaced.Replace("\">", "]");
         replaced.Replace("</a>", "[/URL]");
         Console.WriteLine(replaced.ToString());
 }
Exemple #18
0
 /// <summary>
 /// sql转换[]
 /// </summary>
 /// <param name="sqlstr"></param>
 /// <returns></returns>
 public string ToLikeSql(string sqlstr)
 {
     if (sqlstr == null) return "";
     StringBuilder str = new StringBuilder(sqlstr);
     str.Replace("'", "''");
     str.Replace("[", "[[]");
     str.Replace("%", "[%]");
     str.Replace("_", "[_]");
     return str.ToString();
 }
 static void Main(string[] args)
 {
     string fragment = @"<p>Please visit <a href=""http://academy.telerik. com"">our site</a> to choose a training course.Also visit <a href=""www.devbg.org"">our forum</a>to discuss the courses.</p>";
     StringBuilder str = new StringBuilder();
     str.Append(fragment);
     str.Replace("<a href=\"", "[URL=");
     str.Replace("\">", "]");
     str.Replace("</a>", "[/URL]");
     Console.WriteLine(str);
 }
Exemple #20
0
 static void Main()
 {
     Console.Write("Enter text: ");
     string n = Console.ReadLine();
     StringBuilder text = new StringBuilder();
     text.Append(n);
     text.Replace("<a href=\"", "[URL=");
     text.Replace("\">" , "]");
     text.Replace("</a>" , "[/URL]");
     Console.WriteLine(text);
 }
    private static string DateParse(string myDate)
    {
        StringBuilder myStringBuilder = new StringBuilder(myDate);
        //for not having problems with the directories:
        myStringBuilder.Replace(" ", "_"); //replace the ' ' (date-hour separator) for '_'
        myStringBuilder.Replace("/", "-"); //replace the '/' (date separator) for '-'
        myStringBuilder.Replace(":", "-"); //replace the ':' (hour separator) for '-'
        myStringBuilder.Replace(".", ""); //delete the '.' in a.m.: 13-01-2009_02-05-43_a.m.

        return myStringBuilder.ToString();
    }
    public string NormalizeErrorString(string error) {
        // Lets remove any path information.
        string path = Path.GetDirectoryName(AssemblyName);

        StringBuilder b = new StringBuilder(error);
        if (path.Length > 0) {
            b.Replace(path, "<path>");
        }
        b.Replace("\r\n", " ");

        return b.ToString(); 
    }
Exemple #23
0
    public StringBuilder datastore_create(string datastore_name, string host, string port, string database, string user)
    {
        FileInfo xmlfile = new FileInfo(HttpContext.Current.Server.MapPath("~/App_Data/datastore.xml"));
        StringBuilder sb = new StringBuilder(xmlfile.OpenText().ReadToEnd());
        sb.Replace("@name@", datastore_name);
        sb.Replace("@host@", host);
        sb.Replace("@port@", port);
        sb.Replace("@database@", database);
        sb.Replace("@user@", user);

        return sb;
    }
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        String root = Server.MapPath("~");

        String pgTemplate = root + "\\myPageTemplate.tmp";

        StringBuilder line = new StringBuilder();
        
        using (StreamReader rwOpenTemplate = new StreamReader(pgTemplate))
        {
            while (!rwOpenTemplate.EndOfStream)
            {
                line.Append(rwOpenTemplate.ReadToEnd());
            }
        }

        int ID = 0;
        string SaveFilePath = "";
        string SaveFileName = "";
        Random ran = new Random();
        ID = ran.Next();

        //Page Name Creator
        Title = ID.ToString() + "-" + txtTitle.Text.Replace(' ', '-').Replace('.', '-').Replace('#', '-').Replace('%', '-').Replace('&', '-').Replace('*', '-').Replace('@', '-').Replace('!', '-').Replace('|', '-').Replace(':', '-').Replace(';', '-').Replace(',', '-').Replace('/', '-').Replace('\\', '-').Replace('?', '-').Replace('<', '-').Replace('>', '-').Replace('"', '-').Replace('“', '-').Replace('”', '-');
        SaveFileName = "\\" + Title + ".aspx";
        SaveFilePath = root + "\\myPages\\" + SaveFileName;
        FileStream fsSave = File.Create(SaveFilePath);
        if (line != null)
        {
            line.Replace("[MetaTitle]", txtTitle.Text.Replace("<", "&lt;").Replace(">", "&gt;").Replace('"', ' ').Replace('"', ' '));
            line.Replace("[PageContent]", txtContent.Text);
            line.Replace("[MetaKeywords]", txtTags.Text.Replace('"', ' ').Replace('"', ' ').Replace('<', '-').Replace('>', '-'));
            //line.Replace("[Content]", txtContent.Text.Replace('"', ' ').Replace('"', ' ').Replace('<', '-').Replace('>', '-'));
            line.Replace("[ID]", ID.ToString());
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(fsSave);
                sw.Write(line);
               // lnkNewPage.Text = SaveFilePath;
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
            finally
            {
                sw.Close();                
            }
        }

    }
    static void Main()
    {
        StringBuilder text = new StringBuilder();
             text.Append("Microsoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.");
            string forbiddenWord = "PHP";
            string forbiddenWordTwo = "CLR";
            String forbiddenWordTree = "Microsoft";
            text.Replace(forbiddenWord, "***");
            text.Replace(forbiddenWordTwo, "***");
            text.Replace(forbiddenWordTree, "*********");

            Console.WriteLine(text);
    }
    private static void ProcessingCurrentCycle()
    {
        int s = 0;
        if (cycleIndex < bunnies.Count)
        {
            for (int i = 0; i <= cycleIndex; i++)
            {
                s += bunnies[i];
            }
        }
        else
        {
            return;
        }

        if (cycleIndex + 1 + s > bunnies.Count)
        {
            return;
        }

        BigInteger sum = 0;
        BigInteger product = 1;
        for (int i = cycleIndex + 1; i <= cycleIndex + s; i++)
        {
            sum += bunnies[i];
            product *= bunnies[i];
        }

        var result = new StringBuilder();
        result.Append(sum);
        result.Append(product);
        for (int i = cycleIndex + s + 1; i < bunnies.Count; i++)
        {
            result.Append(bunnies[i]);
        }

        if (result.ToString().Contains("0") || result.ToString().Contains("1"))
        {
            result.Replace("1", string.Empty);
            result.Replace("0", string.Empty);
        }

        bunnies.Clear();
        string newResult = result.ToString();
        bunnies.AddRange(newResult.Select(t => t - '0'));

        // Next cycle begins
        cycleIndex++;
        ProcessingCurrentCycle();
    }
    public string GetNumber()
    {
        int QuotationID = Int32.Parse(hidQuotationID.Text);
        List<string> list = LoadData(QuotationID);
        StringBuilder sb = new StringBuilder();
        sb.Append("<table><tr><td>SubTotal</td></tr><tr><td>Discount</td></tr><tr><td>Total</td></tr></table>");

        sb.Replace("SubTotal", list[0]);
        sb.Replace("Discount", list[1]);
        sb.Replace("Total", list[2]);

        lblTotalCost.Text = list[2];
        lblTotalCost2.Text = list[2];
        return sb.ToString();
    }
    protected void bt_Export_Click(object sender, EventArgs e)
    {
        gv_Summary.AllowPaging = false;
        BindGrid();

        string filename = HttpUtility.UrlEncode("汇总单导出_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        Response.Charset = "UTF-8";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        Page.EnableViewState = false;

        StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        gv_Summary.RenderControl(hw);

        StringBuilder outhtml = new StringBuilder(tw.ToString());
        outhtml = outhtml.Replace("&nbsp;", "").Replace("<br />", "");

        Response.Write(outhtml.ToString());
        Response.End();

        gv_Summary.AllowPaging = true;
        BindGrid();
    }
Exemple #29
0
 static void Main()
 {
     Console.ReadLine();
     string[] input = Console.ReadLine().Split(' ');
     int index = 0;
     bool loop = false;
     StringBuilder result = new StringBuilder();
     while (true)
     {
         if (index < input.Length && index >= 0)
         {
             if (input[index] == "*") loop = true;
             else
             {
                 int tempIndex = index;
                 index = int.Parse(input[index]);
                 result.Append(tempIndex + " ");
                 input[tempIndex] = "*";
                 continue;
             }
         }
         break;
     }
     if (loop)
     {
         if (index == 0) result.Insert(0, "(");
         else result.Replace(" " + index + " ", "(" + index + " ");
     }
     Console.WriteLine(result.ToString().TrimEnd() + ((loop) ? ")" : ""));
 }
 /// <summary>
 /// Prepares the Email and Sends to the Corresponding User
 /// </summary>
 /// <param name="message"></param>
 public static int PrepareAndSendEmail(AdminMessage message)
 {
     String template = AppUtil.ReadEmailTemplate(AppConstants.EmailTemplate.GENERAL_EMAIL_TEMPLATE);
     if (template.Length > 0)
     {
         message.FromEmail = String.Format("{0} {1}<{2}>", AppUtil.Encode(SessionCache.CurrentUser.FirstName), AppUtil.Encode(SessionCache.CurrentUser.LastName), SessionCache.CurrentUser.Author_email);
         message.Subject = AppUtil.Encode(message.Subject);
         message.MessageBody = AppUtil.FormatText(message.MessageBody);
         int sentMessageCounter = 0;
         foreach (PlanningPrepUser user in SessionCache.SelectedUsersForEmail)
         {
             String body = String.Format("Dear {0}, <br/><br/>{1}", AppUtil.Encode(user.Username), message.MessageBody);
             StringBuilder orgMessage = new StringBuilder(template);
             orgMessage.Replace(AppConstants.ETConstants.MESSAGE, body);
             try
             {
                 MailManager.SendMail(user.Author_email, String.Empty, String.Empty, message.FromEmail, message.Subject, orgMessage.ToString());
                 sentMessageCounter++;
             }
             catch { }
         }
         return sentMessageCounter;
     }
     return 0;
 }
        /// <summary>
        /// Processes the string strDrain into a calculated Drain dicepool and appropriate display attributes and labels.
        /// </summary>
        /// <param name="strDrain"></param>
        /// <param name="objImprovementManager"></param>
        /// <param name="drain"></param>
        /// <param name="attributeText"></param>
        /// <param name="valueText"></param>
        /// <param name="tooltip"></param>
        public void CalculateTraditionDrain(string strDrain, Improvement.ImprovementType drain, Label attributeText = null, Label valueText = null, ToolTip tooltip = null)
        {
            if (string.IsNullOrWhiteSpace(strDrain) || (attributeText == null && valueText == null && tooltip == null))
            {
                return;
            }
            StringBuilder objDrain        = valueText != null ? new StringBuilder(strDrain) : null;
            StringBuilder objDisplayDrain = attributeText != null ? new StringBuilder(strDrain) : null;
            StringBuilder objTip          = tooltip != null ? new StringBuilder(strDrain) : null;
            int           intDrain        = 0;

            // Update the Fading CharacterAttribute Value.
            foreach (string strAttribute in AttributeSection.AttributeStrings)
            {
                CharacterAttrib objAttrib = _objCharacter.GetAttribute(strAttribute);
                if (strDrain.Contains(objAttrib.Abbrev))
                {
                    string strAttribTotalValue = objAttrib.TotalValue.ToString();
                    objDrain?.Replace(objAttrib.Abbrev, strAttribTotalValue);
                    objDisplayDrain?.Replace(objAttrib.Abbrev, objAttrib.DisplayAbbrev);
                    objTip?.Replace(objAttrib.Abbrev, objAttrib.DisplayAbbrev + " (" + strAttribTotalValue + ")");
                }
            }
            if (objDrain != null)
            {
                try
                {
                    intDrain = Convert.ToInt32(Math.Ceiling((double)CommonFunctions.EvaluateInvariantXPath(objDrain.ToString())));
                }
                catch (XPathException) { }
                catch (OverflowException) { }    // Result is text and not a double
                catch (InvalidCastException) { } // Result is text and not a double
            }

            if (valueText != null || tooltip != null)
            {
                int intBonusDrain = ImprovementManager.ValueOf(_objCharacter, drain);
                if (intBonusDrain != 0)
                {
                    intDrain += intBonusDrain;
                    objTip?.Append(" + " + LanguageManager.GetString("Tip_Modifiers") + " (" + intBonusDrain.ToString() + ")");
                }
            }

            if (attributeText != null)
            {
                attributeText.Text = objDisplayDrain.ToString();
            }
            if (valueText != null)
            {
                valueText.Text = intDrain.ToString();
            }
            if (tooltip != null)
            {
                tooltip.SetToolTip(valueText, objTip.ToString());
            }
        }
Exemple #32
0
 /// <summary>
 /// Replaces all Greek characters with their ELOT 743 romanized equivalent.
 /// </summary>
 /// <param name="builder">The <see cref="StringBuilder"/> to work on.</param>
 /// <remarks>Not suitable for large bodies of text.
 /// <para>See also <seealso cref="GreekTransliterations"/>.</para></remarks>
 public static void ReplaceGreek(this StringBuilder builder)
 {
     foreach (var transliteration in GreekTransliterations)
     {
         foreach (var character in transliteration.Value)
         {
             builder?.Replace(character, transliteration.Key);
         }
     }
 }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            switch (6)
            {
            case (6):

                StringBuilder text = new StringBuilder(tainted_2);
                text.Replace("&", "&amp;");
                text.Replace("'", "&apos;");
                text.Replace(@"""", "&quot;");
                text.Replace("<", "&lt;");
                text.Replace(">", "&gt;");
                tainted_3 = text.ToString();

                break;

            default:
                break;
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string        connectionString = @"server=localhost;uid=sql_user;password=sql_password;database=dbname";
            SqlConnection dbConnection     = null;

            try {
                dbConnection = new SqlConnection(connectionString);
                dbConnection.Open();
                SqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #34
0
        public static string RemoveColorCodes(this string text)
        {
            if (!text.Contains("§"))
            {
                return(text);
            }

            var sb = new StringBuilder(text);

            sb.Replace("§0", string.Empty);
            sb.Replace("§1", string.Empty);
            sb.Replace("§2", string.Empty);
            sb.Replace("§3", string.Empty);
            sb.Replace("§4", string.Empty);
            sb.Replace("§5", string.Empty);
            sb.Replace("§6", string.Empty);
            sb.Replace("§7", string.Empty);
            sb.Replace("§8", string.Empty);
            sb.Replace("§9", string.Empty);
            sb.Replace("§a", string.Empty);
            sb.Replace("§b", string.Empty);
            sb.Replace("§c", string.Empty);
            sb.Replace("§d", string.Empty);
            sb.Replace("§e", string.Empty);
            sb.Replace("§f", string.Empty);

            return(sb.ToString());
        }
        public ActionResult DownForm(string keyValue, App_ProjectEntity entity)
        {
            //先创建文件
            List <App_TemplatesEntity> strChildEntitys = entity.F_Templates;
            string        filename    = "";
            string        PageTitle   = "";
            string        tempFId     = "";
            string        PageContent = "";
            string        FilePath    = "";
            StringBuilder sb0         = new StringBuilder();
            StringBuilder sb          = new StringBuilder();
            StringBuilder sb1         = new StringBuilder();
            string        zipFileName = entity.F_Name + DateTime.Now.ToString("yyyyMMddHHssmm");
            string        zipFold     = Server.MapPath("/templates/" + zipFileName + "/templates/");
            string        zipFoldJs   = Server.MapPath("/templates/" + zipFileName + "/js/");
            string        zipTemplate = "/templates/" + zipFileName + "/templates/";
            string        zipJs       = "/templates/" + zipFileName + "/js/";
            string        FID         = "";

            if (!Directory.Exists(zipFold))
            {
                Directory.CreateDirectory(zipFold);
            }
            if (!Directory.Exists(zipFoldJs))
            {
                Directory.CreateDirectory(zipFoldJs);
            }
            //打包

            foreach (App_TemplatesEntity item in strChildEntitys)
            {
                App_ContentEntity c1 = item.F_Content.ToObject <App_ContentEntity>();
                if (item.F_Type == "Page")
                {
                    if (sb0.ToString() != "")
                    {
                        StringBuilder strHtml = new StringBuilder();
                        using (StreamReader sr = new StreamReader(Server.MapPath("/templates/app/PageTemplate.html"), Encoding.GetEncoding("utf-8")))
                        {
                            strHtml = strHtml.Append(sr.ReadToEnd());
                            sr.Close();
                        }
                        //替换开始
                        strHtml = strHtml.Replace("{PageTitle}", PageTitle);
                        strHtml = strHtml.Replace("{PageContent}", sb0.ToString());
                        //替换结束

                        FilePath = Server.MapPath(zipTemplate + filename + ".html");
                        System.IO.FileInfo finfo = new System.IO.FileInfo(FilePath);
                        using (FileStream fs = finfo.OpenWrite())
                        {
                            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                            //把新的内容写到创建的HTML页面中
                            sw.WriteLine(strHtml);
                            sw.Flush();
                            sw.Close();
                        }
                    }
                    sb0.Remove(0, sb0.Length);
                    FID       = item.F_Id;
                    filename  = "page" + item.F_Id;
                    filename  = filename.Replace("-", "");
                    tempFId   = item.F_Id;
                    PageTitle = item.F_Name;
                }
                if (item.F_Type == "Component" && item.F_Value != "lrTab")
                {
                    if (item.F_Parent == tempFId)
                    {
                        if (item.F_Value == "lrHeader")
                        {
                            sb0.Append("<" + c1.size + " style=\"color:" + c1.color + "; text-align:" + c1.align + ";\">" + c1.text + "</" + c1.size + ">");
                        }
                        else if (item.F_Value == "lrList3")
                        {
                            sb0.Append("<div class=\"list lr-list-type3\"><ion-item class=\"item item-icon-left\"><i class=\"icon " + c1.icon + " " + c1.color + "\" ></i> <span>" + c1.name + "</span></ion-item></div>");
                        }
                        else if (item.F_Value == "lrList4")
                        {
                            sb0.Append("<div class=\"list lr-list-type3\"><ion-item class=\"item item-icon-left\"><i class=\"icon " + c1.icon + " " + c1.color + "\" ></i> <span>" + c1.name + "</span></ion-item></div>");
                        }
                        else if (item.F_Value == "lrInput")
                        {
                            sb0.Append("<label class=\"item item-input\"><input type=\"text\" placeholder=\"" + c1.placeholder + "\"></label>");
                        }
                        else if (item.F_Value == "lrParagraph")
                        {
                            sb0.Append("<p style=\"color:" + c1.color + ";font-size:" + c1.size + ";text-align:" + c1.align + ";\">" + c1.content + "</p>");
                        }
                        else if (item.F_Value == "lrBtn")
                        {
                            sb0.Append("<button style=\"color:" + c1.color + ";font-size:" + c1.size + ";text-align:" + c1.align + ";font-weight:500;\" class=\"button button-defaultbutton-standardbutton-positive\">" + c1.text + "</button>");
                        }
                    }
                }
                if (item.F_Value == "lrTabs")
                {
                    sb1.Append(".state('tab', {\r\n");
                    sb1.Append("url: '/tab',\r\n");
                    sb1.Append("abstract: true,\r\n");
                    sb1.Append("templateUrl: 'templates/tabs.html',\r\n");
                    sb1.Append("controller: 'lrTabsCtrl'\r\n");
                    sb1.Append("})");
                }
                else if (item.F_Value == "lrTab")
                {
                    sb1.Append(".state('tab" + item.F_Id + "', {\r\n");
                    sb1.Append("url: '/',\r\n");
                    sb1.Append("views: {\r\n");
                    sb1.Append("'tab-home': {\r\n");
                    sb1.Append("templateUrl: 'templates/.html'\r\n");
                    sb1.Append("}\r\n");
                    sb1.Append("}\r\n");
                    sb1.Append("})\r\n");
                    filename = "tabs";
                    if (item.F_Name == "首页")
                    {
                        sb.Append("<ion-tab title=\"首页\" icon-on=\"ion-ios-home\" icon-off=\"ion-ios-home-outline\" href=\"#/tab/DefaultPage\">\r\n");
                        sb.Append("<ion-nav-view name=\"tab-" + item.F_Id + "\"></ion-nav-view>");
                        sb.Append("</ion-tab>\r\n");
                    }
                    else if (item.F_Name == "实例")
                    {
                        sb.Append("<ion-tab title=\"实例\" icon-on=\"ion-ios-book\" icon-off=\"ion-ios-book-outline\" href=\"#/tab/DefaultPage\">\r\n");
                        sb.Append("<ion-nav-view name=\"tab-" + item.F_Id + "\"></ion-nav-view>");
                        sb.Append("</ion-tab>\r\n");
                    }
                    else if (item.F_Name == "通知")
                    {
                        sb.Append("<ion-tab title=\"通知\" icon-on=\"ion-ios-bell\" icon-off=\"ion-ios-bell-outline\" href=\"#/tab/DefaultPage\">\r\n");
                        sb.Append("<ion-nav-view name=\"tab-" + item.F_Id + "\"></ion-nav-view>");
                        sb.Append("</ion-tab>\r\n");
                    }
                    else if (item.F_Name == "我的")
                    {
                        sb.Append("<ion-tab title=\"我的\" icon-on=\"ion-ios-person\" icon-off=\"ion-ios-person-outline\" href=\"#/tab/DefaultPage\">\r\n");
                        sb.Append("<ion-nav-view name=\"tab-" + item.F_Id + "\"></ion-nav-view>");
                        sb.Append("</ion-tab>\r\n");
                    }
                }
            }

            StringBuilder strHtml1 = new StringBuilder();

            using (StreamReader sr = new StreamReader(Server.MapPath("/templates/app/tabs.html"), Encoding.GetEncoding("utf-8")))
            {
                strHtml1 = strHtml1.Append(sr.ReadToEnd());
                sr.Close();
            }
            //替换开始

            strHtml1 = strHtml1.Replace("{PageContent}", sb.ToString());
            //替换结束

            FilePath = Server.MapPath(zipTemplate + filename + ".html");
            System.IO.FileInfo finfo1 = new System.IO.FileInfo(FilePath);
            using (FileStream fs = finfo1.OpenWrite())
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(strHtml1);
                sw.Flush();
                sw.Close();
            }
            //JS替换
            //1.
            strHtml1.Remove(0, strHtml1.Length);
            //System.IO.File.Copy(Server.MapPath("/templates/app/hengtex-app.js"), Server.MapPath(zipJs));

            using (StreamReader sr = new StreamReader(Server.MapPath("/templates/app/hengtex-app.js"), Encoding.GetEncoding("utf-8")))
            {
                strHtml1 = strHtml1.Append(sr.ReadToEnd());
                sr.Close();
            }
            FilePath = Server.MapPath(zipJs + "hengtex-app.js");
            finfo1   = new System.IO.FileInfo(FilePath);
            using (FileStream fs = finfo1.OpenWrite())
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(strHtml1);
                sw.Flush();
                sw.Close();
            }
            //2.
            strHtml1.Remove(0, strHtml1.Length);

            using (StreamReader sr = new StreamReader(Server.MapPath("/templates/app/hengtex-controllers.js"), Encoding.GetEncoding("utf-8")))
            {
                strHtml1 = strHtml1.Append(sr.ReadToEnd());
                sr.Close();
            }
            //替换开始

            strHtml1 = strHtml1.Replace("{FID}", FID);
            //替换结束

            FilePath = Server.MapPath(zipJs + "hengtex-controllers.js");
            finfo1   = new System.IO.FileInfo(FilePath);
            using (FileStream fs = finfo1.OpenWrite())
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(strHtml1);
                sw.Flush();
                sw.Close();
            }
            //3.
            strHtml1.Remove(0, strHtml1.Length);
            strHtml1 = new StringBuilder();
            using (StreamReader sr = new StreamReader(Server.MapPath("/templates/app/hengtex-uirouter.js"), Encoding.GetEncoding("utf-8")))
            {
                strHtml1 = strHtml1.Append(sr.ReadToEnd());
                sr.Close();
            }
            //替换开始

            strHtml1 = strHtml1.Replace("{RouterStr}", sb1.ToString());
            //替换结束

            FilePath = Server.MapPath(zipJs + "hengtex-uirouter.js");
            finfo1   = new System.IO.FileInfo(FilePath);
            using (FileStream fs = finfo1.OpenWrite())
            {
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(strHtml1);
                sw.Flush();
                sw.Close();
            }
            ZipDirectory(Server.MapPath("/templates/" + zipFileName), Server.MapPath("/templates/"), "", false);
            var fieldItem = new
            {
                path = zipFileName,
            };

            return(this.ToJsonResult(fieldItem));
        }
        /// <summary>
        /// Draws an XML node
        /// </summary>
        /// <param name="node"></param>
        /// <param name="einzug">current indentation</param>
        /// <param name="newLineNeeded"></param>
        /// <param name="parentWasInvalid">If True, then the parent node was already so faulty that this node no longer needs to be checked against DTD errors.</param>
        /// <returns></returns>
        private string GetNodeAlsQuellText(System.Xml.XmlNode node, string einzug, bool newLineNeeded, bool parentWasInvalid, bool positionAlreadyCheckedAsOk, ref bool nodeInvalid)
        {
            if (node is XmlWhitespace)
            {
                return(string.Empty); // don't paint Whitespace
            }
            if (node is XmlComment)
            {
                return($"&lt;!--{node.InnerText}--&gt;");
            }

            var          sourceCode = new StringBuilder();
            const string indentPlus = "&nbsp;&nbsp;&nbsp;&nbsp;";
            Colors       nodeColor;

            string nodeErrorMsg;

            if (parentWasInvalid)
            {
                // the parent node was already so invalid that this node no longer needs to be checked against DTD errors
                nodeInvalid  = true;
                nodeErrorMsg = null; //"parent-Node already invalid";
                nodeColor    = Colors.Undefined;
            }
            else
            {
                var checker = _xmlRules.DtdChecker;
                if (checker.IsXmlNodeOk(node, positionAlreadyCheckedAsOk))
                {
                    nodeInvalid  = false;
                    nodeErrorMsg = null;
                    nodeColor    = Colors.Black;
                }
                else
                {
                    nodeInvalid  = true;
                    nodeErrorMsg = checker.ErrorMessages;
                    nodeColor    = Colors.Red;
                }
            }

            var renderType = _xmlRules.DisplayType(node);

            switch (renderType)
            {
            case DisplayTypes.FloatingElement:
            case DisplayTypes.OwnRow:
                break;

            default:
                throw new ApplicationException("unknown render type: " + _xmlRules.DisplayType(node));
            }

            if (newLineNeeded || renderType == DisplayTypes.OwnRow)
            {
                sourceCode.Append(StartNewLine() + einzug);
            }

            sourceCode.Append($"<span style=\"{GetCss(nodeColor)}\">"); // start node color

            if (node is XmlText)                                        // is text node
            {
                var nodetext = new StringBuilder(node.Value);
                nodetext.Replace("\t", " ");
                nodetext.Replace("\r\n", " ");
                nodetext.Replace("  ", " ");
                sourceCode.Append(System.Web.HttpUtility.HtmlEncode(nodetext.ToString()));
            }
            else  // not a text node
            {
                var closingTagVisible = _xmlRules.HasEndTag(node);

                sourceCode.Append($"&lt;{node.Name}{GetAttributeAsSourcecode(node.Attributes)}{(closingTagVisible ? "" : "/")}&gt;");
                sourceCode.Append(GetChildrenAsSourceCode(node.ChildNodes, einzug + indentPlus, true, nodeInvalid, false)); // paint children

                if (closingTagVisible)
                {
                    sourceCode.Append(StartNewLine() + einzug);
                    sourceCode.Append($"&lt;/{node.Name}&gt;");
                }
            }

            sourceCode.Append("</span>"); // end node color

            if (nodeErrorMsg != null)
            {
                this._errorsAsHtml.Append($"<li>{this._lineNumber:000000}: {System.Web.HttpUtility.HtmlEncode(nodeErrorMsg)}</li>");
            }

            return(sourceCode.ToString());
        }
Exemple #37
0
        /// <summary>生成DAL代码
        /// 基于UsTeam数据库操作类
        /// </summary>
        /// <param name="ns">命名空间</param>
        /// <param name="tabname">表名</param>
        /// <param name="classname">类名</param>
        /// <param name="connstr">数据库连接字符串</param>
        /// <returns></returns>
        public static string GenAllCode(string ns, string tabname, string classname, string connstr)
        {
            StringBuilder sb = new StringBuilder();


            MySqlConnection conn = new MySqlConnection(connstr);

            conn.Open();
            string db = string.Empty;

            string[] strdb = connstr.Split(';');
            for (int i = 0; i < strdb.Length; i++)
            {
                if (strdb[i].ToLower().Contains("database"))
                {
                    db = strdb[i].Split('=')[1].Trim();
                }
            }


            MySqlCommand cmd = new MySqlCommand("use information_schema; select * from columns where TABLE_SCHEMA='" + db + "' and table_name='" + tabname + "'", conn);

            //MySqlCommand cmd = new MySqlCommand("use information_schema; select * from columns where table_name='" + tabname + "'", conn);

            DataTable dt = new DataTable();

            dt.Load(cmd.ExecuteReader());

            var q = from a in dt.AsEnumerable()
                    where a.Field <string>("TABLE_NAME") == tabname
                    orderby a.Field <UInt64>("ORDINAL_POSITION")
                    select new
            {
                字段名  = a.Field <string>("COLUMN_NAME"),
                类型   = a.Field <string>("DATA_TYPE"),
                字段说明 = a.Field <string>("COLUMN_COMMENT"),
                默认值  = a.Field <string>("COLUMN_DEFAULT"),
            };


            string        insertfields = "";                  // 字段1,字段2,字段3,....
            string        insertvalues = "";                  // @字段1,@字段2,@字段3,....
            StringBuilder insertparam  = new StringBuilder(); //Add方法的参数添加

            string        updatefields = "";                  // 字段1=@字段1, 字段2=@字段2, .....
            StringBuilder updateparam  = new StringBuilder(); // Update方法的参数添加

            StringBuilder GetListArrayParam = new StringBuilder();

            StringBuilder ReaderBindParam = new StringBuilder();
            string        tmp_id          = ""; // 存储ID字段名

            for (int i = 0; i < q.Count(); i++)
            {
                var    row    = q.ElementAt(i);
                string leixin = Tools.DbTypeToCSharpType_MySQL(row.类型);


                if (row.字段名.ToLower() != "id")
                {
                    if (i == q.Count() - 1)
                    {
                        insertfields += row.字段名 + " ";
                        insertvalues += "@" + row.字段名 + " ";
                        updatefields += row.字段名 + "=@" + row.字段名 + " ";
                    }
                    else
                    {
                        insertfields += row.字段名 + ", ";
                        insertvalues += "@" + row.字段名 + ", ";
                        updatefields += row.字段名 + "=@" + row.字段名 + ", ";
                    }



                    insertparam.Append("            if (model." + row.字段名 + " == null)\r\n");
                    insertparam.Append("            {\r\n");
                    insertparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", DBNull.Value);\r\n");
                    insertparam.Append("            }\r\n");
                    insertparam.Append("            else\r\n");
                    insertparam.Append("            {\r\n");
                    if (leixin.ToLower() != "datetime")
                    {
                        insertparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", model." + row.字段名 + ");\r\n");
                    }
                    else
                    {
                        insertparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", model." + row.字段名 + ".ToString());\r\n");
                    }
                    insertparam.Append("            }\r\n");


                    updateparam.Append("            if (model." + row.字段名 + " == null)\r\n");
                    updateparam.Append("            {\r\n");
                    updateparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", DBNull.Value);\r\n");
                    updateparam.Append("            }\r\n");
                    updateparam.Append("            else\r\n");
                    updateparam.Append("            {\r\n");
                    if (leixin.ToLower() != "datetime")
                    {
                        updateparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", model." + row.字段名 + ");\r\n");
                    }
                    else
                    {
                        updateparam.Append("                 h.AddParameter(\"@" + row.字段名 + "\", model." + row.字段名 + ".ToString());\r\n");
                    }
                    updateparam.Append("            }\r\n");
                }
                else
                {
                    tmp_id = row.字段名;
                }


                string tmp = "";
                if (leixin.ToLower() == "string")
                {
                    tmp = "row[\"" + row.字段名 + "\"].ToString(),";
                }
                else
                {
                    tmp = leixin + ".Parse(row[\"" + row.字段名 + "\"].ToString()),";
                }
                GetListArrayParam.Append(row.字段名 + " = " + tmp);

                if (leixin.ToLower() == "string")
                {
                    ReaderBindParam.Append("            model." + row.字段名 + " = dataReader[\"" + row.字段名 + "\"].ToString();\r\n");
                }
                else
                {
                    ReaderBindParam.Append("            ojb = dataReader[\"" + row.字段名 + "\"];\r\n");
                    ReaderBindParam.Append("            if (ojb != null && ojb != DBNull.Value)\r\n");
                    ReaderBindParam.Append("            {\r\n");
                    ReaderBindParam.Append("                model." + row.字段名 + " = " + leixin + ".Parse(ojb.ToString());\r\n");
                    ReaderBindParam.Append("            }\r\n");
                }
            }
            updateparam.Append("            h.AddParameter(\"@id\", model." + tmp_id + ");\r\n");


            StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + @"\classtemp\MySQLDALTemp.txt");

            sb.Append(sr.ReadToEnd());
            sb = sb.Replace("@namespace@", ns);
            sb = sb.Replace("@tabname@", tabname);
            sb = sb.Replace("@createdate@", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sb = sb.Replace("@classname@", classname);

            sb = sb.Replace("@insertfields@", insertfields);
            sb = sb.Replace("@insertvalues@", insertvalues);
            sb = sb.Replace("@insertparam@", insertparam.ToString());

            sb = sb.Replace("@updatefields@", updatefields);
            sb = sb.Replace("@updateparam@", updateparam.ToString());

            sb = sb.Replace("@GetListArrayParam@", GetListArrayParam.ToString());

            sb = sb.Replace("@ReaderBindParam@", ReaderBindParam.ToString());

            return(sb.ToString());
        }
Exemple #38
0
        /// <summary>
        ///     Executes this ExtractSelectedPropertiesToStyleCommand.
        /// </summary>
        public override void Execute()
        {
            try
            {
                if (_addedNamespaces == null)
                {
                    _addedNamespaces = new List <string>();
                }
                else
                {
                    _addedNamespaces.Clear();
                }
                var selectedCodeBlock = Application.ActiveDocument.Selection as TextSelection;
                var XAML             = selectedCodeBlock.Text.Trim(WhiteSpaceCharacters);
                var nameTable        = new NameTable();
                var nameSpaceManager = new XmlNamespaceManager(nameTable);
                AddNameSpaces(XAML, nameSpaceManager);

                var xmlParseContext = new XmlParserContext(null, nameSpaceManager, null, XmlSpace.None);
                var document        = new XmlDocument();
                document.PreserveWhitespace = true;
                document.XmlResolver        = null;

                var xmlSettings = new XmlReaderSettings();
                xmlSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None;
                xmlSettings.ValidationType  = ValidationType.None;

                using (var reader = XmlReader.Create(new StringReader(XAML), xmlSettings, xmlParseContext))
                {
                    document.Load(reader);
                }

                var isSilverlight      = PtHelpers.IsProjectSilverlight(PtHelpers.GetProjectTypeGuids(Application.SelectedItems.Item(1).ProjectItem.ContainingProject).Split(';'));
                var silverlightVersion = string.Empty;
                if (isSilverlight)
                {
                    silverlightVersion = Application.ActiveDocument.ProjectItem.ContainingProject.Properties.Item("TargetFrameworkMoniker").Value.ToString().Replace("Silverlight,Version=v", String.Empty);
                }

                var extractSelectedPropertiesToStyle = new ExtractSelectedPropertiesToStyleWindow(document, isSilverlight, silverlightVersion);
                var result = extractSelectedPropertiesToStyle.ShowDialog();

                if (result ?? false)
                {
                    var sb             = new StringBuilder(10240);
                    var writerSettings = new XmlWriterSettings()
                    {
                        Indent = true,
                        NewLineOnAttributes = false,
                        OmitXmlDeclaration  = true
                    };

                    using (var writer = XmlWriter.Create(sb, writerSettings))
                    {
                        extractSelectedPropertiesToStyle.Document.Save(writer);
                    }

                    foreach (string item in _addedNamespaces)
                    {
                        sb.Replace(item, string.Empty);
                    }

                    sb.Replace(" >", ">");
                    sb.Replace("    ", " ");
                    sb.Replace("   ", " ");
                    sb.Replace("  ", " ");

                    var editPoint = selectedCodeBlock.TopPoint.CreateEditPoint();
                    selectedCodeBlock.Delete();
                    editPoint.Insert(sb.ToString());
                    sb.Length = 0;

                    sb.AppendFormat(
                        isSilverlight ? "<Style TargetType=\"{0}\"" : "<Style TargetType=\"{{x:Type {0}}}\"",
                        extractSelectedPropertiesToStyle.TypeName);

                    sb.AppendFormat(extractSelectedPropertiesToStyle.StyleName.IsNotNullOrEmpty() ?
                                    " x:Key=\"{0}\">" : ">",
                                    extractSelectedPropertiesToStyle.StyleName
                                    );

                    sb.Append(Environment.NewLine);

                    foreach (var item in extractSelectedPropertiesToStyle.ExtractedProperties)
                    {
                        if (item.IsSelected)
                        {
                            sb.AppendFormat("<Setter Property=\"{0}\" Value=\"{1}\" />{2}", item.PropertyName, item.PropertyValue, Environment.NewLine);
                        }
                    }

                    sb.AppendLine("</Style>");
                    Clipboard.Clear();
                    Clipboard.SetText(sb.ToString());
                    UIUtilities.ShowInformationMessage("Paste Style", "Place insertion point and paste created style into the resource section of a XAML document.");
                }
            }
            catch (XmlException ex)
            {
                UIUtilities.ShowExceptionMessage("Paste Style",
                                                 "Place insertion point and paste created style into the resource section of a XAML document.",
                                                 string.Empty,
                                                 ex.ToString());
            }
            catch (Exception ex)
            {
                UIUtilities.ShowExceptionMessage(Caption, ex.Message, string.Empty, ex.ToString());
            }
        }
Exemple #39
0
        /// <summary>
        /// Generate HTML fragment data string with header that is required for the clipboard.
        /// </summary>
        /// <param name="html">the html to generate for</param>
        /// <returns>the resulted string</returns>
        public static string GetHtmlDataString(string html)
        {
            var sb = new StringBuilder();

            sb.AppendLine(Header);
            //sb.AppendLine(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            sb.AppendLine(@"<!doctype html>");

            // if given html already provided the fragments we won't add them
            int fragmentStart, fragmentEnd;
            int fragmentStartIdx = html.IndexOf(StartFragment, StringComparison.OrdinalIgnoreCase);
            int fragmentEndIdx   = html.LastIndexOf(EndFragment, StringComparison.OrdinalIgnoreCase);

            // if html tag is missing add it surrounding the given html (critical)
            int htmlOpenIdx    = html.IndexOf("<html", StringComparison.OrdinalIgnoreCase);
            int htmlOpenEndIdx = htmlOpenIdx > -1 ? html.IndexOf('>', htmlOpenIdx) + 1 : -1;
            int htmlCloseIdx   = html.LastIndexOf("</html", StringComparison.OrdinalIgnoreCase);

            if (fragmentStartIdx < 0 && fragmentEndIdx < 0)
            {
                int bodyOpenIdx    = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
                int bodyOpenEndIdx = bodyOpenIdx > -1 ? html.IndexOf('>', bodyOpenIdx) + 1 : -1;

                if (htmlOpenEndIdx < 0 && bodyOpenEndIdx < 0)
                {
                    // the given html doesn't contain html or body tags so we need to add them and place start/end fragments around the given html only
                    sb.Append("<html><body>");
                    sb.Append(StartFragment);
                    fragmentStart = GetByteCount(sb);
                    sb.Append(html);
                    fragmentEnd = GetByteCount(sb);
                    sb.Append(EndFragment);
                    sb.Append("</body></html>");
                }
                else
                {
                    // insert start/end fragments in the proper place (related to html/body tags if exists) so the paste will work correctly
                    int bodyCloseIdx = html.LastIndexOf("</body", StringComparison.OrdinalIgnoreCase);

                    if (htmlOpenEndIdx < 0)
                    {
                        sb.Append("<html>");
                    }
                    else
                    {
                        sb.Append(html, 0, htmlOpenEndIdx);
                    }

                    if (bodyOpenEndIdx > -1)
                    {
                        sb.Append(html, htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0, bodyOpenEndIdx - (htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0));
                    }

                    sb.Append(StartFragment);
                    fragmentStart = GetByteCount(sb);

                    var innerHtmlStart = bodyOpenEndIdx > -1 ? bodyOpenEndIdx : (htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0);
                    var innerHtmlEnd   = bodyCloseIdx > -1 ? bodyCloseIdx : (htmlCloseIdx > -1 ? htmlCloseIdx : html.Length);
                    sb.Append(html, innerHtmlStart, innerHtmlEnd - innerHtmlStart);

                    fragmentEnd = GetByteCount(sb);
                    sb.Append(EndFragment);

                    if (innerHtmlEnd < html.Length)
                    {
                        sb.Append(html, innerHtmlEnd, html.Length - innerHtmlEnd);
                    }

                    if (htmlCloseIdx < 0)
                    {
                        sb.Append("</html>");
                    }
                }
            }
            else
            {
                // handle html with existing start\end fragments just need to calculate the correct bytes offset (surround with html tag if missing)
                if (htmlOpenEndIdx < 0)
                {
                    sb.Append("<html>");
                }
                int start = GetByteCount(sb);
                sb.Append(html);
                fragmentStart = start + GetByteCount(sb, start, start + fragmentStartIdx) + StartFragment.Length;
                fragmentEnd   = start + GetByteCount(sb, start, start + fragmentEndIdx);
                if (htmlCloseIdx < 0)
                {
                    sb.Append("</html>");
                }
            }

            // Back-patch offsets (scan only the header part for performance)
            sb.Replace("<<<<<<<<1", Header.Length.ToString("D9"), 0, Header.Length);
            sb.Replace("<<<<<<<<2", GetByteCount(sb).ToString("D9"), 0, Header.Length);
            sb.Replace("<<<<<<<<3", fragmentStart.ToString("D9"), 0, Header.Length);
            sb.Replace("<<<<<<<<4", fragmentEnd.ToString("D9"), 0, Header.Length);

            return(sb.ToString());
        }
Exemple #40
0
        public ActionResult CreatePdf(string ids)
        {
            Result <int> resultInfo = new Result <int>();
            List <long>  idList     = ids.SplitString(",").ToLongList();
            string       pathUrl    = "";

            using (ClientSiteClientProxy proxy = new ClientSiteClientProxy(ProxyEx(Request)))
            {
                string path     = ConfigurationManager.AppSettings["PDFPathUrl"];
                string fileName = path + "甲供物资申请单" + DateTime.Now.ToString("yyyymmddhhMMssfff");
                if (!Directory.Exists(fileName))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(fileName);
                    directoryInfo.Create();
                }
                string pdfPath = "";
                foreach (var item in idList)
                {
                    var result = proxy.GetTzSupplyMaterialApplyModel(item).Data;

                    if (result != null)
                    {
                        string pdfName = "";
                        pdfPath = "";
                        //物资信息
                        string html32 = "";
                        int    index  = 0;
                        foreach (var temp in result.TzSupMatApplyList)
                        {
                            index++;
                            html32 += "<tr class='tab-conten'><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + index + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.SupMatManagement + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'> " + temp.ProductName + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Specification + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.UnitPrice.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Number.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Money.ToString("0.00") + "</td><td style='border: 1px solid #D9D8D8;padding: 2px'>" + temp.SupplierName + "</td><td style='border: 1px solid #D9D8D8;padding: 2px;height: 40px;'>" + temp.Remark + "</td></tr>";
                        }
                        //---读html模板页面到stringbuilder对象里----
                        string[]      format   = new string[20];//定义和htmlyem标记数目一致的数组
                        StringBuilder htmltext = new StringBuilder();
                        try
                        {
                            string htmlPath = "~/HtmlTemp.html";
                            htmlPath = Server.MapPath(htmlPath);
                            using (StreamReader sr = new StreamReader(htmlPath))
                            {
                                String line;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    htmltext.Append(line);
                                }
                                sr.Close();
                            }
                            format[0]  = result.ApplyTitle;
                            format[1]  = result.ApplyUserName;
                            format[2]  = result.SupApplyTime.ToString("yyyy-mm-dd");
                            format[3]  = result.ApplyDepartment;
                            format[4]  = result.ContractCode;
                            format[5]  = result.ContractNumber;
                            format[6]  = result.ArrivalContacts;
                            format[7]  = result.ArrivalContactsTel;
                            format[8]  = result.ProjectName;
                            format[9]  = result.ApprovalNo;
                            format[10] = html32;
                            format[11] = result.TotleMoney.ToString("0.00");

                            format[12] = result.SupplierContacts;
                            format[13] = result.SupplierTel;
                            format[14] = result.SupplierAddress;

                            format[15] = result.ApprovalName;
                            format[16] = result.ApprovalDep;
                            format[17] = result.StateName;
                            format[18] = result.OperateTime.ToString("yyyy-mm-dd");
                            format[19] = result.SignNameUrl;
                            //----------替换htm里的标记为你想加的内容
                            for (int i = 0; i < 20; i++)
                            {
                                htmltext.Replace("$htmlformat[" + i + "]", format[i]);
                            }

                            string html = htmltext.ToString();
                            pdfName = result.ProjectName;
                            pdfPath = fileName + "/" + pdfName + ".pdf";
                            PDFHelper.ExportPDF(pdfPath, html);
                        }
                        catch
                        {
                            resultInfo.Flag = EResultFlag.Failure;
                        }
                    }
                }
                if (idList.Count == 1)
                {
                    pathUrl = pdfPath;
                }
                else
                {
                    string fileNamepath = System.IO.Path.GetFileName(fileName);
                    string paths        = fileName;
                    //using (ZipFile zip = ZipFile.Create(paths))
                    //{
                    //    zip.BeginUpdate();
                    //    zip.CommitUpdate();
                    //}
                    pathUrl = paths + ".zip";
                    Utility.CreateZip(fileName, pathUrl);
                }
                string pathName = System.IO.Path.GetFileName(pathUrl);

                return(Json(new
                {
                    Flag = resultInfo.Flag,
                    fileName = pathName,
                    download = pathUrl//文件下载链接
                }));
            }
        }
Exemple #41
0
        /*	[Test ReplaceKeys] String replace took 01:14.06
         *      [Test ReplaceKeys] Regex replace took 00:41.92
         *      [Test ReplaceKeys] StringBuilder replace took 01:13.35
         */
        static void TestStringReplaceKeys(string[] testdata)
        {
            const int basesize  = 10000;
            const int nreplaces = 3000;
            const int nrounds   = 1;

            var replaces = new List <string>(nreplaces + 100);

            for (int i = 0; i < nreplaces; i++)
            {
                replaces.Add(GenRandomString((random.Next(1000) + 10)));
            }

            var sb = new StringBuilder(GenRandomString(basesize));

            foreach (var s in replaces.Reverse <String>())
            {
                sb.Append(s);
            }

            string data = sb.ToString();

            Console.WriteLine("Finished generating data real");

            int sum = 0;

            RunTest("[Test ReplaceKeys] String replace",
                    new Action(() =>
            {
                for (int j = 0; j < nrounds; j++)
                {
                    foreach (var s in replaces)
                    {
                        sum += data.Replace(s, "bfhgf")[basesize + 1000];
                    }
                }
            }));

            RunTest("[Test ReplaceKeys] Regex replace",
                    new Action(() =>
            {
                for (int j = 0; j < nrounds; j++)
                {
                    foreach (var s in replaces)
                    {
                        sum += Regex.Replace(data, s, "bfhgf")[basesize + 1000];
                    }
                }
            }));

            RunTest("[Test ReplaceKeys] StringBuilder replace",
                    new Action(() =>
            {
                for (int j = 0; j < nrounds; j++)
                {
                    foreach (var s in replaces)
                    {
                        sum += sb.Replace(s, "bfhgf")[basesize + 1000];
                    }
                }
            }));

            Console.WriteLine("" + sum);
        }
Exemple #42
0
        /// <summary>
        /// 当待提取数据超过1天(提取历史数据)时 每次提取一天的数据
        /// </summary>
        private DataSet SelectByDay(DataBaseName database)
        {
            var connstr = Connectionstring.GetConnectionString(database);
            var sqlstr  = new StringBuilder();
            var tables  = TableFieldInfoDic.GetTableFieldInfoDic().GetSameDataBaseTableFieldInfos((int)database.ID);

            for (var i = 0; i < tables.Count; i++)
            {
                string str = string.Format(
                    "select {0} as ProjectCode,{1} as DataBaseNameID,{2} as sensorType,{3} as ACQUISITION_DATETIME,",
                    ProjectInfoDic.GetInstance().GetProjectInfo().ProjectCode,
                    database.ID,
                    tables[i].SensorType,
                    tables[i].AcqTime);
                sqlstr.Append(str);

                if (ConfigInfoTable.ConfigtableInfoDictionary.ContainsKey((int)database.ID))
                {
                    sqlstr.Append(tables[i].SensorID).Append(",");
                }
                else
                {
                    if (!string.IsNullOrEmpty(tables[i].ModuleNo))
                    {
                        sqlstr.Append(tables[i].ModuleNo).Append(",");
                    }

                    if (!string.IsNullOrEmpty(tables[i].ChannelId))
                    {
                        sqlstr.Append(tables[i].ChannelId).Append(",");
                    }
                    else
                    {
                        sqlstr.Append(string.Format("{0} as channelId", 1)).Append(",");
                    }

                    if (!string.IsNullOrEmpty(tables[i].OtherFlag))
                    {
                        sqlstr.Append(tables[i].OtherFlag).Append(",");
                    }
                }

                Type t = tables[i].GetType();
                for (int j = 1; j <= tables[i].ValueNameCount; j++)
                {
                    System.Reflection.PropertyInfo propertyInfo = t.GetProperty(FieldNamestr + j);
                    if (!string.IsNullOrEmpty(propertyInfo.GetValue(tables[i], null).ToString()))
                    {
                        sqlstr.Append(propertyInfo.GetValue(tables[i], null)).Append(",");
                    }
                }
                sqlstr.Replace(',', ' ', sqlstr.Length - 1, 1);
                sqlstr.Append("from ")
                .Append(tables[i].TableName)
                .Append(" where ")
                .Append(tables[i].AcqTime)
                .Append(" >@")
                .Append(acqtime)
                .Append(i)
                .Append(" and ")
                .Append(tables[i].AcqTime)
                .Append(" <=@")
                .Append(acqendtime)
                .Append(i);
                if (i != tables.Count - 1)
                {
                    sqlstr.Append(";");
                }
            }

            List <ExtractionConfig> list = ExtractionConfigDic.GetExtractionConfigDic().GetExtractionConfig((int)database.ID);

            switch (database.DataBaseType)
            {
            case (int)DataBaseType.SQLite:
                var sqlitepara =
                    new SQLiteParameter[tables.Count * 2];
                if (sqlitepara.Length > 0)
                {
                    var endtime1 = new DateTime[tables.Count];
                    for (int i = 0; i < tables.Count; i++)
                    {
                        string   time     = this.GetLastTimeOrDefaultMin(list, tables[i], database);
                        DateTime timeTemp = Convert.ToDateTime(time).AddSeconds(1);
                        endtime1[i]       = GetDayStepEndTime(timeTemp);
                        sqlitepara[i * 2] = new SQLiteParameter(new StringBuilder().Append("@").Append(acqtime).Append(i).ToString(),
                                                                timeTemp.ToString("yyyy-MM-dd HH:mm:ss"));
                        sqlitepara[i * 2 + 1] = new SQLiteParameter(new StringBuilder().Append("@").Append(acqendtime).Append(i).ToString(),
                                                                    endtime1[i].ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    var sqlitehelper = new DbHelperSqLiteP(connstr);
                    try
                    {
                        var s = sqlitehelper.Query(sqlstr.ToString(), sqlitepara);
                        for (var i = 0; i < tables.Count; i++)
                        {
                            ExtractionConfigDic.GetExtractionConfigDic()
                            .UpdateExtractionConfig(
                                new ExtractionConfig
                            {
                                DataBaseId = (int)database.ID,
                                TableName  = tables[i].TableName,
                                Acqtime    = endtime1[i].ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        }
                        return(s);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                break;

            case (int)DataBaseType.SQLServer:

                var sqlpara =
                    new SqlParameter[tables.Count * 2];
                if (sqlpara.Length > 0)
                {
                    var endtime2 = new DateTime[tables.Count];
                    for (var i = 0; i < tables.Count; i++)
                    {
                        string   time     = this.GetLastTimeOrDefaultMin(list, tables[i], database);
                        DateTime timeTemp = Convert.ToDateTime(time).AddSeconds(1);    //这里加1秒是防止重复提取(因为时间记录中不包含毫秒数)
                        endtime2[i]    = GetDayStepEndTime(timeTemp);
                        sqlpara[i * 2] = new SqlParameter(new StringBuilder().Append("@").Append(acqtime).Append(i).ToString(),
                                                          timeTemp.ToString("yyyy-MM-dd HH:mm:ss"));
                        sqlpara[i * 2 + 1] = new SqlParameter(new StringBuilder().Append("@").Append(acqendtime).Append(i).ToString(),
                                                              endtime2[i].ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    var sqlhelper = new DbHelperSQLP(connstr);
                    try
                    {
                        var s1 = sqlhelper.Query(sqlstr.ToString(), 300, sqlpara);
                        for (var i = 0; i < tables.Count; i++)
                        {
                            ExtractionConfigDic.GetExtractionConfigDic()
                            .UpdateExtractionConfig(
                                new ExtractionConfig
                            {
                                DataBaseId = (int)database.ID,
                                TableName  = tables[i].TableName,
                                Acqtime    = endtime2[i].ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        }
                        return(s1);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                break;

            case (int)DataBaseType.ACCESSOld:
            case (int)DataBaseType.ACCESSNew:
                var olepara =
                    new OleDbParameter[tables.Count * 2];
                if (olepara.Length > 0)
                {
                    var endtime3 = new DateTime[tables.Count];
                    for (var i = 0; i < tables.Count; i++)
                    {
                        try
                        {
                            var timestr  = this.GetLastTimeOrDefaultMin(list, tables[i], database);
                            var timeTemp = Convert.ToDateTime(timestr).AddSeconds(1);
                            endtime3[i]    = GetDayStepEndTime(timeTemp);
                            olepara[i * 2] = new OleDbParameter(new StringBuilder().Append("@").Append(acqtime).Append(i).ToString(),
                                                                timeTemp);
                            olepara[i * 2 + 1] = new OleDbParameter(new StringBuilder().Append("@").Append(acqendtime).Append(i).ToString(),
                                                                    endtime3[i]);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    var oledbhelper = new DbHelperOleDbP(connstr);

                    string[] sqlstrings = sqlstr.ToString().Split(';');

                    DataSet[] ds = new DataSet[tables.Count];
                    for (int i = 0; i < tables.Count; i++)
                    {
                        ds[i] = new DataSet();
                    }
                    for (int i = 0; i < tables.Count; i++)
                    {
                        //@MODIFY 2015-01-12 参数化SQL存在错误?
                        var sql = sqlstrings[i].Replace("@" + acqtime + i.ToString(), "#" + Convert.ToDateTime(olepara[i * 2].Value).ToString("yyyy-MM-dd HH:mm:ss") + "#");
                        sql   = sql.Replace("@" + acqendtime + i.ToString(), "#" + Convert.ToDateTime(olepara[i * 2 + 1].Value).ToString("yyyy-MM-dd HH:mm:ss") + "#");
                        ds[i] = oledbhelper.Query(sql);
                        //ds[i] = oledbhelper.Query(sqlstrings[i], olepara[i * 2], olepara[i * 2 + 1]);
                        ExtractionConfigDic.GetExtractionConfigDic()
                        .UpdateExtractionConfig(
                            new ExtractionConfig
                        {
                            DataBaseId = (int)database.ID,
                            TableName  = tables[i].TableName,
                            Acqtime    = endtime3[i].ToString("yyyy-MM-dd HH:mm:ss")
                        });
                    }
                    DataSet retSet = new DataSet();
                    for (int i = 0; i < tables.Count; i++)
                    {
                        retSet.Merge(ds[i]);
                    }
                    return(retSet);
                    //return oledbhelper.Query(sqlstr.ToString(), olepara);
                }
                break;

            default:
                return(new DataSet());
            }//switch
            return(new DataSet());
        }
Exemple #43
0
        public static async Task <string> ParseDynamicContentAsync(IParseManager parseManager, DynamicInfo dynamicInfo, string template)
        {
            var databaseManager = parseManager.DatabaseManager;

            if (string.IsNullOrEmpty(template))
            {
                return(string.Empty);
            }

            var templateInfo = await databaseManager.TemplateRepository.GetAsync(dynamicInfo.TemplateId);

            var siteInfo = await databaseManager.SiteRepository.GetAsync(dynamicInfo.SiteId);

            await parseManager.InitAsync(siteInfo, dynamicInfo.ChannelId, dynamicInfo.ContentId, templateInfo);

            parseManager.PageInfo.User = dynamicInfo.User;

            var templateContent = StlRequest.ParseRequestEntities(dynamicInfo.QueryString, template);
            var contentBuilder  = new StringBuilder(templateContent);
            var stlElementList  = StlParserUtility.GetStlElementList(contentBuilder.ToString());

            var pageIndex = dynamicInfo.Page - 1;

            //如果标签中存在<stl:pageContents>
            if (StlParserUtility.IsStlElementExists(StlPageContents.ElementName, stlElementList))
            {
                var stlElement             = StlParserUtility.GetStlElement(StlPageContents.ElementName, stlElementList);
                var stlPageContentsElement = stlElement;
                var stlPageContentsElementReplaceString = stlElement;

                var pageContentsElementParser = await StlPageContents.GetAsync(stlPageContentsElement, parseManager);

                var(pageCount, totalNum) = pageContentsElementParser.GetPageCount();

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex == pageIndex)
                    {
                        var pageHtml = await pageContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount, false);

                        contentBuilder.Replace(stlPageContentsElementReplaceString, pageHtml);

                        await parseManager.ReplacePageElementsInDynamicPageAsync(contentBuilder, stlElementList, currentPageIndex, pageCount, totalNum, false, dynamicInfo.ElementId);

                        break;
                    }
                }
            }
            //如果标签中存在<stl:pageChannels>
            else if (StlParserUtility.IsStlElementExists(StlPageChannels.ElementName, stlElementList))
            {
                var stlElement             = StlParserUtility.GetStlElement(StlPageChannels.ElementName, stlElementList);
                var stlPageChannelsElement = stlElement;
                var stlPageChannelsElementReplaceString = stlElement;

                var pageChannelsElementParser = await StlPageChannels.GetAsync(stlPageChannelsElement, parseManager);

                var pageCount = pageChannelsElementParser.GetPageCount(out var totalNum);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex != pageIndex)
                    {
                        continue;
                    }

                    var pageHtml = await pageChannelsElementParser.ParseAsync(currentPageIndex, pageCount);

                    contentBuilder.Replace(stlPageChannelsElementReplaceString, pageHtml);

                    await parseManager.ReplacePageElementsInDynamicPageAsync(contentBuilder, stlElementList, currentPageIndex, pageCount, totalNum, false, dynamicInfo.ElementId);

                    break;
                }
            }
            //如果标签中存在<stl:pageSqlContents>
            else if (StlParserUtility.IsStlElementExists(StlPageSqlContents.ElementName, stlElementList))
            {
                var stlElement = StlParserUtility.GetStlElement(StlPageSqlContents.ElementName, stlElementList);
                var stlPageSqlContentsElement = stlElement;
                var stlPageSqlContentsElementReplaceString = stlElement;

                var pageSqlContentsElementParser = await StlPageSqlContents.GetAsync(stlPageSqlContentsElement, parseManager);

                var pageCount = pageSqlContentsElementParser.GetPageCount(out var totalNum);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex != pageIndex)
                    {
                        continue;
                    }

                    var pageHtml = await pageSqlContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount, false);

                    contentBuilder.Replace(stlPageSqlContentsElementReplaceString, pageHtml);

                    await parseManager.ReplacePageElementsInDynamicPageAsync(contentBuilder, stlElementList, currentPageIndex, pageCount, totalNum, false, dynamicInfo.ElementId);

                    break;
                }
            }

            else if (StlParserUtility.IsStlElementExists(StlPageItems.ElementName, stlElementList))
            {
                var pageCount             = TranslateUtils.ToInt(dynamicInfo.QueryString["pageCount"]);
                var totalNum              = TranslateUtils.ToInt(dynamicInfo.QueryString["totalNum"]);
                var pageContentsAjaxDivId = dynamicInfo.QueryString["pageContentsAjaxDivId"];

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex != pageIndex)
                    {
                        continue;
                    }

                    await parseManager.ReplacePageElementsInDynamicPageAsync(contentBuilder, stlElementList, currentPageIndex, pageCount, totalNum, false, pageContentsAjaxDivId);

                    break;
                }
            }

            await parseManager.ParseInnerContentAsync(contentBuilder);

            //var parsedContent = StlParserUtility.GetBackHtml(contentBuilder.ToString(), pageInfo);
            //return pageInfo.HeadCodesHtml + pageInfo.BodyCodesHtml + parsedContent + pageInfo.FootCodesHtml;
            return(contentBuilder.ToString());
        }
Exemple #44
0
        private DataSet SelectAll(DataBaseName database)
        {
            string connstr = Connectionstring.GetConnectionString(database);
            var    sqlstr  = new StringBuilder();
            List <TableFieldInfo> tables =
                TableFieldInfoDic.GetTableFieldInfoDic().GetSameDataBaseTableFieldInfos((int)database.ID);

            for (int i = 0; i < tables.Count; i++)
            {
                // Select CONVERT(varchar(100), GETDATE(), 25)
                string str = string.Format(
                    "select {0} as ProjectCode,{1} as DataBaseNameID,{2} as sensorType,{3} as ACQUISITION_DATETIME,",
                    ProjectInfoDic.GetInstance().GetProjectInfo().ProjectCode,
                    database.ID,
                    tables[i].SensorType,
                    tables[i].AcqTime);
                sqlstr.Append(str);

                if (ConfigInfoTable.ConfigtableInfoDictionary.ContainsKey((int)database.ID))
                {
                    sqlstr.Append(tables[i].SensorID).Append(",");
                }
                else
                {
                    if (!string.IsNullOrEmpty(tables[i].ModuleNo))
                    {
                        sqlstr.Append(tables[i].ModuleNo).Append(",");
                    }

                    if (!string.IsNullOrEmpty(tables[i].ChannelId))
                    {
                        sqlstr.Append(tables[i].ChannelId).Append(",");
                    }
                    else
                    {
                        sqlstr.Append(string.Format("{0} as channelId", 1)).Append(",");
                    }

                    if (!string.IsNullOrEmpty(tables[i].OtherFlag))
                    {
                        sqlstr.Append(tables[i].OtherFlag).Append(",");
                    }
                }

                Type t = tables[i].GetType();
                for (int j = 1; j <= tables[i].ValueNameCount; j++)
                {
                    System.Reflection.PropertyInfo propertyInfo = t.GetProperty(FieldNamestr + j);
                    if (!string.IsNullOrEmpty(propertyInfo.GetValue(tables[i], null).ToString()))
                    {
                        sqlstr.Append(propertyInfo.GetValue(tables[i], null)).Append(",");
                    }
                }
                sqlstr.Replace(',', ' ', sqlstr.Length - 1, 1);
                sqlstr.Append("from ")
                .Append(tables[i].TableName)
                .Append(" where ")
                .Append(tables[i].AcqTime)
                .Append(" >@")
                .Append(acqtime)
                .Append(i);
                if (i != tables.Count - 1)
                {
                    sqlstr.Append(";");
                }
            }

            List <ExtractionConfig> list = ExtractionConfigDic.GetExtractionConfigDic().GetExtractionConfig((int)database.ID);

            switch (database.DataBaseType)
            {
            case (int)DataBaseType.SQLite:
                var sqlitepara =
                    new SQLiteParameter[tables.Count];
                if (sqlitepara.Length > 0)
                {
                    for (int i = 0; i < sqlitepara.Length; i++)
                    {
                        var str = new StringBuilder();
                        str.Append("@").Append(acqtime).Append(i);
                        sqlitepara[i] = new SQLiteParameter(str.ToString(),
                                                            this.GetLastTime(list, tables[i].TableName));
                    }
                    var sqlitehelper = new DbHelperSqLiteP(connstr);
                    try
                    {
                        return(sqlitehelper.Query(sqlstr.ToString(), sqlitepara));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                break;

            case (int)DataBaseType.SQLServer:

                var sqlpara =
                    new SqlParameter[tables.Count];
                if (sqlpara.Length > 0)
                {
                    for (int i = 0; i < sqlpara.Length; i++)
                    {
                        var str = new StringBuilder();
                        str.Append("@").Append(acqtime).Append(i);
                        string time = this.GetLastTime(list, tables[i].TableName);
                        //string timestr = null;
                        //string[] sliptime = time.Split(new char[]{'/',' ',':'});
                        //if (sliptime.Count() > 1)
                        //{
                        //    for (int n = 0; n < sliptime.Count(); n++)
                        //    {
                        //        if (sliptime[n].Length < 8 && sliptime[n]!="")
                        //        {
                        //            if (Convert.ToInt32(sliptime[n]) < 10 && sliptime[n].Length == 1)
                        //            {
                        //                sliptime[n] = "0" + sliptime[n];
                        //            }
                        //        }

                        //    }
                        //}

                        //for (int m = 0; m < sliptime.Count(); m++)
                        //{
                        //    timestr += sliptime[m].Trim();
                        //}
                        //string[] timeformats =
                        //    {
                        //        "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss.fff",
                        //        "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.fff", "yyyyMMddHHmmss",
                        //        "yyyyMMddHHmmss.fff", "yyyy-MM-dd h:mm:ss"
                        //    };
                        DateTime timeTemp = Convert.ToDateTime(time).AddMilliseconds(999);
                        //bool isSuccess = DateTime.TryParseExact(
                        //timestr,
                        //timeformats,
                        //CultureInfo.CurrentCulture,
                        //DateTimeStyles.None,
                        //out timeTemp); //AssumeLocal
                        //if (!isSuccess)
                        //{
                        //    timeTemp = Convert.ToDateTime(timestr);
                        //}
                        sqlpara[i] = new SqlParameter(str.ToString(), timeTemp.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    }
                    var sqlhelper = new DbHelperSQLP(connstr);
                    try
                    {
                        return(sqlhelper.Query(sqlstr.ToString(), 300, sqlpara));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                break;

            case (int)DataBaseType.ACCESSOld:
            case (int)DataBaseType.ACCESSNew:
                var olepara =
                    new OleDbParameter[tables.Count];
                if (olepara.Length > 0)
                {
                    for (int i = 0; i < olepara.Length; i++)
                    {
                        var str = new StringBuilder();
                        str.Append("@").Append(acqtime).Append(i);
                        try
                        {
                            string   timestr  = this.GetLastTime(list, tables[i].TableName);
                            DateTime timeTemp = Convert.ToDateTime(timestr);
                            // string[] timeformats =
                            //     {
                            //         "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss.fff",
                            //         "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.fff",
                            //         "yyyyMMddHHmmss", "yyyyMMddHHmmss.fff", "yyyy-MM-dd h:mm:ss"
                            //     };
                            //bool isSuccess = DateTime.TryParseExact(
                            //timestr,
                            //timeformats,
                            //CultureInfo.CurrentCulture,
                            //DateTimeStyles.None,
                            //out timeTemp); //AssumeLocal
                            // if (!isSuccess)
                            // {
                            //     timeTemp = Convert.ToDateTime(timestr);
                            // }
                            olepara[i] = new OleDbParameter(str.ToString(),
                                                            timeTemp);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    var oledbhelper = new DbHelperOleDbP(connstr);

                    string[] sqlstrings = sqlstr.ToString().Split(';');

                    DataSet[] ds = new DataSet[olepara.Length];
                    for (int i = 0; i < olepara.Length; i++)
                    {
                        ds[i] = new DataSet();
                    }
                    for (int i = 0; i < olepara.Length; i++)
                    {
                        ds[i] = oledbhelper.Query(sqlstrings[i], olepara[i]);
                    }
                    DataSet retSet = new DataSet();
                    for (int i = 0; i < olepara.Length; i++)
                    {
                        retSet.Merge(ds[i]);
                    }
                    return(retSet);
                    //return oledbhelper.Query(sqlstr.ToString(), olepara);
                }
                break;

            default:
                return(new DataSet());
            }
            return(new DataSet());
        }
        /// <summary>
        /// Convert specified text to equivalent persian text
        /// </summary>
        /// <param name="text">Text to convert</param>
        /// <returns>Converted text</returns>
        public string Convert(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                LastConvertedText = string.Empty;
            }
            else if (LastConvertedText != null && LastConvertedText.Equals(text, StringComparison.Ordinal))
            {
                return(LastConvertedText);
            }
            else
            {
                // make sure that we alocated enough space for text
                EnsureCharSize(text.Length);

                if (LastConvertedText == null)
                {
                    LastConvertedText = string.Empty;
                }
                int startoldIndex = 0;
                int lastoldIndex  = LastConvertedText.Length - 1;

                if (LastConvertedText.Length == text.Length + 1) // characters removed
                {
                    int index = LastConvertedText.IndexOf(text);
                    if (index >= 0)
                    {
                        if (index == 0)
                        {
                            PersianCharacter pc = CharacterMap.GetMappedCharacter(LastConvertedText[LastConvertedText.Length - 1]);
                            if (pc != null && !pc.LeftToRight)
                            {
                                // we have to remove from first because text is reversed
                                startoldIndex = LastConvertedText.Length - text.Length;
                            }
                            else
                            {
                                lastoldIndex = text.Length - 1;
                            }
                        }
                        else
                        {
                            lastoldIndex = text.Length - 1;
                        }
                        text = LastConvertedText.Substring(startoldIndex, text.Length);
                    }
                }

                bool findDiff = false;
                for (int i = 0; i < text.Length; i++)
                {
                    CharInfo cf = _SourceChars[i];
                    cf.SourceChar         = text[i];
                    cf.Character          = CharacterMap.GetMappedCharacter(cf.SourceChar);
                    cf.Form               = PersianCharacterForm.Isolated;
                    _RepositionedChars[i] = null;
                    cf.IsReversed         = false;

                    // start from begin and search for missmatch
                    if (!findDiff && startoldIndex < LastConvertedText.Length)
                    {
                        if (cf.SourceChar == LastConvertedText[startoldIndex])
                        {
                            startoldIndex++;
                            cf.IsReversed = true;
                        }
                        else
                        {
                            findDiff = true;
                        }
                    }
                }

                if (findDiff) // if we found missmatch start from last index to find last missmatch
                {
                    for (int i = text.Length - 1; i >= 0; i--)
                    {
                        CharInfo cf = _SourceChars[i];
                        if (lastoldIndex >= startoldIndex)
                        {
                            if (cf.SourceChar == LastConvertedText[lastoldIndex])
                            {
                                lastoldIndex--;
                                cf.IsReversed = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }


                // find none persian characters and place them in correct position
                for (int i = 0; i < text.Length; i++)
                {
                    CharInfo cf = _SourceChars[i];
                    if (!cf.IsReversed)
                    {
                        _RepositionedChars[text.Length - i - 1] = cf;
                    }
                }

                // place persian characters ( that we found them in previous text change) in correct position
                int j = 0;
                for (int i = 0; i < text.Length; i++)
                {
                    if (_RepositionedChars[i] == null)
                    {
                        for (; j < text.Length; j++)
                        {
                            if (_SourceChars[j].IsReversed)
                            {
                                _RepositionedChars[i] = _SourceChars[j];
                                j++;
                                break;
                            }
                        }
                    }
                }

                // place Left To Right characters to correct place

                // find one left to right character
                for (int i = 0; i < text.Length; i++)
                {
                    CharInfo cf = _RepositionedChars[i];
                    if (!cf.IsReversed && (cf.Character == null || cf.Character.LeftToRight))
                    {
                        // find surrounding ltf chars
                        int startIndex = i;
                        int endIndex   = i;

                        //find most previous valid ltf index
                        for (int k = i - 1; k >= 0; k--)
                        {
                            CharInfo cf2 = _RepositionedChars[k];
                            if (cf2.IsReversed && (cf2.Character == null || cf2.Character.LeftToRight))
                            {
                                startIndex = k;
                            }
                            else
                            {
                                break;
                            }
                        }

                        //find most next valid ltf index
                        for (int k = i + 1; k < text.Length; k++)
                        {
                            CharInfo cf2 = _RepositionedChars[k];
                            if (cf2.IsReversed && (cf2.Character == null || cf2.Character.LeftToRight))
                            {
                                endIndex = k;
                            }
                            else
                            {
                                break;
                            }
                        }

                        int index = endIndex - (i - startIndex);
                        int sign  = Math.Sign(index - i);

                        for (int k = i; k != index; k += sign)
                        {
                            _RepositionedChars[k] = _RepositionedChars[k + sign];
                        }

                        _RepositionedChars[index] = cf;
                        cf.IsReversed             = true;
                    }
                }

                // calc forms of each character
                for (int i = 0; i < text.Length; i++)
                {
                    PersianCharacter     currentPc = _RepositionedChars[i].Character;
                    PersianCharacter     prePc     = null;
                    PersianCharacter     nextPc    = null;
                    PersianCharacterForm form      = PersianCharacterForm.Isolated;

                    if (currentPc != null)
                    {
                        if (i > 0)
                        {
                            nextPc = _RepositionedChars[i - 1].Character;
                        }
                        if (i < text.Length - 1)
                        {
                            prePc = _RepositionedChars[i + 1].Character;
                        }

                        if (prePc == null)
                        {
                            if (nextPc != null && nextPc.CanStickToPrevious && currentPc.CanStickToNext)
                            {
                                form = PersianCharacterForm.Initial;
                            }
                        }
                        else if (nextPc == null)
                        {
                            if (prePc != null && prePc.CanStickToNext)
                            {
                                form = PersianCharacterForm.Final;
                            }
                        }
                        else
                        {
                            if (nextPc.CanStickToPrevious && prePc.CanStickToNext)
                            {
                                if (currentPc.CanStickToNext)
                                {
                                    form = PersianCharacterForm.Medial;
                                }
                                else
                                {
                                    form = PersianCharacterForm.Final;
                                }
                            }
                            else if (prePc.CanStickToNext)
                            {
                                form = PersianCharacterForm.Final;
                            }
                            else if (nextPc.CanStickToPrevious && currentPc.CanStickToNext)
                            {
                                form = PersianCharacterForm.Initial;
                            }
                        }
                    }
                    _RepositionedChars[i].Form = form;
                }

                // build text from end to start
                StringBuilder result = new StringBuilder();

                for (int i = 0; i < text.Length; i++)
                {
                    CharInfo cf = _RepositionedChars[i];
                    if (cf.Character != null)
                    {
                        result.Append(cf.Character[cf.Form]);
                    }
                    else
                    {
                        result.Append(cf.SourceChar);
                    }
                }

                if (ConvertLigature)
                {
                    result.Replace("\uFE8E\uFEDF", "\uFEFB");
                    result.Replace("\uFE8E\uFEE0", "\uFEFC");
                    result.Replace("\uFEEA\uFEE0\uFEDF\uFE8D", "\uFDF2");
                }
                LastConvertedText = result.ToString();
            }
            return(LastConvertedText);
        }
Exemple #46
0
        public void Save(out bool cancel)
        {
            if (this._dateiname == null)
            {
                throw new ApplicationException(ResReader.Reader.GetString("NochKeinDateinameVergeben"));
            }
            if (this._seitLetztemIsChangedAufDTDFehlergeprueft)
            {
                this.GegenStartupDTDPruefen(StartupDatei.PruefFehlerVerhalten.NiemalsFehlerZeigen);
            }
            bool flag = true;

            if (this.HatFehler)
            {
                DialogResult dialogResult = MessageBox.Show(ResReader.Reader.GetString("SollDieDateiDefektGespeichertWerden"), string.Format(ResReader.Reader.GetString("DateiIstDefektUndSollteVorSpeichernKorrigiertWerden"), (object)this.Dateiname), MessageBoxButtons.YesNoCancel);
                switch (dialogResult)
                {
                case DialogResult.Cancel:
                    cancel = true;
                    flag   = false;
                    break;

                case DialogResult.Yes:
                    cancel = false;
                    flag   = true;
                    break;

                case DialogResult.No:
                    cancel = false;
                    flag   = false;
                    break;

                default:
                    throw new ApplicationException("Unbekanntes Dialogergebnis '" + (object)dialogResult + "'");
                }
            }
            else
            {
                cancel = false;
            }
            if (!flag)
            {
                return;
            }
            ArrayList arrayList = new ArrayList();

            foreach (XmlNode childNode in this.XML.DocumentElement.ChildNodes)
            {
                if (childNode.Name == "meta")
                {
                    arrayList.Add((object)childNode);
                }
            }
            foreach (XmlNode oldChild in arrayList)
            {
                oldChild.ParentNode.RemoveChild(oldChild);
            }
            for (int index = 10; index >= 0; --index)
            {
                try
                {
                    File.Delete(string.Format("{0}.bak_{1}", (object)this.Dateiname, (object)index.ToString()));
                    File.Move(string.Format("{0}.bak_{1}", (object)this.Dateiname, (object)(index - 1)), string.Format("{0}.bak_{1}", (object)this.Dateiname, (object)index));
                }
                catch (Exception ex)
                {
                }
            }
            if (File.Exists(this.Dateiname))
            {
                File.Move(this.Dateiname, string.Format("{0}.bak_0", (object)this.Dateiname));
            }
            FileStream fileStream = File.Create(this.Dateiname);
            string     s          = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>" + Regex.Replace(this.XML.InnerXml.ToString(), "<\\?xml .*? ?>", "");

            if (true)
            {
                StringBuilder stringBuilder = new StringBuilder(s);
                stringBuilder.Replace("<bot>", "\r\n<bot>");
                stringBuilder.Replace("<predicates>", "\r\n\t<predicates>");
                stringBuilder.Replace("<substitutions>", "\r\n\t<substitutions>");
                stringBuilder.Replace("<sentence-splitters>", "\r\n\t\t<sentence-splitters>");
                stringBuilder.Replace("<input>", "\r\n<input>");
                stringBuilder.Replace("<gender>", "\r\n<gender>");
                stringBuilder.Replace("<person>", "\r\n<person>");
                stringBuilder.Replace("<person2>", "\r\n<person2>");
                stringBuilder.Replace("<property ", "\r\n\t\t<property ");
                stringBuilder.Replace("<substitute ", "\r\n\t\t<substitute ");
                stringBuilder.Replace("<splitter ", "\r\n\t\t\t<splitter ");
                stringBuilder.Replace("<!--", "\r\n<!--");
                s = stringBuilder.ToString();
            }
            byte[] bytes = Encoding.GetEncoding("ISO-8859-15").GetBytes(s);
            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Close();
            this.IsChanged = false;
        }
Exemple #47
0
        private string _processAllMarkup(string markup)
        {
            // all of the syntax of flowing formatting markup across "soft" paragraph breaks gets a lot easier if we just merge soft breaks together.
            // This is what _mergeLines does, giving us an array of "lines" which can be processed for line based formatting such as ==, etc.
            List <int>    originalLineNumbers;
            List <string> lines      = _breakMarkupIntoLines(markup, out originalLineNumbers);
            StringBuilder htmlMarkup = new StringBuilder();

            if (AddIdToParagraphTags)
            {
                htmlMarkup.Append(_getStartTag("<p>").Replace("<p", "<p id='CreoleLine0'"));                 // start with paragraph
            }
            else
            {
                htmlMarkup.Append(_getStartTag("<p>"));
            }

            int  iBullet          = 0;      // bullet indentation level
            int  iNumber          = 0;      // ordered list indentation level
            bool InTable          = false;  // are in a table definition
            bool InEscape         = false;  // we are in an escaped section
            int  idParagraph      = 1;      // id for paragraphs
            bool inRoadkillEscape = false;

            // process each line of the markup, since bullets, numbers and tables depend on start of line
            foreach (string l in lines)
            {
                // make a copy as we will modify line into HTML as we go
                string line        = l.Trim('\r');
                string lineTrimmed = line.TrimStart(' ');

                // if we aren't in an escaped section
                if (!InEscape && !inRoadkillEscape)
                {
                    // if we were in a table definition and this isn't another row
                    if ((InTable) && (lineTrimmed.Length > 0) && lineTrimmed[0] != '|')
                    {
                        // then we close the table out
                        htmlMarkup.Append("</table>");
                        InTable = false;
                    }

                    // process line based commands (aka, starts with a ** --> bulleted list)

                    // ---  if we found a line completely empty, translate it as end of paragraph
                    if (lineTrimmed.Trim().Length == 0)
                    {
                        // close any pending lists
                        _closeLists(ref htmlMarkup, ref iBullet, ref iNumber, lineTrimmed);

                        // end of paragraph (NOTE: we id paragraphs for conveinence sake
                        if (AddIdToParagraphTags)
                        {
                            htmlMarkup.Append(String.Format("</p>\n{0}",
                                                            _getStartTag("<p>").Replace("<p", String.Format("<p id='CreoleLine{0}'", originalLineNumbers[idParagraph]))));
                        }
                        else
                        {
                            htmlMarkup.Append(String.Format("</p>\n{0}", _getStartTag("<p>")));
                        }
                    }
                    // --- process bullets
                    else if (lineTrimmed[0] == '*')
                    {
                        if (lineTrimmed.Length > 1 && lineTrimmed[1] == '*' && iBullet == 0)
                        {
                            // If we're not in a bulleted list, then this might be bold.
                            htmlMarkup.AppendLine(_processCreoleFragment(line));
                        }
                        else
                        {
                            // if we were doing an ordered list and this isn't one, we need to close the previous list down
                            if ((iNumber > 0) && lineTrimmed[0] != '#')
                            {
                                htmlMarkup.Append(_closeList(ref iNumber, "</ol>"));
                            }

                            // generate correct indentation for bullets given current state of iBullet
                            htmlMarkup.Append(_processListIndentations(lineTrimmed, '*', ref iBullet, _getStartTag("<ul>"), "</ul>"));
                        }
                    }
                    // --- process numbers
                    else if (lineTrimmed[0] == '#')
                    {
                        // if we were doing an bullet list and this isn't one, we need to close the previous list down
                        if ((iBullet > 0) && lineTrimmed[0] != '*')
                        {
                            htmlMarkup.Append(_closeList(ref iBullet, "</ul>"));
                        }

                        // generate correct indentation for bullets given current state of iNumber
                        htmlMarkup.Append(_processListIndentations(lineTrimmed, '#', ref iNumber, _getStartTag("<ol>"), "</ol>"));
                    }
                    // --- process Headers
                    else if (!InTable && lineTrimmed[0] == '=')
                    {
                        // close any pending lists
                        _closeLists(ref htmlMarkup, ref iBullet, ref iNumber, lineTrimmed);

                        // process = as headers only on start of lines
                        htmlMarkup.Append(_processCreoleFragment(_processHeadersCreole(line)));
                    }
                    // --- start of table with header row
                    else if (!InTable && lineTrimmed.StartsWith("|="))
                    {
                        // close any pending lists
                        _closeLists(ref htmlMarkup, ref iBullet, ref iNumber, lineTrimmed);

                        // start a new table
                        htmlMarkup.Append(_getStartTag("<table class=\"wikitable\">"));
                        InTable = true;
                        htmlMarkup.Append(_processTableHeaderRow(lineTrimmed));
                    }
                    // --- start of table - standard row
                    else if (!InTable && lineTrimmed[0] == '|')
                    {
                        // close any pending lists
                        _closeLists(ref htmlMarkup, ref iBullet, ref iNumber, lineTrimmed);

                        // start a new table
                        htmlMarkup.Append(_getStartTag("<table class=\"wikitable\">"));
                        InTable = true;
                        htmlMarkup.Append(_processTableRow(lineTrimmed));
                    }
                    // --- new header row in table
                    else if (InTable && lineTrimmed.StartsWith("|="))
                    {
                        // we are already processing table so this must be a new header row
                        htmlMarkup.Append(_processTableHeaderRow(lineTrimmed));
                    }
                    // --- new standard row in table
                    else if (InTable && lineTrimmed[0] == '|')
                    {
                        // we are already processing table so this must be a new row
                        htmlMarkup.Append(_processTableRow(lineTrimmed));
                    }
                    else if (lineTrimmed.Contains(TextPlugin.PARSER_IGNORE_STARTTOKEN))
                    {
                        inRoadkillEscape = true;
                    }
                    // --- process {{{ }}} <pre>
                    else if (lineTrimmed.StartsWith(NoWikiEscapeStart) && (lineTrimmed.Length == NoWikiEscapeStart.Length))
                    {
                        // we are already processing table so this must be a new row
                        htmlMarkup.Append(_getStartTag("<pre>"));
                        InEscape = true;
                    }
                    else
                    {
                        // we didn't find a special "start of line" command,
                        // namely ordered list, unordered list or table definition

                        // just add it, processing any markup on it.
                        htmlMarkup.Append(String.Format("{0}\n", _processCreoleFragment(line)));
                    }
                }
                else
                {
                    if (lineTrimmed.Contains(TextPlugin.PARSER_IGNORE_ENDTOKEN))
                    {
                        inRoadkillEscape = false;
                    }
                    else if (lineTrimmed.StartsWith(NoWikiEscapeEnd))
                    {
                        // we are looking for a line which starts with }}} to close off the preformated
                        htmlMarkup.Append("</pre>\n");
                        InEscape = false;
                    }
                    else
                    {
                        if (!inRoadkillEscape)
                        {
                            htmlMarkup.Append(System.Web.HttpUtility.HtmlEncode(line) + "\n");                             // just pass it straight through unparsed
                        }
                        else
                        {
                            htmlMarkup.Append(line + "\n");                             // no html encoding
                        }
                    }
                }
                idParagraph++;
            }
            // close out paragraph
            htmlMarkup.Append("</p>");

            // lastly, we want to expand tabs out into hard spaces so that the creole tabs are preserved
            // NOTE: this is non-standard CREOLE...
            htmlMarkup = htmlMarkup.Replace("\t", this._tabStop);

            // return the HTML we have generated
            return(htmlMarkup.ToString());
        }
Exemple #48
0
        private void SendNotification()
        {
            var  parent = Content.Create(this.Parent);
            bool isNotificationEnabled;


            if (bool.TryParse(parent.Fields["EnableNotificationMail"].GetData().ToString(), out isNotificationEnabled) && isNotificationEnabled)
            {
                var mailTemplate  = this.Parent.GetReference <Node>("MailTemplatePage");
                var senderAddress = parent.Fields["SenderAddress"].GetData().ToString();

                if (mailTemplate != null && !string.IsNullOrEmpty(senderAddress))
                {
                    var evaluators = parent.Fields["Evaluators"].GetData() as List <Node>;
                    var emailList  = new Dictionary <string, string>();

                    if (evaluators != null)
                    {
                        foreach (var evaluator in evaluators)
                        {
                            var user = evaluator as IUser;

                            if (user != null && !string.IsNullOrEmpty(user.Email) && !emailList.ContainsKey(user.Email))
                            {
                                emailList.Add(user.Email, user.FullName);
                            }
                            else
                            {
                                var group = evaluator as Group;

                                if (group != null)
                                {
                                    foreach (var usr in group.GetAllMemberUsers())
                                    {
                                        if (!string.IsNullOrEmpty(usr.Email) && !emailList.ContainsKey(usr.Email))
                                        {
                                            emailList.Add(usr.Email, usr.FullName);
                                        }
                                    }
                                }
                            }
                        }

                        var mailTemplateCnt = Content.Create(mailTemplate);

                        var mailSubject = new StringBuilder(mailTemplateCnt.Fields["Subtitle"].GetData().ToString());

                        var mailBody = new StringBuilder(mailTemplateCnt.Fields["Body"].GetData().ToString());
                        var linkText = "<a href='{0}?action={1}'>{1}</a>";
                        var url      = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.Substring(0,
                                                                                                     HttpContext.Current.
                                                                                                     Request.
                                                                                                     UrlReferrer.
                                                                                                     AbsoluteUri.
                                                                                                     IndexOf("?"))
                                       + "/" + this.Name;

                        mailBody = mailBody.Replace("{User}", (this.CreatedBy as IUser).FullName);
                        mailBody = mailBody.Replace("{SurveyName}", parent.DisplayName);
                        mailBody = mailBody.Replace("{Browse}", string.Format(linkText, url, "Browse"));
                        mailBody = mailBody.Replace("{Evaluate}", string.Format(linkText, url, "Evaluate"));
                        mailBody = mailBody.Replace("{Creator}", (this.Parent.CreatedBy as IUser).FullName);

                        var smtpClient   = new SmtpClient(System.Web.Configuration.WebConfigurationManager.AppSettings["SMTP"]);
                        var smtpUser     = System.Web.Configuration.WebConfigurationManager.AppSettings["SMTPUser"];
                        var smtpPassword = System.Web.Configuration.WebConfigurationManager.AppSettings["SMTPPassword"];

                        if (!string.IsNullOrEmpty(smtpUser) && !string.IsNullOrEmpty(smtpPassword))
                        {
                            smtpClient.UseDefaultCredentials = false;

                            var smtpDomain = System.Web.Configuration.WebConfigurationManager.AppSettings["SMTPDomain"];
                            smtpClient.Credentials = string.IsNullOrEmpty(smtpDomain) ? new NetworkCredential(smtpUser, smtpPassword) : new NetworkCredential(smtpUser, smtpPassword, smtpDomain);
                        }

                        foreach (var email in emailList)
                        {
                            mailBody = mailBody.Replace("{Addressee}", email.Value);
                            var mailMessage = new MailMessage(senderAddress, email.Key)
                            {
                                Subject    = mailSubject.ToString(),
                                IsBodyHtml = true,
                                Body       = mailBody.ToString()
                            };

                            try
                            {
                                smtpClient.Send(mailMessage);
                            }
                            catch (Exception ex) //logged
                            {
                                Logger.WriteException(ex);
                            }
                        }
                    }
                }
                else
                {
                    Logger.WriteError("Notification e-mail cannot be sent because the template content or the sender address is missing");
                }
            }
        }
Exemple #49
0
        public static void RewriteSubmitButton(StringBuilder builder, string clickString)
        {
            var submitElement = GetHtmlElementByRole(builder.ToString(), "submit");

            if (string.IsNullOrEmpty(submitElement))
            {
                submitElement = GetHtmlElementById(builder.ToString(), "submit");
            }
            if (!string.IsNullOrEmpty(submitElement))
            {
                var     document    = GetXmlDocument(submitElement, false);
                XmlNode elementNode = document.DocumentElement;
                if (elementNode != null)
                {
                    elementNode = elementNode.FirstChild;
                    if (elementNode.Attributes != null)
                    {
                        var elementIe  = elementNode.Attributes.GetEnumerator();
                        var attributes = new StringDictionary();
                        while (elementIe.MoveNext())
                        {
                            var attr = (XmlAttribute)elementIe.Current;
                            if (attr != null)
                            {
                                var attributeName = attr.Name.ToLower();
                                if (attributeName == "href")
                                {
                                    attributes.Add(attr.Name, "javascript:;");
                                }
                                else if (attributeName != "onclick")
                                {
                                    attributes.Add(attr.Name, attr.Value);
                                }
                            }
                        }
                        attributes.Add("onclick", clickString);
                        attributes.Remove("id");
                        attributes.Remove("name");

                        //attributes.Add("id", "submit_" + styleID);

                        if (EqualsIgnoreCase(elementNode.Name, "a"))
                        {
                            attributes.Remove("href");
                            attributes.Add("href", "javascript:;");
                        }

                        if (!string.IsNullOrEmpty(elementNode.InnerXml))
                        {
                            builder.Replace(submitElement,
                                            $@"<{elementNode.Name} {ToAttributesString(attributes)}>{elementNode.InnerXml}</{elementNode
                                    .Name}>");
                        }
                        else
                        {
                            builder.Replace(submitElement,
                                            $@"<{elementNode.Name} {ToAttributesString(attributes)}/>");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            var settings = new XmlWriterSettings
            {
                Indent           = this.IndentXml,
                ConformanceLevel = ConformanceLevel.Fragment,
                IndentChars      = "  ",
            };

            var sb = new StringBuilder();

            using (XmlWriter xtw = XmlWriter.Create(sb, settings))
            {
                xtw.WriteStartElement("log4j", "event", dummyNamespace);
                xtw.WriteAttributeString("xmlns", "nlog", null, dummyNLogNamespace);
                xtw.WriteAttributeString("logger", logEvent.LoggerName);
                xtw.WriteAttributeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture));
                xtw.WriteAttributeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture));
                xtw.WriteAttributeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));

                xtw.WriteElementString("log4j", "message", dummyNamespace, logEvent.FormattedMessage);
                if (logEvent.Exception != null)
                {
                    xtw.WriteElementString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString());
                }

                if (this.IncludeNdc)
                {
                    xtw.WriteElementString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()));
                }

                if (logEvent.Exception != null)
                {
                    xtw.WriteStartElement("log4j", "throwable", dummyNamespace);
                    xtw.WriteCData(logEvent.Exception.ToString());
                    xtw.WriteEndElement();
                }

#if !NET_CF
                if (this.IncludeCallSite || this.IncludeSourceInfo)
                {
                    System.Diagnostics.StackFrame frame = logEvent.UserStackFrame;
                    if (frame != null)
                    {
                        MethodBase methodBase = frame.GetMethod();
                        Type       type       = methodBase.DeclaringType;

                        xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace);
                        if (type != null)
                        {
                            xtw.WriteAttributeString("class", type.FullName);
                        }

                        xtw.WriteAttributeString("method", methodBase.ToString());
#if !SILVERLIGHT
                        if (this.IncludeSourceInfo)
                        {
                            xtw.WriteAttributeString("file", frame.GetFileName());
                            xtw.WriteAttributeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture));
                        }
#endif
                        xtw.WriteEndElement();

                        if (this.IncludeNLogData)
                        {
                            xtw.WriteElementString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture));
                            xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace);
                            if (type != null)
                            {
                                xtw.WriteAttributeString("assembly", type.Assembly.FullName);
                            }

                            xtw.WriteEndElement();
                        }
                    }
                }
#endif
                if (this.IncludeNLogData)
                {
                    xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace);
                    foreach (var contextProperty in logEvent.Properties)
                    {
                        xtw.WriteStartElement("nlog", "data", dummyNLogNamespace);
                        xtw.WriteAttributeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture));
                        xtw.WriteAttributeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture));
                        xtw.WriteEndElement();
                    }

                    xtw.WriteEndElement();
                }

                xtw.WriteStartElement("log4j", "properties", dummyNamespace);
                if (this.IncludeMdc)
                {
                    foreach (KeyValuePair <string, string> entry in MappedDiagnosticsContext.ThreadDictionary)
                    {
                        xtw.WriteStartElement("log4j", "data", dummyNamespace);
                        xtw.WriteAttributeString("name", entry.Key);
                        xtw.WriteAttributeString("value", entry.Value);
                        xtw.WriteEndElement();
                    }
                }

                foreach (NLogViewerParameterInfo parameter in this.Parameters)
                {
                    xtw.WriteStartElement("log4j", "data", dummyNamespace);
                    xtw.WriteAttributeString("name", parameter.Name);
                    xtw.WriteAttributeString("value", parameter.Layout.Render(logEvent));
                    xtw.WriteEndElement();
                }

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeString("name", "log4japp");
                xtw.WriteAttributeString("value", this.AppInfo);
                xtw.WriteEndElement();

                xtw.WriteStartElement("log4j", "data", dummyNamespace);
                xtw.WriteAttributeString("name", "log4jmachinename");
#if NET_CF
                xtw.WriteAttributeString("value", "netcf");
#elif SILVERLIGHT
                xtw.WriteAttributeString("value", "silverlight");
#else
                xtw.WriteAttributeString("value", Environment.MachineName);
#endif
                xtw.WriteEndElement();
                xtw.WriteEndElement();

                xtw.WriteEndElement();
                xtw.Flush();

                // get rid of 'nlog' and 'log4j' namespace declarations
                sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty);
                sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty);

                builder.Append(sb.ToString());
            }
        }
Exemple #51
0
 public static void XmlToHtml(StringBuilder builder)
 {
     builder?.Replace("&quot;", "'").Replace("&gt;", ">").Replace("&lt;", "<").Replace("&amp;", "&");
 }
        public async Task Invoke(HttpContext context)
        {
            context.Response.ContentType = "text/html; charset=utf-8";
            var _path = context.Request.Path.ToString().Replace(LoggerSettings.LogRequestPath, "");
            var file  = new FileInfo(Path.Combine(_fileDirectory, _path.TrimStart('\\', '/')));

            context.Response.Headers.Add(HeaderNames.AcceptRanges, "bytes");
            EntityTagHeaderValue _tag = null;

            if (file.Exists)
            {
                var  _lastModified = file.LastAccessTime.ToUniversalTime();
                long value         = _lastModified.ToFileTime() ^ file.Length;
                _tag = EntityTagHeaderValue.Parse($"\"{ Convert.ToString(value, 16)}\"");
                if (context.Request.Headers.Keys.Contains("If-None-Match"))
                {
                    var tag = context.Request.Headers["If-None-Match"].ToString();
                    if (tag == _tag.Tag)
                    {
                        context.Response.StatusCode = 304;
                        await Task.CompletedTask;
                        return;
                    }
                }
                if (_tag != null)
                {
                    var _responseHeaders = context.Response.GetTypedHeaders();
                    _responseHeaders.LastModified = file.LastAccessTime;
                    _responseHeaders.ETag         = _tag;
                    _responseHeaders.CacheControl = new CacheControlHeaderValue
                    {
                        MaxAge = TimeSpan.FromHours(2),
                        //Public = true,
                    };
                }
                string fileContent;
                using (var stream = file.OpenRead())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        fileContent = reader.ReadToEnd();
                    }
                }
                StringBuilder html       = new StringBuilder(markdownHtmlContent);
                var           pathString = context.Request.Path;
                string        text       = "/";
                string[]      array      = pathString.Value.Split(new char[1]
                {
                    '/'
                }, StringSplitOptions.RemoveEmptyEntries);
                //var _paths = array.Take(array.Length - 1).ToArray();
                StringBuilder stringBuilder = new StringBuilder($"<a href='{LoggerSettings.SettingsPath}'>Settings</a>&nbsp;&nbsp;");
                foreach (string text2 in array)
                {
                    text = string.Format("{0}{1}/", text, text2);
                    if (text.TrimEnd('/') == context.Request.Path)
                    {
                        stringBuilder.AppendFormat("<a href='javascript:;'>{0}</a>", _htmlEncoder.Encode(text2));
                    }
                    else
                    {
                        stringBuilder.AppendFormat("<a href=\"{0}\">{1}/</a>", _htmlEncoder.Encode(text), _htmlEncoder.Encode(text2));
                    }
                }
                html.Replace("{{content}}", MarkdownHead + fileContent)
                .Replace("{{title}}", string.Join("/", array.Take(array.Length - 1)))
                .Replace("{{link}}", stringBuilder.ToString());
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync(html.ToString(), Encoding.UTF8);
            }
        }
Exemple #53
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// The constructor initializes the dictionary for the default backup directory.
        /// ENHANCE: If we want this class to be able to be used for any arbitrary directory,
        /// we'll need to pass in the directory name or have a way to change it.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public BackupFileRepository(string defaultBackupDir)
        {
            string[] backups;
            try
            {
                backups = FileUtils.GetFilesInDirectory(defaultBackupDir);
            }
            catch (Exception)
            {
                return;
            }

            Regex regex = new Regex(@" \d\d\d\d-\d\d?-\d\d(-| )\d\d\d\d");

            foreach (string backup in backups)
            {
                string ext = Path.GetExtension(backup);
                if (ext != FdoFileHelper.ksFwBackupFileExtension && ext != FdoFileHelper.ksFw60BackupFileExtension)
                {
                    continue;
                }
                string          filename = Path.GetFileNameWithoutExtension(backup);
                MatchCollection matches  = regex.Matches(filename);
                Debug.Assert(matches.Count <= 1, "Maybe there was a date in the comment or (perish the thought) in the project name.");
                if (matches.Count >= 1)
                {
                    Match         match       = matches[0];
                    string        projectName = filename.Substring(0, match.Index);
                    StringBuilder date        = new StringBuilder(match.Value);
                    date.Replace("-", CultureInfo.InvariantCulture.DateTimeFormat.DateSeparator);
                    // These next three lines are fairly ugly, but we need them to account for backups that have
                    // a dash between the date and the time.
                    int ichShouldBeASpace = BackupSettings.ksBackupDateFormat.Length - BackupSettings.ksBackupDateFormat.LastIndexOf(' ');
                    Debug.Assert(ichShouldBeASpace == 5, "Rather than hard-coding a 5 here, we try to calculate this from the constant, but if this is ever not 5, someone should make sure this logic is still correct.");
                    date[date.Length - ichShouldBeASpace] = ' ';
                    DateTime dateOfBackup;
                    if (DateTime.TryParseExact(date.ToString(), s_dateFormatForParsing,
                                               CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dateOfBackup))
                    {
                        SortedDictionary <DateTime, BackupFileSettings> versions = GetOrCreateProjectVersions(projectName);
                        string comment;
                        if (ext == FdoFileHelper.ksFw60BackupFileExtension)
                        {
                            comment = Properties.Resources.kstidFw60OrEarlierBackupComment;
                        }
                        else
                        {
                            int ichStartOfComment = match.Index + match.Length + 1;
                            comment = (ichStartOfComment < filename.Length) ? filename.Substring(ichStartOfComment) : string.Empty;
                        }
                        versions[dateOfBackup] = new BackupFileSettings(backup, dateOfBackup, comment);
                        continue;
                    }
                }
                // Try to read the contents of the zip file to see if it really is a valid FW
                // zip file whose filename just got mangled.
                BackupFileSettings settings = new BackupFileSettings(backup, false);
                if (IsBackupValid(settings))
                {
                    SortedDictionary <DateTime, BackupFileSettings> versions = GetOrCreateProjectVersions(settings.ProjectName);
                    versions[settings.BackupTime] = settings;
                }
            }
        }
Exemple #54
0
        private static string ExecuteFiddle(FiddleExecuteModel model)
        {
            var client = new RestClient(ApiUrl);

            // execute request through API
            var request = new RestRequest("execute", Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(model);

            IRestResponse <FiddleExecuteResult> response = client.Execute <FiddleExecuteResult>(request);

            StringBuilder result = new StringBuilder();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                result.AppendLine("Failed to execute API request. Here is an answer from API");
                result.AppendLine("Response Code: " + response.StatusCode);
                result.AppendLine("Response Body: " + response.Content);
            }
            else
            {
                // write usage statistics
                foreach (var header in response.Headers)
                {
                    //if (header.Name == "X-RateLimit-Limit")
                    //{
                    //    result.AppendLine("Your total per hour limit is " + header.Value);
                    //}

                    //if (header.Name == "X-RateLimit-Remaining")
                    //{
                    //    result.AppendLine("Your remaining executions count per hour is " + header.Value);
                    //}

                    if (header.Name == "X-RateLimit-Reset")
                    {
                        var epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                        epochTime = epochTime.AddSeconds(int.Parse(header.Value.ToString()));
                        //result.AppendLine("UTC Time when limit will be refreshed " + epochTime);
                    }
                }

                //result.AppendLine();
                //result.AppendLine("Code output:");
                result.AppendLine(response.Data.ConsoleOutput);
            }
            var   resultString = result.Replace(Environment.NewLine, "<br/>").ToString();
            Regex regex        = new Regex("error");
            Regex regex1       = new Regex("exception");

            if (regex.IsMatch(resultString.ToLower()) || regex1.IsMatch(resultString.ToLower()))
            {
                correct = false;
                return("Не верно <br/>" + resultString);
            }


            correct = true;
            return("ЗАДАНИЕ ВЫПОЛНЕНО <br/>" + resultString);
        }
        protected override string TomultipleSqlString(List <IGrouping <int, DbColumnInfo> > groupList)
        {
            Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List<T> need Primary key");
            int           pageSize       = 200;
            int           pageIndex      = 1;
            int           totalRecord    = groupList.Count;
            int           pageCount      = (totalRecord + pageSize - 1) / pageSize;
            StringBuilder batchUpdateSql = new StringBuilder();

            while (pageCount >= pageIndex)
            {
                StringBuilder updateTable = new StringBuilder();
                string        setValues   = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it =>
                {
                    if (SetValues.IsValuable())
                    {
                        var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName));
                        if (setValue != null && setValue.Any())
                        {
                            return(setValue.First().Value);
                        }
                    }
                    var result = string.Format("{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName));
                    return(result);
                }));
                string tempColumnValue = string.Join(",", groupList.First().Select(it =>
                {
                    if (SetValues.IsValuable())
                    {
                        var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName));
                        if (setValue != null && setValue.Any())
                        {
                            return(setValue.First().Value);
                        }
                    }
                    var result = Builder.GetTranslationColumnName(it.DbColumnName);
                    return(result);
                }));
                batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString);
                int i = 0;
                var tableColumnList = this.Context.DbMaintenance.GetColumnInfosByTableName(GetTableNameStringNoWith);

                foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
                {
                    var isFirst = i == 0;
                    if (!isFirst)
                    {
                        updateTable.Append(SqlTemplateBatchUnion);
                    }
                    updateTable.Append("\r\n (" + string.Join(",", columns.Select(it =>
                    {
                        var columnInfo = tableColumnList.FirstOrDefault(x => x.DbColumnName.Equals(it.DbColumnName, StringComparison.OrdinalIgnoreCase));
                        var dbType     = columnInfo?.DataType;
                        if (dbType == null)
                        {
                            var typeName = it.PropertyType.Name.ToLower();
                            if (typeName == "int32")
                            {
                                typeName = "int";
                            }
                            if (typeName == "int64")
                            {
                                typeName = "long";
                            }
                            if (typeName == "int16")
                            {
                                typeName = "short";
                            }

                            var isAnyType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).Any();
                            if (isAnyType)
                            {
                                dbType = PostgreSQLDbBind.MappingTypesConst.Where(x => x.Value.ToString().ToLower() == typeName).FirstOrDefault().Key;
                            }
                            else
                            {
                                dbType = "varchar";
                            }
                        }
                        return(string.Format("CAST({0} AS {1})", FormatValue(it.Value), dbType));
                    })) + ")");
                    ++i;
                }
                pageIndex++;
                updateTable.Append("\r\n");
                string whereString = null;
                if (this.WhereValues.HasValue())
                {
                    foreach (var item in WhereValues)
                    {
                        var isFirst = whereString == null;
                        whereString += (isFirst ? null : " AND ");
                        whereString += item;
                    }
                }
                else if (PrimaryKeys.HasValue())
                {
                    foreach (var item in PrimaryKeys)
                    {
                        var isFirst = whereString == null;
                        whereString += (isFirst ? null : " AND ");
                        whereString += string.Format("{0}.{1}=T.{1}", GetTableNameStringNoWith, Builder.GetTranslationColumnName(item));
                    }
                }
                var format = string.Format(SqlTemplateJoin, updateTable, whereString, tempColumnValue);
                batchUpdateSql.Replace("${0}", format);
                batchUpdateSql.Append(";");
            }
            return(batchUpdateSql.ToString());
        }
Exemple #56
0
        public static bool ExportMesh(AssetItem item, string exportPath)
        {
            var m_Mesh = (Mesh)item.Asset;

            if (m_Mesh.m_VertexCount <= 0)
            {
                return(false);
            }
            var exportFullName = exportPath + item.Text + ".obj";

            if (ExportFileExists(exportFullName))
            {
                return(false);
            }
            var sb = new StringBuilder();

            sb.AppendLine("g " + m_Mesh.m_Name);
            #region Vertices
            if (m_Mesh.m_Vertices == null || m_Mesh.m_Vertices.Length == 0)
            {
                return(false);
            }
            int c = 3;
            if (m_Mesh.m_Vertices.Length == m_Mesh.m_VertexCount * 4)
            {
                c = 4;
            }
            for (int v = 0; v < m_Mesh.m_VertexCount; v++)
            {
                sb.AppendFormat("v {0} {1} {2}\r\n", -m_Mesh.m_Vertices[v * c], m_Mesh.m_Vertices[v * c + 1], m_Mesh.m_Vertices[v * c + 2]);
            }
            #endregion

            #region UV
            if (m_Mesh.m_UV0 != null && m_Mesh.m_UV0.Length == m_Mesh.m_VertexCount * 2)
            {
                for (int v = 0; v < m_Mesh.m_VertexCount; v++)
                {
                    sb.AppendFormat("vt {0} {1}\r\n", m_Mesh.m_UV0[v * 2], m_Mesh.m_UV0[v * 2 + 1]);
                }
            }
            else if (m_Mesh.m_UV1 != null && m_Mesh.m_UV1.Length == m_Mesh.m_VertexCount * 2)
            {
                for (int v = 0; v < m_Mesh.m_VertexCount; v++)
                {
                    sb.AppendFormat("vt {0} {1}\r\n", m_Mesh.m_UV1[v * 2], m_Mesh.m_UV1[v * 2 + 1]);
                }
            }
            #endregion

            #region Normals
            if (m_Mesh.m_Normals != null && m_Mesh.m_Normals.Length > 0)
            {
                if (m_Mesh.m_Normals.Length == m_Mesh.m_VertexCount * 3)
                {
                    c = 3;
                }
                else if (m_Mesh.m_Normals.Length == m_Mesh.m_VertexCount * 4)
                {
                    c = 4;
                }
                for (int v = 0; v < m_Mesh.m_VertexCount; v++)
                {
                    sb.AppendFormat("vn {0} {1} {2}\r\n", -m_Mesh.m_Normals[v * c], m_Mesh.m_Normals[v * c + 1], m_Mesh.m_Normals[v * c + 2]);
                }
            }
            #endregion

            #region Face
            int sum = 0;
            for (var i = 0; i < m_Mesh.m_SubMeshes.Length; i++)
            {
                sb.AppendLine($"g {m_Mesh.m_Name}_{i}");
                int indexCount = (int)m_Mesh.m_SubMeshes[i].indexCount;
                var end        = sum + indexCount / 3;
                for (int f = sum; f < end; f++)
                {
                    sb.AppendFormat("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\r\n", m_Mesh.m_Indices[f * 3 + 2] + 1, m_Mesh.m_Indices[f * 3 + 1] + 1, m_Mesh.m_Indices[f * 3] + 1);
                }
                sum = end;
            }
            #endregion

            sb.Replace("NaN", "0");
            File.WriteAllText(exportFullName, sb.ToString());
            return(true);
        }
        /// <summary>
        /// Atualiza PontoVenda
        /// </summary>
        /// <returns></returns>
        public override bool Atualizar(BD bd)
        {
            try
            {
                string sqlVersion = "SELECT MAX(Versao) FROM cPontoVenda_IngressoMais WHERE ID=" + this.Control.ID;
                object obj        = bd.ConsultaValor(sqlVersion);
                int    versao     = (obj != null) ? Convert.ToInt32(obj) : 0;
                this.Control.Versao = versao;

                InserirControle("U");
                InserirLog();

                StringBuilder sql = new StringBuilder();
                sql.Append("UPDATE tPontoVenda_IngressoMais SET Local = '@001', Nome = '@002', Endereco = '@003', Numero = '@004', Compl = '@005', Cidade = '@006', Estado = '@007', Bairro = '@008', Obs = '@009', Referencia = '@010', CEP = '@011', PermiteRetirada = '@012', IR = '@013' ");
                sql.Append("WHERE ID = @ID");
                sql.Replace("@ID", this.Control.ID.ToString());
                sql.Replace("@001", this.Local.ValorBD);
                sql.Replace("@002", this.Nome.ValorBD);
                sql.Replace("@003", this.Endereco.ValorBD);
                sql.Replace("@004", this.Numero.ValorBD);
                sql.Replace("@005", this.Compl.ValorBD);
                sql.Replace("@006", this.Cidade.ValorBD);
                sql.Replace("@007", this.Estado.ValorBD);
                sql.Replace("@008", this.Bairro.ValorBD);
                sql.Replace("@009", this.Obs.ValorBD);
                sql.Replace("@010", this.Referencia.ValorBD);
                sql.Replace("@011", this.CEP.ValorBD);
                sql.Replace("@012", this.PermiteRetirada.ValorBD);
                sql.Replace("@013", this.IR.ValorBD);

                int x = bd.Executar(sql.ToString());

                bool result = (x == 1);

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Inserir novo(a) PontoVenda
        /// </summary>
        /// <returns></returns>
        public override bool Inserir(BD bd)
        {
            try
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("SELECT MAX(ID) AS ID FROM cPontoVenda_IngressoMais");
                object obj = bd.ConsultaValor(sql);
                int    id  = (obj != null) ? Convert.ToInt32(obj) : 0;

                this.Control.ID     = ++id;
                this.Control.Versao = 0;

                sql = new StringBuilder();
                sql.Append("INSERT INTO tPontoVenda_IngressoMais(ID, Local, Nome, Endereco, Numero, Compl, Cidade, Estado, Bairro, Obs, Referencia, CEP, PermiteRetirada, IR) ");
                sql.Append("VALUES (@ID,'@001','@002','@003','@004','@005','@006','@007','@008','@009','@010','@011','@012','@013')");

                sql.Replace("@ID", this.Control.ID.ToString());
                sql.Replace("@001", this.Local.ValorBD);
                sql.Replace("@002", this.Nome.ValorBD);
                sql.Replace("@003", this.Endereco.ValorBD);
                sql.Replace("@004", this.Numero.ValorBD);
                sql.Replace("@005", this.Compl.ValorBD);
                sql.Replace("@006", this.Cidade.ValorBD);
                sql.Replace("@007", this.Estado.ValorBD);
                sql.Replace("@008", this.Bairro.ValorBD);
                sql.Replace("@009", this.Obs.ValorBD);
                sql.Replace("@010", this.Referencia.ValorBD);
                sql.Replace("@011", this.CEP.ValorBD);
                sql.Replace("@012", this.PermiteRetirada.ValorBD);
                sql.Replace("@013", this.IR.ValorBD);

                int x = bd.Executar(sql.ToString());

                bool result = (x == 1);

                if (result)
                {
                    InserirControle("I");
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 protected override void Build(MethodInfo methodInfo)
 {
     template.Replace("{__methodArgs}", GetArgsString(methodInfo.Arguments));
 }
Exemple #60
0
        /// <inheritdoc/>
        public string GetDomainName(Uri requestedUri, bool parsePortNumber)
        {
            var domainName = new StringBuilder();

            // split both URL separater, and parameter separator
            // We trim right of '?' so test for filename extensions can occur at END of URL-componenet.
            // Test:   'www.aspxforum.net'  should be returned as a valid domain name.
            // just consider left of '?' in URI
            // Binary, else '?' isn't taken literally; only interested in one (left) string
            string uri        = requestedUri.ToString();
            string hostHeader = Config.GetSetting("HostHeader");

            if (!string.IsNullOrEmpty(hostHeader))
            {
                uri = uri.ToLowerInvariant().Replace(hostHeader.ToLowerInvariant(), string.Empty);
            }

            int queryIndex = uri.IndexOf("?", StringComparison.Ordinal);

            if (queryIndex > -1)
            {
                uri = uri.Substring(0, queryIndex);
            }

            string[] url = uri.Split('/');
            for (queryIndex = 2; queryIndex <= url.GetUpperBound(0); queryIndex++)
            {
                bool needExit = false;
                switch (url[queryIndex].ToLowerInvariant())
                {
                case "":
                    continue;

                case "admin":
                case "controls":
                case "desktopmodules":
                case "mobilemodules":
                case "premiummodules":
                case "providers":
                case "api":
                    needExit = true;
                    break;

                default:
                    // exclude filenames ENDing in ".aspx" or ".axd" ---
                    //   we'll use reverse match,
                    //   - but that means we are checking position of left end of the match;
                    //   - and to do that, we need to ensure the string we test against is long enough;
                    if (url[queryIndex].Length >= ".aspx".Length)
                    {
                        if (url[queryIndex].LastIndexOf(".aspx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".aspx".Length) ||
                            url[queryIndex].LastIndexOf(".axd", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".axd".Length) ||
                            url[queryIndex].LastIndexOf(".ashx", StringComparison.OrdinalIgnoreCase) == (url[queryIndex].Length - ".ashx".Length))
                        {
                            break;
                        }
                    }

                    // non of the exclusionary names found
                    domainName.Append((!string.IsNullOrEmpty(domainName.ToString()) ? "/" : string.Empty) + url[queryIndex]);
                    break;
                }

                if (needExit)
                {
                    break;
                }
            }

            if (parsePortNumber)
            {
                if (domainName.ToString().IndexOf(":", StringComparison.Ordinal) != -1)
                {
                    if (!Globals.UsePortNumber())
                    {
                        domainName = domainName.Replace(":" + requestedUri.Port, string.Empty);
                    }
                }
            }

            return(domainName.ToString());
        }