Beispiel #1
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;
		}
	}
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int f = int.Parse(Console.ReadLine());
        int r = int.Parse(Console.ReadLine());

        string nInBinary = Convert.ToString(n, 2).PadLeft(19, '0');
        StringBuilder bin = new StringBuilder(nInBinary);
        char charAtFPos = bin[bin.Length - 1 - f];
        bin.Remove(bin.Length - 1 - f, 1);

        for (int i = 0; i < r; i++)
        {
            char right = bin[bin.Length - 1];

            bin.Remove(bin.Length - 1, 1);
            bin.Insert(0, right);
        }

        bin.Insert(bin.Length - f, charAtFPos);

        int res = Convert.ToInt32(bin.ToString(), 2);

        Console.WriteLine(res);
    }
    static void Main()
    {
        string line = "aaaaabbbbbcdddeeeedssaa";
        StringBuilder sb = new StringBuilder();
        sb.Append(line);
        char compare = sb[0];
        int startIndex = 0;
        int sum = 1;
        int count = 0;
        for (int i = 1; i < sb.Length; i++)
        {
            if (compare == sb[i])
            {
                sum++;
            }

            else
            {
                sb.Remove(startIndex + 1, sum - 1);
                sum = 1;
                count++;
                startIndex = count;
                compare = sb[startIndex];
                i = count;
            }

        }

        sb.Remove(startIndex + 1, sum - 1);
        Console.WriteLine(sb.ToString());
    }
Beispiel #4
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);
        }

        //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 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);
     }
 }
Beispiel #6
0
    static void Main()
    {
        string text = Console.ReadLine();
        int start = text.IndexOf("<upcase>");
        int end = text.IndexOf("</upcase>") + 9;

        while (start != -1 && end != -1)
        {
            StringBuilder sb = new StringBuilder(text);
            for (int i = start; i < end; i++)
            {
                if (sb[i] >= 'a' && sb[i] <= 'z')
                {
                    sb[i] -= (char)32;
                }
            }

            sb = sb.Remove(end - 9, 9);
            sb = sb.Remove(start, 8);

            text = sb.ToString();
            start = text.IndexOf("<upcase>");
            end = text.IndexOf("</upcase>") + 9;
        }
        Console.WriteLine(text);
    }
Beispiel #7
0
    public BLOCK(StringBuilder raw)
    {
        if (raw[0] != BLOCK_START)
            throw new ArgumentException("Expected block start token");

        do
        {
            raw.Remove(0, 1);
            LTrim(raw);

            //TODO: Special case, test for empty block
            if (raw[0] == BLOCK_END)
                break;

            if (raw[0] != BLOCK_SEPARATOR)
            {
                var element = Element.From(raw);
                _elements.Add(element);
                LTrim(raw);
            }
        }
        while (raw[0] == BLOCK_SEPARATOR);

        if (raw[0] != BLOCK_END)
            throw new ArgumentException("Expected end of block");

        raw.Remove(0, 1);
    }
Beispiel #8
0
    public static string GetJson(DataTable dt, String page, String rows)
    {
        int totalRecord = dt.Rows.Count; // 总记录数(应根据数据库取得,在此只是模拟)
        int totalPage = totalRecord % int.Parse(rows) == 0 ? totalRecord
                / int.Parse(rows) : totalRecord / int.Parse(rows)
                + 1; // 计算总页数

        int index = (int.Parse(page) - 1) * int.Parse(rows); // 开始记录数
        int pageSize = int.Parse(rows);
        // 以下模拟构造JSON数据对象
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"page\":" + page + ",\"total\":" + totalPage + ",\"records\":" + totalRecord + ",\"rows\"");
        jsonBuilder.Append(":[");
        for (int i = index; i < pageSize + index && i < totalRecord; i++)
        {
            jsonBuilder.Append("{\"id\":" + i + ",\"cell\":[");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"" + dt.Rows[i][j].ToString().Trim() + "\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }
        static void Main()
        {
            string sentence = "C# is not C++, not PHP and not Delphi!";
                        
            char[] separator = { ' ', '!' ,','};
            string[] words = sentence.Split(separator,StringSplitOptions.RemoveEmptyEntries);

            StringBuilder result = new StringBuilder();

            int currentWords = words.Length - 1;

            string[] subSentence = sentence.Split(',');
            foreach (var item in subSentence)
            {
                string newitem = item.Trim();
                int countWordsSub = newitem.Split(' ').Length;
                for (int i = 0; i < countWordsSub; i++)
                {
                    result.AppendFormat("{0} ", words[currentWords]);
                    currentWords--;
                }
                result.Remove(result.ToString().Length - 1, 1);
                result.Append(", ");
            }
            result.Remove(result.ToString().Length - 2, 2);
            result.Append("!");
            Console.WriteLine(sentence);
            Console.WriteLine();
            Console.WriteLine(result.ToString());                        
        }
    private static void PrintPolynomial(decimal[] polynomial)
    {
        StringBuilder returnString = new StringBuilder();

        for (int i = polynomial.Length - 1; i >= 0; i--)
        {
            if (polynomial[i] != 0)
            {
                returnString.Append(polynomial[i] > 0 ? " + " : " - ");
                returnString.Append(Math.Abs(polynomial[i]));
                if (i != 0)
                {
                    returnString.Append(i > 1 ? "x^" + i : "x");
                }
            }
        }

        if (returnString[1] != '-')
        {
            returnString.Remove(0, 3);
        }
        else
        {
            returnString.Remove(0, 1);
        }

        Console.Write(returnString);
    }
Beispiel #11
0
    static string PrintPoli(decimal[] polynomial)
    {
        StringBuilder returnString = new StringBuilder();

        for (int i = polynomial.Length - 1; i >= 0; i--)
        {
            if (polynomial[i] != 0)
            {
                returnString.Append(polynomial[i] > 0 ? " + " : " - ");
                returnString.Append(Math.Abs(polynomial[i]));
                if (i != 0)
                {
                    returnString.Append(i > 1 ? "x^" + i : "x");
                }
            }
        }

        if (returnString[1] != '-')
        {
            returnString.Remove(0, 3);
        }
        else
        {
            returnString.Remove(0, 1);
        }

        return returnString.ToString();
    }
Beispiel #12
0
    public static void SetTextOnMesh(string text, TextMesh mesh, float boundary)
    {
        //TODO: This is rather naive. Hyphenation?
        text = text.Replace(System.Environment.NewLine, "");
        string[] words = text.Split(' ');

        var sb = new StringBuilder();
        var renderer = mesh.GetComponent<Renderer>();

        for (int i = 0; i < words.Length; i++)
        {
            sb.Append(words[i] + " ");
            mesh.text = sb.ToString();

            if (renderer.bounds.size.x >= boundary && i!=0)
            {
                //TODO: This crashes on first word. why +2 anyway?
                sb.Remove(sb.Length - (words[i].Length + 1), words[i].Length + 1);
                sb.Append(System.Environment.NewLine);
                sb.Append(words[i] + " ");
            }
        }
        sb.Remove(sb.Length - 1, 1);

        mesh.text = sb.ToString();
    }
Beispiel #13
0
    public static void GotNewLetter(string letter)
    {
        int index = LetterSpawner.currentWordLettersLeft.IndexOf(letter);
        currentWordLetters[index] = letter;

        var aStringBuilder = new StringBuilder(currentWordLettersInString);

        if (index == 0)
        {
            aStringBuilder.Remove(1, 1);
            aStringBuilder.Insert(1, letter);
        }
        else
        {
            aStringBuilder.Remove(index * 2 + 1, 1);
            aStringBuilder.Insert(index * 2 + 1, letter);
        }

        currentWordLettersInString = aStringBuilder.ToString();

        LetterSpawner.currentWordLettersLeft[index] = "*";

        //for (int i = 0; i < LetterSpawner.currentWordLettersLeft.Count; i++)
        //    Debug.Log(LetterSpawner.currentWordLettersLeft[i]);
    }
    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);
    }
    static void Main()
    {
        string s;
        int inputLines = int.Parse(Console.ReadLine());
        int desiredWidth = int.Parse(Console.ReadLine());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < inputLines; i++)
        {
            s = Console.ReadLine();
            sb.Append(s.Trim() + " ");
        }
        sb.Remove(sb.Length - 1, 1);
        string[] sWords = sb.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        List<string> words = new List<string>(sWords);
        do
        {

            sb.Clear();
            sb.Append(words[0]);
            int currentWord = 1;
            while (sb.Length < desiredWidth && currentWord < words.Count)
            {
                sb.Append(" " + words[currentWord]);
                currentWord++;
            }
            if (sb.Length > desiredWidth)
            {
                sb.Remove(sb.Length - words[currentWord - 1].Length - 1, words[currentWord - 1].Length + 1);
                currentWord--;
            }
                if (sb.Length == desiredWidth || currentWord == 1)
            {
                Console.WriteLine(sb);
                words.RemoveRange(0, currentWord);
                continue;
            }
            int spacecount = currentWord - 1;
            int sizeOfSpaces = (desiredWidth - sb.Length + spacecount) / spacecount; // / (currentWord - 1)
            int numOfLongSpaces = (desiredWidth - sb.Length + spacecount) % spacecount;
            sb.Clear();
            sb.Append(words[0]);
            for (int i = 1; i <= spacecount; i++)
            {
                if (i <= numOfLongSpaces)
                    sb.Append(" ");
                sb.Append(new string(' ',sizeOfSpaces) + words[i]);
            }
            Console.WriteLine(sb);
            words.RemoveRange(0, currentWord);
        } while (words.Count > 0);
    }
Beispiel #16
0
 static void Main()
 {
     int n = int.Parse(Console.ReadLine());
     int[] array = new int[n];
     char[] separator = new char[] { ' ' };
     string[] inputArray = Console.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries);
     for (int index = 0; index < n; index++)
     {
         array[index] = int.Parse(inputArray[index]);
     }
     bool[] visitedElements = new bool[n];
     StringBuilder result = new StringBuilder();
     int startCycleIndex = -1;
     int currentElement = 0;
     while (true)
     {
         if (currentElement < 0 || currentElement >= n)
         {
             break;
         }
         if (visitedElements[currentElement])
         {
             startCycleIndex = currentElement;
             break;
         }
         visitedElements[currentElement] = true;
         result.Append(currentElement + " ");
         currentElement = array[currentElement];
     }
     if (startCycleIndex != -1) // We are in cycle
     {
         int startIndexOfCyclingIndex = result.ToString().IndexOf(startCycleIndex + " ");
         if (startIndexOfCyclingIndex > 1)
         {
             result[startIndexOfCyclingIndex - 1] = '(';
         }
         else
         {
             result.Insert(0, '(');
         }
         result.Remove(result.Length - 1, 1);
         result.Append(")");
         Console.WriteLine(result);
         return;
     }
     result.Remove(result.Length - 1, 1);
     Console.WriteLine(result);
 }
    static void Main()
    {
        StringBuilder line = new StringBuilder();
        string pattern = @"(?<![a-zA-Z])[A-Z]+(?![a-zA-Z])";
        Regex regex = new Regex(pattern);

        while (line.ToString() != "END")
        {          
            MatchCollection matches = regex.Matches(line.ToString());

            int offset = 0;
            foreach (Match match in matches)
            {
               string word = match.Value;
               string reversed = Reverse(word);
              
                if (reversed == word)
                {
                    reversed = DoubleEachLetter(reversed);
                }

                int index = match.Index;
                line = line.Remove(index + offset, word.Length);
                line = line.Insert(index + offset, reversed);
                offset += reversed.Length - word.Length;

            }

            Console.WriteLine(SecurityElement.Escape(line.ToString()));
            line = new StringBuilder(Console.ReadLine());
        }
    }
Beispiel #18
0
    public static void ReplaceTarget(List<string> words)
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            using (StreamWriter writer = new StreamWriter("temp.txt"))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(@"\b(");
                foreach (string word in words) sb.Append(word + "|");

                sb.Remove(sb.Length - 1, 1);
                sb.Append(@")\b");

                string pattern = @sb.ToString();
                Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                for (string line; (line = reader.ReadLine()) != null; )
                {
                    string newLine = rgx.Replace(line, "");
                    writer.WriteLine(newLine);
                }
            }
        }

        File.Delete("test.txt");
        File.Move("temp.txt", "test.txt");
    }
    /*
     21. Letters count

        Write a program that reads a string from the console and
        prints all different letters in the string along with
        information how many times each letter is found.

    */
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a word: ");
        string word = Console.ReadLine();
        StringBuilder strB = new StringBuilder(word);
        Dictionary<char, int> result = new Dictionary<char, int>();
        for(int i = 0; i < strB.Length; i++)
        {
            int count = 1;
            for(int j = i+1; j < strB.Length; j++)
            {
                if(strB[i]== strB[j])
                {
                    count++;
                    strB.Remove(j, 1);
                    j--;
                }
            }
            result.Add(strB[i], count);
        }
        for(int i = 0; i < strB.Length; i++)
        {
            Console.WriteLine("{0} - {1} {2}",strB[i], result[strB[i]], result[strB[i]] > 1 ? "times" : "time");
        }
    }
Beispiel #20
0
    static StringBuilder Move(StringBuilder input)
    {
        for (int i = 0; i < input.Length; i++)
        {
            StringBuilder newStr = new StringBuilder();
            char currChar = input[i];
            int newPosition;

            if (char.IsLower(currChar))
            {
                newPosition = (int)currChar - 96 + i;
                newPosition = newPosition % input.Length;
            }
            else
            {
                newPosition = (int)currChar - 64 + i;
                newPosition = newPosition % input.Length;
            }

            input.Remove(i, 1);
            input.Insert(newPosition, currChar);
        }

        return input;
    }
    static void Main()
    {
        string input = "We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
        string searchedWord = " in ";
        int sentenceEndIndex = new int();
        int searchedWordIndex = new int();
        StringBuilder sentences = new StringBuilder();
        StringBuilder modifyInput = new StringBuilder();
        modifyInput.Append(input);

        while (true)
        {
            searchedWordIndex = modifyInput.ToString().IndexOf(searchedWord);
            sentenceEndIndex = modifyInput.ToString().IndexOf(".");
            if (sentenceEndIndex > searchedWordIndex && searchedWordIndex >= 0)
            {
                        sentences.Append(modifyInput.ToString().Substring(0, sentenceEndIndex + 1));
            }
            else if (searchedWordIndex < 0)
            {
                break;
            }
            modifyInput.Remove(0, sentenceEndIndex + 1);
        }
        Console.WriteLine(sentences.ToString().Trim());
    }
    static string PrintPoli(decimal[] polynomial)
    {
        StringBuilder returnString = new StringBuilder();

        for (int i = polynomial.Length - 1; i >= 0; i--)
        {
            if (polynomial[i] != 0)
            {
                returnString.Append(polynomial[i] > 0 ? " + " : " - ");
                returnString.Append(Math.Abs(polynomial[i]));
                if (i != 0)
                {
                    returnString.Append(i > 1 ? "x^" + i : "x");
                }
            }
        }

        //delete extra characters at the beginning
        if (returnString[1] != '-')
        {
            returnString.Remove(0, 2);
            returnString.Insert(0, "  ");
        }

        return returnString.ToString();
    }
	//Find the length of longest chain starting from s
	private static int Bfs(string s, HashSet<string> dict){
		Queue<string> q = new Queue<string>();
		int current = 1, next = 0;
		int depth = 1; //If no chain, the length is 1
		q.Enqueue(s);
		while(current!=0){
			string currWord = q.Dequeue();
			current--;
			for(int i=0;i<currWord.Length;i++){
				StringBuilder sb = new StringBuilder(currWord);
				sb.Remove(i,1);
				string temp = sb.ToString();
				if(dict.Contains(temp)){
					if(temp.Length==1){ 
						return depth+1; //the chain ends at next level, so depth++
					}
					q.Enqueue(temp);
					next++;
				}
			}
			if(current==0){
				current = next;
				next = 0;
				depth++;
			}
		}
		//if no return inside while loop, chain ends at last level, so return depth-1.
		return depth-1; 
	}
Beispiel #24
0
    static void Main()
    {
        Dictionary<string, int> dict = new Dictionary<string, int>()
        {
                                    {"Rawr", 0},
                                    {"Rrrr", 1},
                                    {"Hsst", 2},
                                    {"Ssst", 3},
                                    {"Grrr", 4},
                                    {"Rarr", 5},
                                    {"Mrrr", 6},
                                    {"Psst", 7},
                                    {"Uaah", 8},
                                    {"Uaha", 9},
                                    {"Zzzz", 10},
                                    {"Bauu", 11},
                                    {"Djav", 12},
                                    {"Myau", 13},
                                    {"Gruh", 14},
        };
        string input = Console.ReadLine().Trim();
        long result = 0;
        int pow = 0;
        StringBuilder sb = new StringBuilder();
        sb.Append(input);
        for (int i = sb.Length-1; i >=0; i-=4)
        {
            string word = sb.ToString().Substring(i - 3, 4);
            sb.Remove(i-3,4);
            result += dict[word] * (long)Math.Pow(15, pow);
            pow++;

        }
        Console.WriteLine(result);
    }
 static void MoveRight(StringBuilder letters, int pos, int positions)
 {
     char letter = letters[pos];
     letters.Remove(pos, 1);
     int newPos = (pos + positions) % (letters.Length + 1);
     letters.Insert(newPos, letter);
 }
    private void PopulateControls()
    {
        int userId = Convert.ToInt32(Session["UserID"]);
        string itemName = "";
        if (Request.QueryString["term"] != null && Request.QueryString["term"] != "")
        {
            itemName = Request.QueryString["term"];
        }

        ItemTableBLL bll = new ItemTableBLL();
        DataTable dt = bll.GetItemPriceListByItemName(userId, itemName);

        StringBuilder items = new StringBuilder();
        items.Append("[");

        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                items.Append("{\"label\":" + "\"" + Convert.ToDouble(dr["ItemPrice"]).ToString("0.0##") + "\"},");
            }
            items.Remove(items.ToString().LastIndexOf(','), 1);
        }

        items.Append("]");

        Response.Write(items.ToString());
        Response.End();
    }
Beispiel #27
0
    static void Main()
    {
        //z-a+1
        //string[] words = Console.ReadLine().Split();
        string[] words = { "Telerik", "Academy" };
        StringBuilder extractLetters = new StringBuilder();
        int maxWordLength = 0;
        for (int i = 0; i < words.Length; i++)
            maxWordLength = Math.Max(maxWordLength, words[i].Length);
        for (int cycle = 1; cycle <= maxWordLength; cycle++)
        {
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length - cycle >= 0)
                    extractLetters.Append(words[i].Substring(words[i].Length - cycle, 1));
            }
        }

        int lettersCount = extractLetters.Length;

        for (int i = 0; i < lettersCount; i++)
        {
            char item = extractLetters[i];
            int moove = (char.ToLower(extractLetters[i]) + 1 - 'a') % lettersCount;
            extractLetters.Remove(i, 1);

            int newIndex = (i + moove) % lettersCount;
            //if (newIndex > i) newIndex--;
            // the actual index could have shifted due to the removal

            extractLetters.Insert(newIndex, item);
        }

        Console.WriteLine(extractLetters);
    }
Beispiel #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int userId = Convert.ToInt32(Session["UserID"]);
        string keywords = "";

        if (Request.QueryString["term"] != "" && Request.QueryString["term"] != null)
        {
            keywords = Request.QueryString["term"].Replace("%", "");

            StringBuilder items = new StringBuilder();
            items.Append("[");

            ItemTableBLL bll = new ItemTableBLL();
            DataTable dt = bll.GetItemNameListByKeywords(userId, keywords);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    items.Append("{");
                    items.Append("\"id\":" + "\"" + dr["ItemName"].ToString() + "\",");
                    items.Append("\"label\":" + "\"" + dr["ItemName"].ToString() + "\"");
                    items.Append("},");
                }
                items.Remove(items.ToString().LastIndexOf(','), 1);
            }

            items.Append("]");

            Response.Write(items.ToString());
            Response.End();
        }
    }
    public string ConvertFractionFromDecimalToBinary(double number, int baseoutput = 2)
    {
        StringBuilder builder = new StringBuilder();

        while (number != 0.0 && builder.Length<24)
        {
            number = number * baseoutput;
            if (number >= 1)
            {
                number = number - 1;
                builder.Append("1");
            }
            else
            {
                builder.Append("0");
            }
        }
        if (builder.Length == 24)
        {
            if (builder[23] == '1')
            {
                builder[22] = '1';
            }
            builder.Remove(builder.Length - 1, 1);

        }

        return builder.ToString();
    }
    protected void PopulateControls()
    {
        string itemName = "";
        int userId = Int32.Parse(Session["UserID"].ToString());
        if (Request.QueryString["term"] != null && Request.QueryString["term"] != "")
        {
            itemName = Request.QueryString["term"];
        }

        DataTable dt = ItemAccess.GetItemPriceListByName(userId, itemName);

        StringBuilder items = new StringBuilder();
        items.Append("[");

        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                items.Append("{\"label\":" + "\"" + Double.Parse(dr["ItemPrice"].ToString()).ToString("0.0##") + "\"},");
            }
            items.Remove(items.ToString().LastIndexOf(','), 1);
        }

        items.Append("]");

        Response.Write(items.ToString());
        Response.End();
    }
Beispiel #31
0
        public void Reset()
        {
            has_reached_end = false;

            ctx_stack.Clear();
            context = new WriterContext();
            ctx_stack.Push(context);

            inst_string_builder?.Remove(0, inst_string_builder.Length);
        }
        private string GetVaultNames()
        {
            StringBuilder sb = new StringBuilder();

            Vaults = MFilesServerApp.GetOnlineVaults();
            for (int i = 1; i < Vaults.Count + 1; i++)
            {
                sb.AppendLine($"({i}) {Vaults[i].Name}");
            }

            return(sb?.Remove(sb.Length - 2, 1).ToString());
        }
        /// <summary>
        /// Constructs the actual query
        /// </summary>
        /// <returns>A single update query</returns>
        public virtual string Build()
        {
            StringBuilder query = new StringBuilder();

            if (CommentOut)
            {
                query.Append("-- ");
            }

            // Return empty if there are no values or where clause or no table name set
            if (!WhereClause.HasConditions)
            {
                return(string.Empty);
            }

            query.Append("UPDATE ");
            query.Append(SQLUtil.GetTableName <T>());
            query.Append(" SET ");

            bool hasValues = false;

            foreach (var field in _databaseFields)
            {
                object value = field.Item2.GetValue(_value.Data);

                Array arr = value as Array;
                if (arr != null)
                {
                    for (int i = 0; i < arr.Length; i++)
                    {
                        object v = arr.GetValue(i);
                        if (v == null)
                        {
                            continue;
                        }

                        query.Append(SQLUtil.AddBackQuotes(field.Item3.First().Name + (field.Item3.First().StartAtZero ? i : i + 1)));
                        query.Append("=");
                        query.Append(SQLUtil.ToSQLValue(v, noQuotes: field.Item3.Any(a => a.NoQuotes)));
                        query.Append(SQLUtil.CommaSeparator);

                        hasValues = true;
                    }
                    continue;
                }

                if (value == null)
                {
                    continue;
                }

                if (field.Item2.Name != "VerifiedBuild" || !Settings.SkipOnlyVerifiedBuildUpdateRows)
                {
                    hasValues = true;
                }

                query.Append(field.Item1);
                query.Append("=");
                query.Append(SQLUtil.ToSQLValue(value, noQuotes: field.Item3.Any(a => a.NoQuotes)));
                query.Append(SQLUtil.CommaSeparator);
            }
            if (!hasValues)
            {
                return(string.Empty);
            }

            query.Remove(query.Length - SQLUtil.CommaSeparator.Length, SQLUtil.CommaSeparator.Length); // remove last ", "

            query.Append(" WHERE ");
            query.Append(WhereClause.Build());
            query.Append(";");

            if (!string.IsNullOrWhiteSpace(_value.Comment))
            {
                query.Append(" -- " + _value.Comment);
            }

            return(query.ToString());
        }
        public string Build()
        {
            if (_conditions == null || _conditions.Count == 0)
            {
                return(string.Empty);
            }

            StringBuilder whereClause = new StringBuilder();

            if (_onlyPrimaryKeys && _conditions.GetPrimaryKeyCount() == 1)
            {
                var field = _databaseFields.Single(f => f.Item2 == _primaryKeyReflectionField);

                whereClause.Append(field.Item1);
                if (_conditions.Count == 1)
                {
                    whereClause.Append("=");
                    whereClause.Append(field.Item2.GetValue(_conditions.First().Data));
                }
                else
                {
                    whereClause.Append(" IN (");

                    foreach (Row <T> condition in _conditions)
                    {
                        object value = field.Item2.GetValue(condition.Data);
                        whereClause.Append(SQLUtil.ToSQLValue(value));

                        if (!string.IsNullOrEmpty(condition.Comment))
                        {
                            whereClause.Append(" /*" + condition.Comment + "*/");
                        }

                        whereClause.Append(SQLUtil.CommaSeparator);
                    }
                    whereClause.Remove(whereClause.Length - SQLUtil.CommaSeparator.Length, SQLUtil.CommaSeparator.Length); // remove last ", "

                    whereClause.Append(")");
                }
            }
            else
            {
                foreach (Row <T> condition in _conditions)
                {
                    whereClause.Append("(");
                    foreach (var field in _databaseFields)
                    {
                        object value = field.Item2.GetValue(condition.Data);

                        if (value == null ||
                            (_onlyPrimaryKeys &&
                             field.Item3.Any(a => !a.IsPrimaryKey)))
                        {
                            continue;
                        }

                        whereClause.Append(field.Item1);

                        whereClause.Append("=");
                        whereClause.Append(SQLUtil.ToSQLValue(value));
                        whereClause.Append(" AND ");
                    }

                    whereClause.Remove(whereClause.Length - 5, 5); // remove last " AND "
                    whereClause.Append(")");
                    whereClause.Append(" OR ");
                }
                whereClause.Remove(whereClause.Length - 4, 4); // remove last " OR ";
            }

            return(whereClause.ToString());
        }
        /// <summary>
        /// Constructs the actual query
        /// </summary>
        /// <returns>Single insert row (data)</returns>
        public string Build()
        {
            if (NoData)
            {
                return("-- " + _headerComment + Environment.NewLine);
            }

            StringBuilder query = new StringBuilder();

            if (_row.CommentOut)
            {
                query.Append("-- ");
            }

            query.Append("(");

            foreach (var field in _databaseFields)
            {
                object value = field.Item2.GetValue(_row.Data);
                if (value == null)
                {
                    if (field.Item3.Any(a => a.Nullable))
                    {
                        query.Append("NULL");
                        query.Append(SQLUtil.CommaSeparator);
                    }
                    else
                    {
                        query.Append("UNKNOWN");
                        query.Append(SQLUtil.CommaSeparator);
                    }
                }
                else
                {
                    Array arr = value as Array;
                    if (arr != null)
                    {
                        foreach (object v in arr)
                        {
                            if (v == null)
                            {
                                if (field.Item3.Any(a => a.Nullable))
                                {
                                    query.Append("NULL");
                                }
                                else
                                {
                                    query.Append("UNKNOWN");
                                }
                            }
                            else
                            {
                                query.Append(SQLUtil.ToSQLValue(v, noQuotes: field.Item3.Any(a => a.NoQuotes)));
                            }

                            query.Append(SQLUtil.CommaSeparator);
                        }
                    }
                    else
                    {
                        query.Append(SQLUtil.ToSQLValue(value, noQuotes: field.Item3.Any(a => a.NoQuotes == true)));
                        query.Append(SQLUtil.CommaSeparator);
                    }
                }
            }
            query.Remove(query.Length - SQLUtil.CommaSeparator.Length, SQLUtil.CommaSeparator.Length); // remove last ", "
            query.Append("),");

            if (!string.IsNullOrWhiteSpace(_row.Comment))
            {
                query.Append(" -- " + _row.Comment);
            }

            return(query.ToString());
        }
Beispiel #36
0
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="iot_flmeterdata"></param>
        /// <returns>是否成功</returns>
        public string GetUpdateStr(IOT_FLMeterData iot_flmeterdata)
        {
            StringBuilder part1 = new StringBuilder();

            part1.Append("update iot_flmeterdata set ");
            if (iot_flmeterdata.communicateNo != null)
            {
                part1.Append("communicateNo = @communicateNo,");
            }
            if (iot_flmeterdata.FLMeterNo != null)
            {
                part1.Append("FLMeterNo = @FLMeterNo,");
            }
            if (iot_flmeterdata.siteNo != null)
            {
                part1.Append("siteNo = @siteNo,");
            }
            if (iot_flmeterdata.InstantTime != null)
            {
                part1.Append("InstantTime = @InstantTime,");
            }
            if (iot_flmeterdata.ReceivTime != null)
            {
                part1.Append("ReceivTime = @ReceivTime,");
            }
            if (iot_flmeterdata.StdSum != null)
            {
                part1.Append("StdSum = @StdSum,");
            }
            if (iot_flmeterdata.WorkSum != null)
            {
                part1.Append("WorkSum = @WorkSum,");
            }
            if (iot_flmeterdata.StdFlow != null)
            {
                part1.Append("StdFlow = @StdFlow,");
            }
            if (iot_flmeterdata.WorkFlow != null)
            {
                part1.Append("WorkFlow = @WorkFlow,");
            }
            if (iot_flmeterdata.Temperature != null)
            {
                part1.Append("Temperature = @Temperature,");
            }
            if (iot_flmeterdata.Pressure != null)
            {
                part1.Append("Pressure = @Pressure,");
            }
            if (iot_flmeterdata.FMState != null)
            {
                part1.Append("FMState = @FMState,");
            }
            if (iot_flmeterdata.FMStateMsg != null)
            {
                part1.Append("FMStateMsg = @FMStateMsg,");
            }
            if (iot_flmeterdata.RTUState != null)
            {
                part1.Append("RTUState = @RTUState,");
            }
            if (iot_flmeterdata.RTUStateMsg != null)
            {
                part1.Append("RTUStateMsg = @RTUStateMsg,");
            }
            if (iot_flmeterdata.SumTotal != null)
            {
                part1.Append("SumTotal = @SumTotal,");
            }
            if (iot_flmeterdata.RemainMoney != null)
            {
                part1.Append("RemainMoney = @RemainMoney,");
            }
            if (iot_flmeterdata.RemainVolume != null)
            {
                part1.Append("RemainVolume = @RemainVolume,");
            }
            if (iot_flmeterdata.Overdraft != null)
            {
                part1.Append("Overdraft = @Overdraft,");
            }
            if (iot_flmeterdata.RemoteChargeMoney != null)
            {
                part1.Append("RemoteChargeMoney = @RemoteChargeMoney,");
            }
            if (iot_flmeterdata.RemoteChargeTimes != null)
            {
                part1.Append("RemoteChargeTimes = @RemoteChargeTimes,");
            }
            if (iot_flmeterdata.Price != null)
            {
                part1.Append("Price = @Price,");
            }
            if (iot_flmeterdata.ValveState != null)
            {
                part1.Append("ValveState = @ValveState,");
            }
            if (iot_flmeterdata.ValveStateMsg != null)
            {
                part1.Append("ValveStateMsg = @ValveStateMsg,");
            }
            if (iot_flmeterdata.PowerVoltage != null)
            {
                part1.Append("PowerVoltage = @PowerVoltage,");
            }
            if (iot_flmeterdata.BatteryVoltage != null)
            {
                part1.Append("BatteryVoltage = @BatteryVoltage,");
            }
            if (iot_flmeterdata.Reserve1 != null)
            {
                part1.Append("Reserve1 = @Reserve1,");
            }
            if (iot_flmeterdata.Reserve2 != null)
            {
                part1.Append("Reserve2 = @Reserve2,");
            }
            if (iot_flmeterdata.Reserve3 != null)
            {
                part1.Append("Reserve3 = @Reserve3,");
            }
            if (iot_flmeterdata.Reserve4 != null)
            {
                part1.Append("Reserve4 = @Reserve4,");
            }
            int n = part1.ToString().LastIndexOf(",");

            part1.Remove(n, 1);
            part1.Append(" where Id= @Id  ");
            return(part1.ToString());
        }
Beispiel #37
0
        }   //  end displayHelp

        private void onRegression(object sender, EventArgs e)
        {
            //  because of reset selection button, need to clear the concatenated fields nefore doing regression
            concatSpecies.Remove(0, concatSpecies.Length);
            concatLiveDead = "";
            concatProduct  = "";

            //  make sure a UOM has been selected
            if (volType == "")
            {
                MessageBox.Show("Please select a valid UOM.", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                UnitOfMeasure.Focus();
                return;
            }   //  endif

            //  make sure at least one speciesGroup was selected
            int anySelected = rgList.Sum(r => r.rgSelected);

            if (anySelected == 0)
            {
                MessageBox.Show("No species groups selected.\nPlease select at least one group to process.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }   //  endif

            MainTitle_TW.Remove(0, MainTitle_TW.Length);
            MainTitle.Remove(0, MainTitle.Length);
            //  setup title for graph
            if (topwoodRegress)
            {
                MainTitle_TW.Append(volumeToUse);
                MainTitle_TW.Append(volType);
                MainTitle.Append(volumeToUse);
                MainTitle.Append(volType);
                MainTitle_TW.Append(" (Primary + Secondary)");
                MainTitle.Append(" Primary");
            }
            else if (!topwoodRegress)
            {
                MainTitle.Append(volumeToUse);
                MainTitle.Append(volType);
                MainTitle.Append(" Primary");
            }   //  endif topwood

            //  pull data for species selected
            List <float>  justDBH    = new List <float>();
            List <double> justVol    = new List <double>();
            List <double> justVol_TW = new List <double>();

            concatLiveDead = "";
            concatProduct  = "";
            concatSpecies.Remove(0, concatSpecies.Length);
            foreach (RegressGroups rl in rgList)
            {
                if (rl.rgSelected == 1)
                {
                    //  load up arrays
                    foreach (TreeCalculatedValuesDO jt in
                             Global.BL.getRegressTrees(rl.rgSpecies, rl.rgProduct, rl.rgLiveDead, "M"))
                    {
                        // load DBH or DRC
                        float jd = new float();
                        if (jt.Tree.DBH > 0)
                        {
                            jd = jt.Tree.DBH;
                        }
                        else if (jt.Tree.DRC > 0)
                        {
                            jd = jt.Tree.DRC;
                        }
                        justDBH.Add(jd);

                        //  load volume  for primary regression
                        double jv = new double();
                        //  need primary whether topwood checked or not
                        switch (volType)
                        {
                        case "BDFT":
                            if (volumeToUse == "Gross")
                            {
                                jv = jt.GrossBDFTPP;
                            }
                            else if (volumeToUse == "Net")
                            {
                                jv = jt.NetBDFTPP;
                            }
                            break;

                        case "CUFT":
                            if (volumeToUse == "Gross")
                            {
                                jv = jt.GrossCUFTPP;
                            }
                            else if (volumeToUse == "Net")
                            {
                                jv = jt.NetCUFTPP;
                            }
                            break;

                        case "CORDS":
                            jv = jt.CordsPP;
                            break;
                        }   //  end switch
                        justVol.Add(jv);

                        if (topwoodRegress)
                        {
                            switch (volType)
                            {
                            case "BDFT":
                                if (volumeToUse == "Gross")
                                {
                                    jv = jt.GrossBDFTSP;
                                }
                                else if (volumeToUse == "Net")
                                {
                                    jv = jt.NetBDFTSP;
                                }
                                break;

                            case "CUFT":
                                if (volumeToUse == "Gross")
                                {
                                    jv = jt.GrossCUFTSP;
                                }
                                else if (volumeToUse == "Net")
                                {
                                    jv = jt.NetCUFTSP;
                                }
                                break;

                            case "CORDS":
                                jv = jt.CordsSP;
                                break;
                            } //  end switch
                            justVol_TW.Add(jv);
                        }     //  endif topwood
                    }         //  end foreach loop on trees
                    //  update species/product/livedead for current group
                    updateHeaderInfo(rl);
                } //  endif selected
            }     //  end foreach on groups

            //  load arrays to pass to regression
            float[]  DBHarray = new float[justDBH.Count];
            double[] VolArray = new double[justVol.Count];
            int      nthItem  = 0;

            foreach (float jd in justDBH)
            {
                DBHarray[nthItem] = jd;
                nthItem++;
            }   //  end foreach loop
            nthItem = 0;
            foreach (double jv in justVol)
            {
                VolArray[nthItem] = jv;
                nthItem++;
            }   //  end foreach loop

            //  call regression
            //  need to create model code to send for graph title
            switch (MainTitle.ToString())
            {
            case "GrossCUFT Primary":
                TitleCode = 1;
                break;

            case "NetCUFT Primary":
                TitleCode = 2;
                break;

            case "GrossBDFT Primary":
                TitleCode = 3;
                break;

            case "NetBDFT Primary":
                TitleCode = 4;
                break;

            case "Cords Primary":
                TitleCode = 5;
                break;
            }   //  end switch on MainTitle

            //  Call local volume library for primary regression
            if (nthItem < 3)
            {
                MessageBox.Show("Too few trees.  Need more than two trees\nto run regression analysis.", "WARING", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            GetLocalTable(DBHarray, VolArray, nthItem, TitleCode, ref coef1, ref coef2, ref coef3, ref meanSqEr, ref rSquared, ref ModelCode);

            //  create DBH class list
            float minDBH = DBHarray.Min();
            float maxDBH = DBHarray.Max();

            if (ModelCode != 0)
            {
                //  update regression results
                updateResults(volType, "Primary", concatSpecies, concatProduct, concatLiveDead, minDBH, maxDBH);
            }   //  endif cancel was clicked


            // then regress secondary
            if (topwoodRegress)
            {
                //  add TW to primary
                for (int j = 0; j < justVol_TW.Count; j++)
                {
                    justVol[j] += justVol_TW[j];
                }

                //  then dump into array to pass to regression
                Array.Clear(VolArray, 0, VolArray.Length);
                nthItem = 0;
                foreach (double jv in justVol)
                {
                    VolArray[nthItem] = jv;
                    nthItem++;
                }   //  end foreach loop

                //  change main title for secondary
                switch (MainTitle_TW.ToString())
                {
                case "GrossCUFT (Primary + Secondary)":
                    TitleCode = 11;
                    break;

                case "NetCUFT (Primary + Secondary)":
                    TitleCode = 21;
                    break;

                case "GrossBDFT (Primary + Secondary)":
                    TitleCode = 31;
                    break;

                case "NetBDFT (Primary + Secondary)":
                    TitleCode = 41;
                    break;

                case "Cords (Primary + Secondary)":
                    TitleCode = 51;
                    break;
                }   //  end switch on MainTitle

                //  call regression for secondary
                GetLocalTable(DBHarray, VolArray, nthItem, TitleCode, ref coef1, ref coef2, ref coef3, ref meanSqEr, ref rSquared, ref ModelCode);

                if (ModelCode != 0)
                {
                    //  min and max DBH will be the same
                    //  update results list
                    updateResults(volType, "Secondary", concatSpecies, concatProduct, concatLiveDead, minDBH, maxDBH);
                } //  endif cancel was clicked
            }     //  endif topwood

            //  Save results
            Global.BL.SaveRegress(resultsList);

            return;
        }   //  end onRegression
        public string[] Split(string src, string delimiters)
        {
            ArrayList     parts   = new ArrayList();
            StringBuilder sb      = new StringBuilder();
            bool          escaped = false;

            char contextMarker = Char.MinValue;

            foreach (char c in src)
            {
                if (delimiters.IndexOf(c) != -1 && !escaped)
                {
                    if (contextMarker != Char.MinValue)
                    {
                        sb.Append(c);
                    }
                    else
                    {
                        if (sb.Length <= 0)
                        {
                            continue;
                        }
                        parts.Add(sb.ToString());
                        sb.Remove(0, sb.Length);
                    }
                }
                else if (c == '\\' && _escapeBackslash)
                {
                    escaped = !escaped;
                }
                else
                {
                    int contextIndex = ContextMarkers.IndexOf(c);
                    if (!escaped && contextIndex != -1)
                    {
                        // if we have found the closing marker for our open
                        // marker, then close the context
                        if ((contextIndex % 2) == 1)
                        {
                            if (contextMarker == ContextMarkers[contextIndex - 1])
                            {
                                contextMarker = Char.MinValue;
                            }
                        }
                        else
                        {
                            // if the opening and closing context markers are
                            // the same then we will always find the opening
                            // marker.
                            if (contextMarker == ContextMarkers[contextIndex + 1])
                            {
                                contextMarker = Char.MinValue;
                            }
                            else if (contextMarker == Char.MinValue)
                            {
                                contextMarker = c;
                            }
                        }
                    }

                    sb.Append(c);
                }
            }
            if (sb.Length > 0)
            {
                parts.Add(sb.ToString());
            }
            return((string[])parts.ToArray(typeof(string)));
        }
Beispiel #39
0
        public static StringBuilder Remove(this StringBuilder sb, char ch)
        {
            int removed_count;

            return(sb.Remove(ch, out removed_count));
        }
Beispiel #40
0
 public override void Use(Player p, string message)
 {
     if (message == "")
     {
         Help(p); return;
     }
     string[] split = message.Split(' ');
     if (split[0] == "add")
     {
         if (split.Length < 2)
         {
             Help(p); return;
         }
         Player pl = Player.Find(split[1]);
         if (pl != null)
         {
             split[1] = pl.name;
         }
         if (VIP.Find(split[1]))
         {
             Player.SendMessage(p, (pl == null ? "" : pl.color) + split[1] + " is already a VIP!");
         }
         else
         {
             VIP.Add(split[1]);
             Player.SendMessage(p, (pl == null ? "" : pl.color) + split[1] + " is now a VIP.");
             if (pl != null)
             {
                 Player.SendMessage(pl, "You are now a VIP!");
             }
         }
     }
     else if (split[0] == "remove")
     {
         if (split.Length < 2)
         {
             Help(p); return;
         }
         Player pl = Player.Find(split[1]);
         if (pl != null)
         {
             split[1] = pl.name;
         }
         if (!VIP.Find(split[1]))
         {
             Player.SendMessage(p, (pl == null ? "" : pl.color) + split[1] + " is not a VIP!");
         }
         else
         {
             VIP.Remove(split[1]);
             Player.SendMessage(p, (pl == null ? "" : pl.color) + split[1] + " is no longer a VIP.");
             if (pl != null)
             {
                 Player.SendMessage(pl, "You are no longer a VIP!");
             }
         }
     }
     else if (split[0] == "list")
     {
         List <string> list = VIP.GetAll();
         if (list.Count < 1)
         {
             Player.SendMessage(p, "There are no VIPs.");
         }
         else
         {
             StringBuilder sb = new StringBuilder();
             foreach (string name in list)
             {
                 sb.Append(name).Append(", ");
             }
             Player.SendMessage(p, "There are " + list.Count + " VIPs:");
             Player.SendMessage(p, sb.Remove(sb.Length - 2, 2).ToString());
         }
     }
     else
     {
         Help(p);
     }
 }
Beispiel #41
0
 public override void Transform(StringBuilder css)
 {
     css.Remove(MatchIndex, MatchLength);
     css.Insert(MatchIndex, "url(" + DataUri + ")");
 }
Beispiel #42
0
        public void WriteMse(List <FNamespace> namespaces, TextWriter writer)
        {
            var line = new StringBuilder();

            line.AppendLine("(Moose.Model (id: 1)");
            line.AppendLine("\t(name 'PMC#')");
            line.AppendLine("\t(entity");
            for (int i = 0; i < namespaces.Count; i++)
            {
                line.AppendLine("\t\t(FAMIX.Package (id: " + namespaces[i].NId + ")");
                line.AppendLine("\t\t\t(name '" + namespaces[i].NName + "')");
                if (namespaces[i].NPackagedIn > 1)
                {
                    line.AppendLine("\t\t\t(packagedIn (idref: " + namespaces[i].NPackagedIn + "))");
                }
                line.AppendLine("\t\t\t)");

                for (int k = 0; k < namespaces[i].NClasses.Count; k++)
                {
                    line.AppendLine("\t\t(FAMIX.Class (id: " + namespaces[i].NClasses[k].CId + ")");
                    line.AppendLine("\t\t\t(name '" + namespaces[i].NClasses[k].CName + "')");
                    line.AppendLine("\t\t\t(packagedIn (idref: " + namespaces[i].NId + "))");
                    if (namespaces[i].NClasses[k].CIsAbstract)
                    {
                        line.AppendLine("\t\t\t(isAbstract true))");
                    }
                    else
                    {
                        line.AppendLine("\t\t\t(isAbstract false))");
                    }
                    for (int x = 0; x < namespaces[i].NClasses[k].CMethods.Count; x++)
                    {
                        line.AppendLine("\t\t(FAMIX.Method (id: " + namespaces[i].NClasses[k].CMethods[x].MId + ")");
                        line.AppendLine("\t\t\t(name '" + namespaces[i].NClasses[k].CMethods[x].MName + "')");
                        line.AppendLine("\t\t\t(accessControlQualifier '" +
                                        namespaces[i].NClasses[k].CMethods[x].mMccessControlQualifier + "')");
                        line.AppendLine("\t\t\t(belongsTo (idref: " + namespaces[i].NClasses[k].CId + "))");
                        line.AppendLine("\t\t\t(LOC " + namespaces[i].NClasses[k].CMethods[x].Loc + ")");
                        line.AppendLine("\t\t\t(packagedIn (idref: " + namespaces[i].NId + "))");
                        line.AppendLine("\t\t\t(signature '" + namespaces[i].NClasses[k].CMethods[x].MSignature + "'))");
                    }
                    for (int n = 0; n < namespaces[i].NClasses[k].cCFields.Count; n++)
                    {
                        line.AppendLine("\t\t(FAMIX.Attribute (id: " + namespaces[i].NClasses[k].cCFields[n].FID + ")");
                        line.AppendLine("\t\t\t(name '" + namespaces[i].NClasses[k].cCFields[n].FName + "')");
                        if (namespaces[i].NClasses[k].cCFields[n].FAccessControlQualifier != "")
                        {
                            line.AppendLine("\t\t\t(accessControlQualifier '" +
                                            namespaces[i].NClasses[k].cCFields[n].FAccessControlQualifier + "')");
                        }
                        line.AppendLine("\t\t\t(belongsTo (idref: " + namespaces[i].NClasses[k].CId + ")))");
                    }
                }
                for (int x = 0; x < namespaces[i].FInheritance.Count; x++)
                {
                    line.AppendLine("(FAMIX.InheritanceDefinition (id: " + namespaces[i].FInheritance[x].IId + ")");
                    line.AppendLine("\t\t\t(stub false)");
                    line.AppendLine("\t\t\t(subclass (idref: " + namespaces[i].FInheritance[x].SubClass + "))");
                    line.AppendLine("\t\t\t(superclass (idref: " + namespaces[i].FInheritance[x].SuperClass + ")))");
                }
                for (int xx = 0; xx < namespaces[i].FInvoc.Count; xx++)
                {
                    line.AppendLine("(FAMIX.Invocation (id: " + namespaces[i].FInvoc[xx].FID + ")");
                    line.AppendLine("\t\t\t(candidate (idref: " + namespaces[i].FInvoc[xx].FCandidate + "))");
                    line.AppendLine("\t\t\t(invokedBy (idref: " + namespaces[i].FInvoc[xx].FInvokedBy + "))");
                    line.AppendLine("\t\t\t(invokes '" + namespaces[i].FInvoc[xx].FName + "')");
                    line.AppendLine("\t\t\t(stub false))");
                }
                for (int xxx = 0; xxx < namespaces[i].FAccess.Count; xxx++)
                {
                    line.AppendLine("(FAMIX.Access (id: " + namespaces[i].FAccess[xxx].AID + ")");
                    line.AppendLine("\t\t\t(accessedIn (idref: " + namespaces[i].FAccess[xxx].ABelongsTo + "))");
                    line.AppendLine("\t\t\t(accesses (idref: " + namespaces[i].FAccess[xxx].AAccesses + "))");
                    line.AppendLine("\t\t\t(stub false))");
                }
            }
            line.Remove(line.Length - 2, 1);
            line.AppendLine(")");
            line.AppendLine("(sourceLanguage 'C#'))");
            writer.Write(line.ToString());
        }
Beispiel #43
0
        /// <summary>
        /// 从字符串模板定义中加载模板结果
        /// </summary>
        /// <param name="str"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static string FromPartString(string str, dpz3.Xml.XmlNode table, dpz3.Xml.XmlNode field)
        {
            // 字符串创建器
            StringBuilder sb = new StringBuilder();

            // 命令解析器
            ParseType     pt    = ParseType.Normal;
            StringBuilder sbCmd = new StringBuilder();

            for (int i = 0; i < str.Length; i++)
            {
                char chr = str[i];

                switch (chr)
                {
                case '$':
                    if (pt == ParseType.Define)
                    {
                        sb.Append(chr);
                        pt = ParseType.Normal;
                    }
                    else
                    {
                        pt = ParseType.Define;
                    }
                    break;

                case '{':
                    if (pt == ParseType.Define)
                    {
                        if (sbCmd.Length > 0)
                        {
                            throw new Exception("语法错误");
                        }
                        sbCmd.Append(chr);
                    }
                    else
                    {
                        sb.Append(chr);
                    }
                    break;

                case '}':
                    if (pt == ParseType.Define)
                    {
                        if (sbCmd.Length <= 0)
                        {
                            throw new Exception("语法错误");
                        }
                        if (sbCmd[0] != '{')
                        {
                            throw new Exception("语法错误");
                        }

                        // 获取定义内容
                        sbCmd.Remove(0, 1);
                        string cmdStr = sbCmd.ToString();
                        sbCmd.Clear();

                        string[] cmds = cmdStr.Split('.');
                        if (cmds.Length != 2)
                        {
                            throw new Exception($"不支持的对象\"{cmdStr}\"");
                        }

                        // 判断命令类型
                        switch (cmds[0])
                        {
                        case "table":
                            sb.Append(table.Attr[cmds[1]]);
                            break;

                        case "field":
                            if (cmds[1] == "data")
                            {
                                sb.Append(field["data"].Attr[cmds[2]]);
                            }
                            else
                            {
                                sb.Append(field.Attr[cmds[1]]);
                            }
                            //sb.Append(field.GetType().GetProperty(cmds[1]).GetValue(field));
                            break;

                        default: throw new Exception($"不支持的对象\"{cmdStr}\"");
                        }

                        // 重置解析模式
                        pt = ParseType.Normal;
                    }
                    else
                    {
                        sb.Append(chr);
                    }
                    break;

                default:
                    if (pt == ParseType.Define)
                    {
                        sbCmd.Append(chr);
                    }
                    else
                    {
                        sb.Append(chr);
                    }
                    break;
                }
            }

            return(sb.ToString());
        }
Beispiel #44
0
        /// <summary>
        /// 生成商品的促销信息
        /// </summary>
        /// <param name="singlePromotionInfo">单品促销活动</param>
        /// <param name="buySendPromotionList">买送促销活动列表</param>
        /// <param name="fullSendPromotionInfo">满赠促销活动</param>
        /// <param name="fullCutPromotionInfo">满减促销活动</param>
        /// <returns></returns>
        public static string GeneratePromotionMsg(SinglePromotionInfo singlePromotionInfo, List <BuySendPromotionInfo> buySendPromotionList, FullSendPromotionInfo fullSendPromotionInfo, FullCutPromotionInfo fullCutPromotionInfo)
        {
            StringBuilder promotionMsg = new StringBuilder();

            //单品促销
            if (singlePromotionInfo != null)
            {
                //折扣类别
                switch (singlePromotionInfo.DiscountType)
                {
                case 0:    //折扣
                    promotionMsg.AppendFormat("折扣:{0}折<br/>", singlePromotionInfo.DiscountValue);
                    break;

                case 1:    //直降
                    promotionMsg.AppendFormat("直降:{0}元<br/>", singlePromotionInfo.DiscountValue);
                    break;

                case 2:    //折后价
                    promotionMsg.AppendFormat("折后价:{0}元<br/>", singlePromotionInfo.DiscountValue);
                    break;
                }

                //积分
                if (singlePromotionInfo.PayCredits > 0)
                {
                    promotionMsg.AppendFormat("赠送{0}:{1}<br/>", Credits.PayCreditName, singlePromotionInfo.PayCredits);
                }

                //优惠劵
                if (singlePromotionInfo.CouponTypeId > 0)
                {
                    CouponTypeInfo couponTypeInfo = Coupons.GetCouponTypeById(singlePromotionInfo.CouponTypeId);
                    if (couponTypeInfo != null)
                    {
                        promotionMsg.AppendFormat("赠送优惠劵:{0}<br/>", couponTypeInfo.Name);
                    }
                }
            }
            //买送促销
            if (buySendPromotionList != null && buySendPromotionList.Count > 0)
            {
                promotionMsg.Append("买送促销:");
                foreach (BuySendPromotionInfo buySendPromotionInfo in buySendPromotionList)
                {
                    promotionMsg.AppendFormat("买{0}送{1},", buySendPromotionInfo.BuyCount, buySendPromotionInfo.SendCount);
                }
                promotionMsg.Remove(promotionMsg.Length - 1, 1);
                promotionMsg.Append("<br/>");
            }
            //满赠促销
            if (fullSendPromotionInfo != null)
            {
                promotionMsg.Append("满赠促销:");
                promotionMsg.AppendFormat("满{0}元加{1}元<br/>", fullSendPromotionInfo.LimitMoney, fullSendPromotionInfo.AddMoney);
            }
            //满减促销
            if (fullCutPromotionInfo != null)
            {
                promotionMsg.Append("满减促销:");
                promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney1, fullCutPromotionInfo.CutMoney1);
                if (fullCutPromotionInfo.LimitMoney2 > 0 && fullCutPromotionInfo.CutMoney2 > 0)
                {
                    promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney2, fullCutPromotionInfo.CutMoney2);
                }
                if (fullCutPromotionInfo.LimitMoney3 > 0 && fullCutPromotionInfo.CutMoney3 > 0)
                {
                    promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney3, fullCutPromotionInfo.CutMoney3);
                }
                promotionMsg.Remove(promotionMsg.Length - 1, 1);
                promotionMsg.Append("<br/>");
            }

            return(promotionMsg.Length > 0 ? promotionMsg.Remove(promotionMsg.Length - 5, 5).ToString() : "");
        }
        public static TreeNode ReadTree(string title)
        {
            typeList = new List <string>();
            foreach (var type in monitorType)
            {
                typeList.Add(type.FullName);
            }

            TreeNode root = new TreeNode(title);

            foreach (var type in monitorType)
            {
                FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public | BindingFlags.GetField);
                foreach (FieldInfo f in fields)
                {
                    var      data     = f.GetValue(null);
                    string   typeName = data.GetType().FullName;
                    TreeNode node     = null;
                    if (data is IEnumerable)
                    {
                        int         result     = 0;
                        IEnumerator enumerator = (data as IEnumerable).GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            result++;
                        }

                        node = new TreeNode(f.Name + separator + f.Name + ".Count:" + result);
                    }
                    else
                    {
                        node = new TreeNode(f.Name);
                    }

                    if (typeName.StartsWith("System.Collections.Generic.List`1[[System.String,"))
                    {
                        foreach (var m in data as List <string> )
                        {
                            TreeNode item = new TreeNode(m);
                            node.Nodes.Add(item);
                        }
                    }
                    else if (typeName.StartsWith("System.Collections.Generic.List`1[[System.Int32,"))
                    {
                        foreach (var m in data as List <int> )
                        {
                            TreeNode item = new TreeNode(m.ToString());
                            node.Nodes.Add(item);
                        }
                    }
                    else if (typeName.StartsWith("System.Collections.Generic.List`1[[") && typeList.Exists(p => typeName.StartsWith("System.Collections.Generic.List`1[[" + p)))
                    {
                        foreach (var m in (data as IEnumerable))
                        {
                            Dictionary <string, object> dic = new Dictionary <string, object>();
                            PropertyInfo[] ps = m.GetType().GetProperties();
                            foreach (var p in ps)
                            {
                                object obj = p.GetValue(m, null);
                                dic.Add(p.Name, obj);
                            }

                            StringBuilder content = new StringBuilder();
                            foreach (var c in dic)
                            {
                                content.AppendFormat("{0}:{1}{2}", c.Key, c.Value, separator);
                            }

                            if (content.Length > 0)
                            {
                                content.Remove(content.Length - separator.Length, separator.Length);
                            }

                            TreeNode itemNode = new TreeNode(content.ToString());
                            node.Nodes.Add(itemNode);
                        }
                    }
                    else if (typeList.Exists(p => typeName.StartsWith(p)))
                    {
                        var typeFullName = typeList.Find(p => typeName.StartsWith(p));
                    }

                    root.Nodes.Add(node);
                }
            }

            return(root);
        }
Beispiel #46
0
        private void GetInitialAddresses()
        {
            List <Address> allAddresses = CacheLayer.AllAddresses();
            List <Client>  allClients   = CacheLayer.AllClients();

            Debug.WriteLine("cur company: " + curCompany.Name);

            List <Client> companyClients = allClients.Where(c => c.Company.Equals(curCompany)).ToList();

            Debug.WriteLine("companyClients null: " + (companyClients == null).ToString());
            Debug.WriteLine("companyClients empty: " + (companyClients.Count == 0).ToString());
            Debug.WriteLine("company clients:");
            foreach (Client client in companyClients)
            {
                Debug.WriteLine(client.LastName);
            }

            // addresses that match clients of the company
            List <Address> matchingAddresses = companyClients.Select(c => c.Address).ToList();

            // now, match the qs
            matchingAddresses = matchingAddresses.Where(a => a.Address1.ToLower().StartsWith(term.ToLower())).ToList();

            Debug.WriteLine("matching addresses:");
            foreach (Address address in matchingAddresses)
            {
                Debug.WriteLine(address.Address1);
            }

            StringBuilder json = new StringBuilder();

            json.Append("[");

            if (matchingAddresses.Count == 0)
            {
                // return empty json
                WriteEmptyJson();
            }

            else
            {
                foreach (Address address in matchingAddresses)
                {
                    json.Append("{");
                    json.Append("\"id\": \"");
                    json.Append(address.AddressId.ToString());
                    json.Append("\",");
                    json.Append("\"label\": \"");
                    json.Append(address.Address1);
                    json.Append("\",");
                    json.Append("\"address1\": \"");
                    json.Append(address.Address1);
                    json.Append("\",");
                    json.Append("\"address2\": \"");
                    if (address.Address2 != null)
                    {
                        json.Append(address.Address2);
                    }
                    json.Append("\",");
                    json.Append("\"city\": \"");
                    json.Append(address.City);
                    json.Append("\",");
                    json.Append("\"state\": \"");
                    json.Append(address.State);
                    json.Append("\",");
                    json.Append("\"postalCode\": \"");
                    json.Append(address.PostalCode);
                    json.Append("\",");
                    json.Append("\"country\": \"");
                    if (address.Country != null)
                    {
                        json.Append(address.Country);
                    }
                    json.Append("\"");
                    json.Append("},");
                }

                // remove last comma
                json.Remove(json.Length - 1, 1);
            }

            json.Append("]");

            Debug.WriteLine(json.ToString());

            this.Response.Clear();
            this.Response.Write(json.ToString());
            //this.Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
 public static StringBuilder TrimEnd(this StringBuilder builder, char c)
 {
     return builder.Length > 0
         ? builder.Remove(builder.Length - 1, 1)
         : builder;
 }
        private static TreeNode GetChildTreeNode(object data, string name, ref object childObj)
        {
            string   typeName = data.GetType().FullName;
            TreeNode node     = null;

            if (data is IEnumerable)
            {
                int         result     = 0;
                IEnumerator enumerator = (data as IEnumerable).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    result++;
                }

                node = new TreeNode(name + separator + name + ".Count:" + result);
            }
            else
            {
                node = new TreeNode(name);
            }

            if (typeName.StartsWith("System.Collections.Generic.List`1[[System.String,"))
            {
                foreach (var m in data as List <string> )
                {
                    TreeNode item = new TreeNode(m);
                    node.Nodes.Add(item);
                }

                childObj = null;
            }
            else if (typeName.StartsWith("System.Collections.Generic.List`1[[System.Int32,"))
            {
                foreach (var m in data as List <int> )
                {
                    TreeNode item = new TreeNode(m.ToString());
                    node.Nodes.Add(item);
                }

                childObj = null;
            }
            else if (typeName.StartsWith("System.Collections.Generic.List`1[[") && typeList.Exists(p => typeName.StartsWith("System.Collections.Generic.List`1[[" + p)))
            {
                foreach (var m in (data as IEnumerable))
                {
                    Dictionary <string, object> dic = new Dictionary <string, object>();
                    PropertyInfo[] ps = m.GetType().GetProperties();
                    foreach (var p in ps)
                    {
                        object obj = p.GetValue(m, null);
                        dic.Add(p.Name, obj);
                    }

                    StringBuilder content = new StringBuilder();
                    foreach (var c in dic)
                    {
                        content.AppendFormat("{0}:{1}{2}", c.Key, c.Value, separator);
                    }

                    if (content.Length > 0)
                    {
                        content.Remove(content.Length - separator.Length, separator.Length);
                    }

                    TreeNode itemNode = new TreeNode(content.ToString());
                    node.Nodes.Add(itemNode);
                }
            }
            else if (typeList.Exists(p => typeName.StartsWith(p)))
            {
                var typeFullName = typeList.Find(p => typeName.StartsWith(p));
            }

            return(node);
        }
Beispiel #49
0
        /// <summary>
        /// 插入
        /// 使用说明:sqlSugar.Insert(entity);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">插入对象</param>
        /// <param name="isIdentity">主键是否为自增长,true可以不填,false必填</param>
        /// <returns></returns>
        public object Insert<T>(T entity, bool isIdentity = true) where T : class
        {

            Type type = entity.GetType();
            string typeName = type.Name;
            typeName = GetTableNameByClassType(typeName);

            StringBuilder sbInsertSql = new StringBuilder();
            List<SqlParameter> pars = new List<SqlParameter>();
            var primaryKeyName = SqlSugarTool.GetPrimaryKeyByTableName(this, typeName);
            //sql语句缓存
            string cacheSqlKey = "db.Insert." + typeName;
            var cacheSqlManager = CacheManager<StringBuilder>.GetInstance();

            //属性缓存
            string cachePropertiesKey = "db." + typeName + ".GetProperties";
            var cachePropertiesManager = CacheManager<PropertyInfo[]>.GetInstance();

            PropertyInfo[] props = null;
            if (cachePropertiesManager.ContainsKey(cachePropertiesKey))
            {
                props = cachePropertiesManager[cachePropertiesKey];
            }
            else
            {
                props = type.GetProperties();
                cachePropertiesManager.Add(cachePropertiesKey, props, cachePropertiesManager.Day);
            }
            var isContainCacheSqlKey = cacheSqlManager.ContainsKey(cacheSqlKey);
            if (isContainCacheSqlKey)
            {
                sbInsertSql = cacheSqlManager[cacheSqlKey];
            }
            else
            {



                //2.获得实体的属性集合 


                //实例化一个StringBuilder做字符串的拼接 


                sbInsertSql.Append("insert into " + typeName + " (");

                //3.遍历实体的属性集合 
                foreach (PropertyInfo prop in props)
                {
                    //EntityState,@EntityKey
                    if (isIdentity == false || (isIdentity && prop.Name != primaryKeyName))
                    {
                        //4.将属性的名字加入到字符串中 
                        sbInsertSql.Append("["+prop.Name + "],");
                    }
                }
                //**去掉最后一个逗号 
                sbInsertSql.Remove(sbInsertSql.Length - 1, 1);
                sbInsertSql.Append(" ) values(");

            }

            //5.再次遍历,形成参数列表"(@xx,@xx@xx)"的形式 
            foreach (PropertyInfo prop in props)
            {
                //EntityState,@EntityKey
                if (isIdentity == false || (isIdentity && prop.Name != primaryKeyName))
                {
                    if (!cacheSqlManager.ContainsKey(cacheSqlKey))
                        sbInsertSql.Append("@" + prop.Name + ",");
                    object val = prop.GetValue(entity, null);
                    if (val == null)
                        val = DBNull.Value;
                    var par = new SqlParameter("@" + prop.Name, val);
                    if (par.SqlDbType == SqlDbType.Udt)
                    {
                        par.UdtTypeName = "HIERARCHYID";
                    }
                    pars.Add(par);
                }
            }
            if (!isContainCacheSqlKey)
            {
                //**去掉最后一个逗号 
                sbInsertSql.Remove(sbInsertSql.Length - 1, 1);
                if (isIdentity == false)
                {
                    sbInsertSql.Append(");select 'true';");
                }
                else
                {
                    sbInsertSql.Append(");select @@identity;");
                }
                cacheSqlManager.Add(cacheSqlKey, sbInsertSql, cacheSqlManager.Day);
            }
            var sql = sbInsertSql.ToString();
            try
            {
                var lastInsertRowId = GetScalar(sql, pars.ToArray());
                return lastInsertRowId;
            }
            catch (Exception ex)
            {
                throw new Exception("sql:" + sql + "\n" + ex.Message);
            }

        }
Beispiel #50
0
        /// <summary>
        /// Компилировать исходный код формул калькулятора
        /// </summary>
        public bool CompileSource()
        {
            try
            {
                // загрузка исходного кода класса CalcEngine
                string source;

                using (Stream stream = Assembly.GetExecutingAssembly().
                                       GetManifestResourceStream("Scada.Server.Engine.CalcEngine.cs"))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        source = reader.ReadToEnd();
                    }
                }

                // добавление членов класса CalcEngine
                int todoInd = source.IndexOf("/*TODO*/");

                if (todoInd >= 0)
                {
                    StringBuilder sourceSB = new StringBuilder(source);
                    sourceSB.Remove(todoInd, "/*TODO*/".Length);

                    for (int i = exprList.Count - 1; i >= 0; i--)
                    {
                        string expr = exprList[i];
                        sourceSB.Insert(todoInd, expr);
                        if (i > 0)
                        {
                            sourceSB.Insert(todoInd, "\r\n");
                        }
                    }

                    source = sourceSB.ToString();
                }

                // сохранение исходного кода класса CalcEngine в файле для анализа
                string sourceFileName = mainLogic.AppDirs.LogDir + "CalcEngine.cs";
                File.WriteAllText(sourceFileName, source, Encoding.UTF8);

                // компилирование исходного кода класса CalcEngine
                CompilerParameters compParams = new CompilerParameters();
                compParams.GenerateExecutable      = false;
                compParams.GenerateInMemory        = true;
                compParams.IncludeDebugInformation = false;
                compParams.ReferencedAssemblies.Add("System.dll");
                compParams.ReferencedAssemblies.Add("System.Core.dll");
                compParams.ReferencedAssemblies.Add(mainLogic.AppDirs.ExeDir + "ScadaData.dll");
                CodeDomProvider compiler        = CSharpCodeProvider.CreateProvider("CSharp");
                CompilerResults compilerResults = compiler.CompileAssemblyFromSource(compParams, source);

                if (compilerResults.Errors.HasErrors)
                {
                    appLog.WriteAction(Localization.UseRussian ?
                                       "Ошибка при компилировании исходного кода формул: " :
                                       "Error compiling the source code of the formulas: ", Log.ActTypes.Error);

                    foreach (CompilerError error in compilerResults.Errors)
                    {
                        appLog.WriteLine(string.Format(Localization.UseRussian ?
                                                       "Строка {0}, колонка {1}: error {2}: {3}" :
                                                       "Line {0}, column {1}: error {2}: {3}",
                                                       error.Line, error.Column, error.ErrorNumber, error.ErrorText));
                    }

                    appLog.WriteLine(string.Format(Localization.UseRussian ?
                                                   "Для ознакомления с исходным кодом см. файл {0}" :
                                                   "See the file {0} with the source code",
                                                   sourceFileName));
                    return(false);
                }
                else
                {
                    Type calcEngineType = compilerResults.CompiledAssembly.GetType(
                        "Scada.Server.Engine.CalcEngine", true);
                    calcEngine = Activator.CreateInstance(calcEngineType,
                                                          new Func <int, SrezTableLight.CnlData>(mainLogic.GetProcSrezCnlData),
                                                          new Action <int, SrezTableLight.CnlData>(mainLogic.SetProcSrezCnlData));

                    appLog.WriteAction(Localization.UseRussian ?
                                       "Исходный код формул калькулятора откомпилирован" :
                                       "The formulas source code has been compiled", Log.ActTypes.Action);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                appLog.WriteAction((Localization.UseRussian ?
                                    "Ошибка при компилировании исходного кода формул: " :
                                    "Error compiling the source code of the formulas: ") + ex.Message, Log.ActTypes.Exception);
                return(false);
            }
        }
Beispiel #51
0
        /// <summary>
        /// 获得套装促销活动列表
        /// </summary>
        /// <param name="pid">商品id</param>
        /// <param name="nowTime">当前时间</param>
        /// <returns></returns>
        public static List <KeyValuePair <SuitPromotionInfo, List <ExtSuitProductInfo> > > GetProductAllSuitPromotion(int pid, DateTime nowTime)
        {
            List <KeyValuePair <SuitPromotionInfo, List <ExtSuitProductInfo> > > result = new List <KeyValuePair <SuitPromotionInfo, List <ExtSuitProductInfo> > >();

            List <SuitPromotionInfo> suitPromotionList = GetSuitPromotionList(pid, nowTime);

            if (suitPromotionList.Count > 0)
            {
                StringBuilder pmIdList = new StringBuilder();
                foreach (SuitPromotionInfo suitPromotionInfo in suitPromotionList)
                {
                    pmIdList.AppendFormat("{0},", suitPromotionInfo.PmId);
                }
                List <ExtSuitProductInfo> allExtSuitProduct = GetAllExtSuitProductList(pmIdList.Remove(pmIdList.Length - 1, 1).ToString());

                foreach (SuitPromotionInfo suitPromotionInfo in suitPromotionList)
                {
                    result.Add(new KeyValuePair <SuitPromotionInfo, List <ExtSuitProductInfo> >(suitPromotionInfo, allExtSuitProduct.FindAll(x => x.PmId == suitPromotionInfo.PmId)));
                }
            }

            return(result);
        }
Beispiel #52
0
        public static String Encode(String text)
        {
            const Int32 InitialBias      = 72;
            const Int32 InitialNumber    = 0x80;
            const Int32 MaxIntValue      = 0x7ffffff;
            const Int32 LabelLimit       = 63;
            const Int32 DefaultNameLimit = 255;

            // 0 length strings aren't allowed
            if (text.Length == 0)
            {
                return(text);
            }

            var output              = new StringBuilder(text.Length);
            var iNextDot            = 0;
            var iAfterLastDot       = 0;
            var iOutputAfterLastDot = 0;

            // Find the next dot
            while (iNextDot < text.Length)
            {
                // Find end of this segment
                iNextDot = text.IndexOfAny(possibleDots, iAfterLastDot);

                if (iNextDot < 0)
                {
                    iNextDot = text.Length;
                }

                // Only allowed to have empty . section at end (www.microsoft.com.)
                if (iNextDot == iAfterLastDot)
                {
                    break;
                }

                // We'll need an Ace prefix
                output.Append(acePrefix);

                var basicCount   = 0;
                var numProcessed = 0;

                for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
                {
                    if (text[basicCount] < 0x80)
                    {
                        output.Append(EncodeBasic(text[basicCount]));
                        numProcessed++;
                    }
                    else if (Char.IsSurrogatePair(text, basicCount))
                    {
                        basicCount++;
                    }
                }

                var numBasicCodePoints = numProcessed;

                if (numBasicCodePoints == iNextDot - iAfterLastDot)
                {
                    output.Remove(iOutputAfterLastDot, acePrefix.Length);
                }
                else
                {
                    // If it has some non-basic code points the input cannot start with xn--
                    if (text.Length - iAfterLastDot >= acePrefix.Length && text.Substring(iAfterLastDot, acePrefix.Length).Equals(acePrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }

                    // Need to do ACE encoding
                    var numSurrogatePairs = 0;

                    // Add a delimiter (-) if we had any basic code points (between basic and encoded pieces)
                    if (numBasicCodePoints > 0)
                    {
                        output.Append(Text.Symbols.Minus);
                    }

                    // Initialize the state
                    var n     = InitialNumber;
                    var delta = 0;
                    var bias  = InitialBias;

                    // Main loop
                    while (numProcessed < (iNextDot - iAfterLastDot))
                    {
                        var j    = 0;
                        var m    = 0;
                        var test = 0;

                        for (m = MaxIntValue, j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1)
                        {
                            test = Char.ConvertToUtf32(text, j);

                            if (test >= n && test < m)
                            {
                                m = test;
                            }
                        }

                        // Increase delta enough to advance the decoder's
                        // <n,i> state to <m,0>, but guard against overflow:
                        delta += (m - n) * ((numProcessed - numSurrogatePairs) + 1);
                        n      = m;

                        for (j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1)
                        {
                            // Make sure we're aware of surrogates
                            test = Char.ConvertToUtf32(text, j);

                            // Adjust for character position (only the chars in our string already, some
                            // haven't been processed.

                            if (test < n)
                            {
                                delta++;
                            }
                            else if (test == n)
                            {
                                // Represent delta as a generalized variable-length integer:
                                int q, k;

                                for (q = delta, k = PunycodeBase; ; k += PunycodeBase)
                                {
                                    var t = k <= bias ? Tmin : k >= bias + Tmax ? Tmax : k - bias;

                                    if (q < t)
                                    {
                                        break;
                                    }

                                    output.Append(EncodeDigit(t + (q - t) % (PunycodeBase - t)));
                                    q = (q - t) / (PunycodeBase - t);
                                }

                                output.Append(EncodeDigit(q));
                                bias  = AdaptChar(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
                                delta = 0;
                                numProcessed++;

                                if (IsSupplementary(m))
                                {
                                    numProcessed++;
                                    numSurrogatePairs++;
                                }
                            }
                        }

                        ++delta;
                        ++n;
                    }
                }

                // Make sure its not too big
                if (output.Length - iOutputAfterLastDot > LabelLimit)
                {
                    throw new ArgumentException();
                }

                // Done with this segment, add dot if necessary
                if (iNextDot != text.Length)
                {
                    output.Append(possibleDots[0]);
                }

                iAfterLastDot       = iNextDot + 1;
                iOutputAfterLastDot = output.Length;
            }

            var rest      = IsDot(text[text.Length - 1]) ? 0 : 1;
            var maxlength = DefaultNameLimit - rest;

            // Throw if we're too long
            if (output.Length > maxlength)
            {
                output.Remove(maxlength, output.Length - maxlength);
            }

            return(output.ToString());
        }
Beispiel #53
0
        /// <summary>
        /// Reads a content of current xaml element, converts it
        /// </summary>
        /// <param name="xamlReader">
        /// XmlTextReader which is expected to be at XmlNodeType.Element
        /// (opening element tag) position.
        /// </param>
        /// <param name="htmlWriter">
        /// May be null, in which case we are skipping the xaml element;
        /// witout producing any output to html.
        /// </param>
        /// <param name="inlineStyle">
        /// StringBuilder used for collecting css properties for inline STYLE attribute.
        /// </param>
        private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            bool elementContentStarted = false;

            if (xamlReader.IsEmptyElement)
            {
                if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
                {
                    // Output STYLE attribute and clear inlineStyle buffer.
                    htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                    inlineStyle.Remove(0, inlineStyle.Length);
                }
                elementContentStarted = true;
            }
            else
            {
                while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
                {
                    switch (xamlReader.NodeType)
                    {
                    case XmlNodeType.Element:
                        if (xamlReader.Name.Contains("."))
                        {
                            AddComplexProperty(xamlReader, inlineStyle);
                        }
                        else
                        {
                            if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
                            {
                                // Output STYLE attribute and clear inlineStyle buffer.
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                                inlineStyle.Remove(0, inlineStyle.Length);
                            }
                            elementContentStarted = true;
                            WriteElement(xamlReader, htmlWriter, inlineStyle);
                        }
                        Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
                        break;

                    case XmlNodeType.Comment:
                        if (htmlWriter != null)
                        {
                            if (!elementContentStarted && inlineStyle.Length > 0)
                            {
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                            }
                            htmlWriter.WriteComment(xamlReader.Value);
                        }
                        elementContentStarted = true;
                        break;

                    case XmlNodeType.CDATA:
                    case XmlNodeType.Text:
                    case XmlNodeType.SignificantWhitespace:
                        if (htmlWriter != null)
                        {
                            if (!elementContentStarted && inlineStyle.Length > 0)
                            {
                                htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
                            }
                            htmlWriter.WriteString(xamlReader.Value.Replace(" ", "&nbsp;"));
                        }
                        elementContentStarted = true;
                        break;
                    }
                }

                Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement);
            }
        }
        public virtual void Test()
        {
            Directory         dir = NewDirectory();
            RandomIndexWriter w   = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);

            long startTime = Environment.TickCount;

            // TODO: replace w/ the @nightly test data; make this
            // into an optional @nightly stress test
            Document doc  = new Document();
            Field    body = NewTextField("body", "", Field.Store.NO);

            doc.Add(body);
            StringBuilder sb = new StringBuilder();

            for (int docCount = 0; docCount < NUM_DOCS; docCount++)
            {
                int numTerms = Random().Next(10);
                for (int termCount = 0; termCount < numTerms; termCount++)
                {
                    sb.Append(Random().NextBoolean() ? "aaa" : "bbb");
                    sb.Append(' ');
                }
                body.StringValue = sb.ToString();
                w.AddDocument(doc);
                sb.Remove(0, sb.Length);
            }
            IndexReader r = w.Reader;

            w.Dispose();

            long endTime = Environment.TickCount;

            if (VERBOSE)
            {
                Console.WriteLine("BUILD took " + (endTime - startTime));
            }

            IndexSearcher s = NewSearcher(r);

            AtomicBoolean failed    = new AtomicBoolean();
            AtomicLong    netSearch = new AtomicLong();

            ThreadClass[] threads = new ThreadClass[NUM_SEARCH_THREADS];
            for (int threadID = 0; threadID < NUM_SEARCH_THREADS; threadID++)
            {
                threads[threadID] = new ThreadAnonymousInnerClassHelper(this, s, failed, netSearch);
                threads[threadID].SetDaemon(true);
            }

            foreach (ThreadClass t in threads)
            {
                t.Start();
            }

            foreach (ThreadClass t in threads)
            {
                t.Join();
            }

            if (VERBOSE)
            {
                Console.WriteLine(NUM_SEARCH_THREADS + " threads did " + netSearch.Get() + " searches");
            }

            r.Dispose();
            dir.Dispose();
        }
Beispiel #55
0
        public IEnumerable <DTOShipmentsViewModel> GetShipments(DTOGroupingShipsmentsViewModel dtoGroupingShipsmentsViewModel = null)
        {
            string query;

            if (dtoGroupingShipsmentsViewModel == null)
            {
                query = "SELECT S.Id, S.ShipmentDate,S.Company,S.City,S.Country, A.Surname+' '+A.Name as SurnameName, A.UserName as Login, S.Quantity,S.Sum FROM Shipments S INNER JOIN AspNetUsers A ON S.Manager_Id = A.Id";
            }
            else
            {
                StringBuilder queryBegin = new StringBuilder("SELECT ");
                StringBuilder queryEnd   = new StringBuilder(" FROM Shipments S INNER JOIN AspNetUsers A ON S.Manager_Id=A.Id GROUP BY ");
                if (dtoGroupingShipsmentsViewModel.Date)
                {
                    queryBegin.Append("CAST(S.ShipmentDate AS date) as ShipmentDate, ");
                    queryEnd.Append("CAST(S.ShipmentDate AS date),");
                }
                if (dtoGroupingShipsmentsViewModel.Company)
                {
                    queryBegin.Append("S.Company, ");
                    queryEnd.Append("S.Company,");
                }
                if (dtoGroupingShipsmentsViewModel.City)
                {
                    queryBegin.Append("S.City, ");
                    queryEnd.Append("S.City,");
                }
                if (dtoGroupingShipsmentsViewModel.Country)
                {
                    queryBegin.Append("S.Country, ");
                    queryEnd.Append("S.Country,");
                }
                if (dtoGroupingShipsmentsViewModel.SurnameName)
                {
                    queryBegin.Append("A.Surname+' '+A.Name as SurnameName, ");
                    queryEnd.Append("A.Surname+' '+A.Name,");
                }
                query = queryBegin.Append("Sum(S.Quantity) as Quantity,Sum(S.Sum) as Sum").ToString() + queryEnd.Remove(queryEnd.Length - 1, 1).ToString();
            }
            var shipments = Database.Shipments.GetShipments(query);

            List <DTOShipmentsViewModel> dtoShipmentsViewModel = new List <DTOShipmentsViewModel>();

            foreach (var item in shipments)
            {
                dtoShipmentsViewModel.Add(new DTOShipmentsViewModel()
                {
                    Id           = item.Id,
                    ShipmentDate = item.ShipmentDate,
                    Company      = item.Company,
                    City         = item.City,
                    Country      = item.Country,
                    SurnameName  = item.SurnameName,
                    Login        = item.Login,
                    Quantity     = item.Quantity,
                    Sum          = item.Sum
                });
            }
            return(dtoShipmentsViewModel);
        }
Beispiel #56
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            ljxpower.BLL.com_organization   bll   = new ljxpower.BLL.com_organization();
            ljxpower.Model.com_organization model = null;
            if (context.Request.QueryString["type"] == "edit")//获取部门信息
            {
                int Id = int.Parse(context.Request.QueryString["Id"]);

                model = bll.GetModel(Id);
                if (model != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(model.Agency + ",");
                    //ljxpower.Model.com_organization pmodel = bll.GetModel(model.ParentId);
                    //if (pmodel != null)
                    //{
                    //    sb.Append(pmodel.Agency);
                    //}
                    sb.Append(model.ParentId + ",");
                    sb.Append(model.Sort + ",");
                    sb.Append(model.Person + ",");
                    sb.Append(model.Remark + ",");
                    sb.Append(model.orgid);
                    context.Response.Write(sb.ToString());
                }
            }
            else if (context.Request.QueryString["type"] == "del")//删除部门信息
            {
                string Id = context.Request.QueryString["Id"];
                //ljxpower.BLL.com_organization bll = new ljxpower.BLL.com_organization();
                string[] str = Id.Split(',');
                int      oId = int.Parse(str[str.Length - 1]);
                model = bll.GetModel(oId);
                List <string> listSql = new List <string>();
                if (model != null)
                {
                    string sql = "update com_organization set Sort=Sort-1 where ParentId=" + model.ParentId + " and Sort>" + model.Sort;
                    listSql.Add(sql);
                }
                listSql.Add(" delete  from  com_organization where Id in(" + Id + ")");
                listSql.Add(" update Com_OrgAddUser set OrgId=(select   Id from com_organization where ParentId=0 limit 1,1) where OrgId=" + Id);
                if (ljxpower.Common.DbHelperMySQL.ExecuteSqlTran(listSql) > 0)
                {
                    context.Response.Write("true");
                }
            }
            else if (context.Request.QueryString["type"] == "save")//保存修改或添加部门信息
            {
                //ljxpower.BLL.com_organization bll = new ljxpower.BLL.com_organization();

                string name   = context.Request.QueryString["name"];
                string remark = context.Request.QueryString["remark"];
                string person = context.Request.QueryString["person"];
                int    sort   = int.Parse(context.Request.QueryString["sort"]);
                int    parent = 0;
                if (context.Request.QueryString["parentId"] != null && context.Request.QueryString["parentId"] != "")
                {
                    parent = int.Parse(context.Request.QueryString["parentId"]);
                }
                string orgid = getnewbianhao(Convert.ToString(context.Request.QueryString["parentId"]));

                List <ljxpower.Model.com_organization> list = bll.GetModelList(" ParentId=" + parent);
                List <string> listSql = new List <string>();
                if (context.Request.QueryString["Id"] != null && context.Request.QueryString["Id"] != "")
                {
                    int Id = int.Parse(context.Request.QueryString["Id"]);
                    model = bll.GetModel(Id);
                    if (model.ParentId == parent)
                    {
                        if (sort > list.Count)
                        {
                            sort = list.Count;
                        }
                        if (model.Sort > sort)
                        {
                            string sql = "update com_organization set Sort=Sort+1 where ParentId=" + parent + " and Sort>=" + sort + " and Sort<" + model.Sort;
                            listSql.Add(sql);
                        }
                        else if (model.Sort < sort)
                        {
                            string sql = "update com_organization set Sort=Sort-1 where ParentId=" + parent + " and Sort<=" + sort + " and Sort>" + model.Sort;
                            listSql.Add(sql);
                        }
                    }
                    else
                    {
                        if (sort > list.Count + 1)
                        {
                            sort = list.Count + 1;
                        }
                        else
                        {
                            string sql = "update com_organization set Sort=Sort+1 where ParentId=" + parent + " and Sort>=" + sort;
                            listSql.Add(sql);
                            string sql2 = "update com_organization set Sort=Sort-1 where ParentId=" + model.ParentId + " and Sort>" + model.Sort;
                            listSql.Add(sql2);
                        }
                    }
                    if (listSql.Count > 0)
                    {
                        ljxpower.Common.DbHelperMySQL.ExecuteSqlTran(listSql);
                    }
                    model.Agency = name;
                    model.Person = person;
                    model.Remark = remark;
                    model.Sort   = sort;
                    if (model.ParentId != parent)
                    {
                        model.ParentId = parent;
                        model.orgid    = orgid;
                    }
                    bll.Update1(model);
                }
                else
                {
                    model        = new ljxpower.Model.com_organization();
                    model.Agency = name;
                    model.Person = person;
                    model.Remark = remark;
                    model.orgid  = orgid;
                    if (sort > list.Count + 1)
                    {
                        sort = list.Count + 1;
                    }
                    else
                    {
                        string sql = "update com_organization set Sort=Sort+1 where ParentId=" + parent + " and Sort>=" + sort;
                        listSql.Add(sql);
                        string sql2 = "update com_organization set Sort=Sort-1 where ParentId=" + model.ParentId + " and Sort>" + model.Sort;
                        listSql.Add(sql2);
                        ljxpower.Common.DbHelperMySQL.ExecuteSqlTran(listSql);
                    }
                    model.Sort     = sort;
                    model.ParentId = parent;
                    bll.Add1(model);
                }

                context.Response.Write("true");
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                //ljxpower.BLL.Com_UserInfos ubll = new ljxpower.BLL.Com_UserInfos();
                //ljxpower.Model.Com_UserInfos user = null;
                DataSet ds = new DataSet();
                if (context.Request["Id"] != null)
                {
                    ds = bll.GetList(" Id!=" + context.Request.QueryString["Id"]);
                }
                else
                {
                    ds = bll.GetAllList();
                }
                if (ds.Tables.Count > 0)
                {
                    sb.Append("[");
                    DataView dv = new DataView(ds.Tables[0]);
                    dv.RowFilter = "ParentId=0";
                    dv.Sort      = " Sort ";
                    for (int i = 0; i < dv.Count; i++)
                    {
                        sb.Append("{");
                        sb.Append("\"id\":" + dv[i]["Id"] + ",");
                        sb.Append("\"text\":\"" + dv[i]["Agency"] + "\",");
                        sb.Append("\"Sort\":\"" + dv[i]["Sort"] + "\"");
                        //sb.Append("\"Person\":\"" + dv[i]["Person"] + "\",");
                        //sb.Append("\"Remark\":\"" + dv[i]["Remark"] + "\"");
                        DataView dv2 = new DataView(ds.Tables[0]);
                        dv2.RowFilter = "ParentId=" + dv[i]["Id"];
                        dv2.Sort      = " Sort ";
                        if (dv2.Count > 0)
                        {
                            sb.Append(GetChlid(dv2, ds));
                        }
                        sb.Append("},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    sb.Append("]");
                }
                context.Response.Write(sb.ToString());
            }
        }
        public ActionResult GetGrid(JqGridRequest request, string key, string value, string viewModel, string field, long?id_master)
        {
            string fieldMain = String.Empty;
            long   ID_master;
            bool   result = Int64.TryParse(id_master.ToString(), out ID_master);


            if (String.IsNullOrEmpty(field))
            {
                fieldMain = "ID_Obrazac";
            }

            else
            {
                fieldMain = field;
            }

            viewModel = gridModelNamespace + viewModel;

            string filterExpression = String.Empty;

            if (request.Searching)
            {
                if (request.SearchingFilter != null)
                {
                    filterExpression = GetFilter(request.SearchingFilter.SearchingName, request.SearchingFilter.SearchingOperator, request.SearchingFilter.SearchingValue);
                }
                else if (request.SearchingFilters != null)
                {
                    StringBuilder filterExpressionBuilder  = new StringBuilder();
                    string        groupingOperatorToString = request.SearchingFilters.GroupingOperator.ToString();
                    foreach (JqGridRequestSearchingFilter searchingFilter in request.SearchingFilters.Filters)
                    {
                        filterExpressionBuilder.Append(GetFilter(searchingFilter.SearchingName, searchingFilter.SearchingOperator, searchingFilter.SearchingValue));
                        filterExpressionBuilder.Append(String.Format(KeyWord.FormaterRazno.StringFormat.Prvi, groupingOperatorToString));
                    }
                    if (filterExpressionBuilder.Length > 0)
                    {
                        filterExpressionBuilder.Remove(filterExpressionBuilder.Length - groupingOperatorToString.Length - 2, groupingOperatorToString.Length + 2);
                    }
                    filterExpression = filterExpressionBuilder.ToString();
                }
            }
            string sortingName       = request.SortingName;
            long   totalRecordsCount = GetCount(filterExpression, key, value);


            JqGridResponse response = new JqGridResponse()
            {
                TotalPagesCount   = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount),
                PageIndex         = request.PageIndex,
                TotalRecordsCount = totalRecordsCount,
            };


            response.Records.AddRange
            (
                from item in GetGridData(filterExpression, key, value, String.Format(KeyWord.FormaterRazno.StringFormat.PrviDrugi, sortingName, request.SortingOrder), request.PageIndex * request.RecordsCount, (request.PagesCount.HasValue ? request.PagesCount.Value : 1) * request.RecordsCount)
                select new JqGridRecord(Convert.ToString(item.GetType().GetProperty(fieldMain).GetValue(item, null)), Activator.CreateInstance(Type.GetType(viewModel), new[] { item }))
            );


            return(new JqGridJsonResult()
            {
                Data = response
            });
        }
Beispiel #58
0
        /// <summary>
        /// Reads attributes of the current xaml element and converts
        /// them into appropriate html attributes or css styles.
        /// </summary>
        /// <param name="xamlReader">
        /// XmlTextReader which is expected to be at XmlNodeType.Element
        /// (opening element tag) position.
        /// The reader will remain at the same level after function complete.
        /// </param>
        /// <param name="htmlWriter">
        /// XmlTextWriter for output html, which is expected to be in
        /// after WriteStartElement state.
        /// </param>
        /// <param name="inlineStyle">
        /// String builder for collecting css properties for inline STYLE attribute.
        /// </param>



        private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
        {
            bool IsParagraph = false;

            if (xamlReader.Name == "Paragraph")
            {
                IsParagraph = true;
            }
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            // Clear string builder for the inline style
            inlineStyle.Remove(0, inlineStyle.Length);

            if (!xamlReader.HasAttributes)
            {
                if (IsParagraph)
                {
                    string temp = "font-size:" + 11 + ";";
                    inlineStyle.Append(temp);
                }
                return;
            }

            bool borderSet = false;

            while (xamlReader.MoveToNextAttribute())
            {
                string css = null;

                switch (xamlReader.Name)
                {
                // Character fomatting properties
                // ------------------------------
                case "Background":

                    css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";" + "opacity:" + (double)Convert.ToInt32(xamlReader.Value.Substring(1, 2), 16) / (double)byte.MaxValue + ";";
                    break;

                case "FontFamily":
                    css = "font-family:" + xamlReader.Value + ";";
                    break;

                case "FontStyle":
                    css = "font-style:" + xamlReader.Value.ToLower() + ";";
                    break;

                case "FontWeight":
                    css = "font-weight:" + xamlReader.Value.ToLower() + ";";
                    break;

                case "FontStretch":
                    break;

                case "FontSize":
                    css = "font-size:" + xamlReader.Value + ";";
                    break;

                case "Foreground":
                    css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
                    break;

                case "TextDecorations":
                    css = "text-decoration:underline;";
                    break;

                case "TextEffects":
                    break;

                case "Emphasis":
                    break;

                case "StandardLigatures":
                    break;

                case "Variants":
                    break;

                case "Capitals":
                    break;

                case "Fraction":
                    break;

                // Paragraph formatting properties
                // -------------------------------
                case "PagePadding":
                    css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
                    break;

                case "Margin":
                    css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
                    break;

                case "BorderThickness":
                    css       = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
                    borderSet = true;
                    break;

                case "BorderBrush":
                    css       = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
                    borderSet = true;
                    break;

                case "LineHeight":

                    break;

                case "TextIndent":
                    css = "text-indent:" + xamlReader.Value + ";";
                    break;

                case "TextAlignment":
                    css = "text-align:" + xamlReader.Value + ";";
                    break;

                case "IsKeptTogether":
                    break;

                case "IsKeptWithNext":
                    break;

                case "ColumnBreakBefore":
                    break;

                case "PageBreakBefore":
                    break;

                case "FlowDirection":
                    break;

                // Table attributes
                // ----------------
                case "Width":
                    css = "width:" + xamlReader.Value + ";";
                    break;

                case "ColumnSpan":
                    htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
                    break;

                case "RowSpan":
                    htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
                    break;
                }

                if (css != null)
                {
                    inlineStyle.Append(css);
                }
            }

            if (borderSet)
            {
                inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
            }

            // Return the xamlReader back to element level
            xamlReader.MoveToElement();
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
        }
        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>
        /// 执行分页查询
        /// </summary>
        /// <param name="pWhereConditions">筛选条件</param>
        /// <param name="pOrderBys">排序</param>
        /// <param name="pPageSize">每页的记录数</param>
        /// <param name="pCurrentPageIndex">以0开始的当前页码</param>
        /// <returns></returns>
        public PagedQueryResult <VipCardVipMappingEntity> PagedQuery(IWhereCondition[] pWhereConditions, OrderBy[] pOrderBys, int pPageSize, int pCurrentPageIndex)
        {
            //组织SQL
            StringBuilder pagedSql      = new StringBuilder();
            StringBuilder totalCountSql = new StringBuilder();

            //分页SQL
            pagedSql.AppendFormat("select * from (select row_number()over( order by ");
            if (pOrderBys != null && pOrderBys.Length > 0)
            {
                foreach (var item in pOrderBys)
                {
                    if (item != null)
                    {
                        pagedSql.AppendFormat(" {0} {1},", StringUtils.WrapperSQLServerObject(item.FieldName), item.Direction == OrderByDirections.Asc ? "asc" : "desc");
                    }
                }
                pagedSql.Remove(pagedSql.Length - 1, 1);
            }
            else
            {
                pagedSql.AppendFormat(" [MappingID] desc"); //默认为主键值倒序
            }
            pagedSql.AppendFormat(") as ___rn,* from [VipCardVipMapping] where 1=1  and isdelete=0 ");
            //总记录数SQL
            totalCountSql.AppendFormat("select count(1) from [VipCardVipMapping] where 1=1  and isdelete=0 ");
            //过滤条件
            if (pWhereConditions != null)
            {
                foreach (var item in pWhereConditions)
                {
                    if (item != null)
                    {
                        pagedSql.AppendFormat(" and {0}", item.GetExpression());
                        totalCountSql.AppendFormat(" and {0}", item.GetExpression());
                    }
                }
            }
            pagedSql.AppendFormat(") as A ");
            //取指定页的数据
            pagedSql.AppendFormat(" where ___rn >{0} and ___rn <={1}", pPageSize * (pCurrentPageIndex - 1), pPageSize * (pCurrentPageIndex));
            //执行语句并返回结果
            PagedQueryResult <VipCardVipMappingEntity> result = new PagedQueryResult <VipCardVipMappingEntity>();
            List <VipCardVipMappingEntity>             list   = new List <VipCardVipMappingEntity>();

            using (SqlDataReader rdr = this.SQLHelper.ExecuteReader(pagedSql.ToString()))
            {
                while (rdr.Read())
                {
                    VipCardVipMappingEntity m;
                    this.Load(rdr, out m);
                    list.Add(m);
                }
            }
            result.Entities = list.ToArray();
            int totalCount = Convert.ToInt32(this.SQLHelper.ExecuteScalar(totalCountSql.ToString()));    //计算总行数

            result.RowCount = totalCount;
            int remainder = 0;

            result.PageCount = Math.DivRem(totalCount, pPageSize, out remainder);
            if (remainder > 0)
            {
                result.PageCount++;
            }
            return(result);
        }