Example #1
0
 public TypeLexer(String s)
 {
     // Turn the string into a char array with a NUL terminator.
     char[] chars = new char[s.Length + 1];
     s.CopyTo(0, chars, 0, s.Length);
     _chars = chars;
     _index = 0;
 }
Example #2
0
/* ------------------------------------------------------------ */
//  PROCEDURE RealToStr*(r : REAL; OUT s : ARRAY OF CHAR);
//  (** Decode a CP REAL into an array *)
//  BEGIN END RealToStr;
//
    // Known in ILASM as [RTS]RTS::RealToStr
    public static void RealToStr(double num,
                                 char[] str)
    {
        System.String lls = ((System.Double)num).ToString("R");
        int           len = lls.Length;

        lls.CopyTo(0, str, 0, len);
        str[len] = '\0';
    }
Example #3
0
 internal AssemblyNameLexer(String s)
 {
     // Convert string to char[] with NUL terminator. (An actual NUL terminator in the input string will be treated
     // as an actual end of string: this is compatible with desktop behavior.)
     char[] chars = new char[s.Length + 1];
     s.CopyTo(0, chars, 0, s.Length);
     _chars = chars;
     _index = 0;
 }
Example #4
0
/* ------------------------------------------------------------ */
//  PROCEDURE SRealToStrLocal*(r : SHORTREAL; OUT s : ARRAY OF CHAR);
//  (** Decode a CP REAL into an array *)
//  BEGIN END SRealToStr;
//
    // Known in ILASM as [RTS]RTS::SRealToStr
    public static void SRealToStr(float num,
                                  char[] str)
    {
        // System.String lls = System.Convert.ToString(num);
        System.String lls = ((System.Single)num).ToString("R", currentCulture);
        int           len = lls.Length;

        lls.CopyTo(0, str, 0, len);
        str[len] = '\0';
    }
Example #5
0
/* -------------------------------------------------------------------- */

    // Known in ILASM as [RTS]CP_rts::StrToChF
    public static void StrToChF(char[] res, System.String inp)
    {
        if (inp == null)
        {
            res[0] = '\0'; return;
        }
        int len = inp.Length;

        inp.CopyTo(0, res, 0, len);
        res[len] = '\0';
    }
Example #6
0
//
//  PROCEDURE GetDateString(OUT str : ARRAY OF CHAR);
//
    // Known in ILASM as [RTS]RTS::GetDateString
    public static void GetDateString(char[] arr)
    {
        System.String str = System.DateTime.Now.ToString();
        int           len = str.Length;

        if (len >= arr.Length)
        {
            len = arr.Length - 1;
        }
        str.CopyTo(0, arr, 0, len);
        arr[len] = '\0';
    }
Example #7
0
/* ------------------------------------------------------------ */
//  PROCEDURE LongToStr*(i : LONGINT; OUT s : ARRAY OF CHAR);
//  (** Decode a CP LONGINT into an array *)
//  BEGIN END LongToStr;
//
    // Known in ILASM as [RTS]RTS::LongToStr
    public static void LongToStr(long num,
                                 char[] str)
    {
        System.String lls = System.Convert.ToString(num);
        int           len = lls.Length;

        if (len >= str.Length)
        {
            len = str.Length - 1;
        }
        lls.CopyTo(0, str, 0, len);
        str[len] = '\0';
    }
Example #8
0
/* ------------------------------------------------------------ */
//  PROCEDURE SRealToStr*(r : SHORTREAL; OUT s : ARRAY OF CHAR);
//  (** Decode a CP REAL into an array *)
//  BEGIN END SRealToStr;
//
    // Known in ILASM as [RTS]RTS::SRealToStr
    public static void SRealToStr(float num,
                                  char[] str)
    {
        // System.String lls = System.Convert.ToString(num);
#if BETA1
        System.String lls = ((System.Single)num).ToString();
#else //BETA2
        System.String lls = ((System.Single)num).ToString("R");
#endif
        int len = lls.Length;
        lls.CopyTo(0, str, 0, len);
        str[len] = '\0';
    }
Example #9
0
/* ------------------------------------------------------------ */
//  PROCEDURE RealToStrLocal*(r : REAL; OUT s : ARRAY OF CHAR);
//  (** Decode a CP REAL into an array *)
//  BEGIN END RealToStrInvar;
//
    // Known in ILASM as [RTS]RTS::RealToStrLocal
    public static void RealToStrLocal(double num,
                                      char[] str)
    {
#if BETA1
        System.String lls = System.Convert.ToString(num);
#else //BETA2
        System.String lls =
            ((System.Double)num).ToString("R", currentCulture);
#endif
        int len = lls.Length;
        lls.CopyTo(0, str, 0, len);
        str[len] = '\0';
    }
Example #10
0
/* -------------------------------------------------------------------- */
//
//  PROCEDURE mkArr*(s : String) : RTS.CharOpen); END mkArr;
//
/* -------------------------------------------------------------------- */
    // Known in ILASM as [RTS]NativeStrings::mkArr
    public static char[] mkArr(System.String inp)
    {
        if (inp == null)
        {
            return(null);
        }

        int len = inp.Length;

        char[] res = new char[len + 1];
        inp.CopyTo(0, res, 0, len);
        res[len] = '\0';
        return(res);
    }
Example #11
0
/* -------------------------------------------------------------------- */

    // Known in ILASM as [RTS]CP_rts::strToChO
    public static char[] strToChO(System.String input)
    {
        if (input == null)
        {
            return(null);
        }

        int len = input.Length;

        char[] arr = new char[len + 1];
        input.CopyTo(0, arr, 0, len);
        arr[len] = '\0';
        return(arr);
        //  return input.ToCharArray();
    }
        /// <summary>
        /// Parses new console command
        /// </summary>
        /// <param name="Line">Command to parse</param>
        /// <param name="server">Current Server instance</param>
        public void parseConsoleCommand(String Line, Server server)
        {
            ConsoleSender cSender = new ConsoleSender(server);
            cSender.ConsoleCommand.Message = Line;
            Sender sender = new Sender();
            sender.Op = true;
            cSender.ConsoleCommand.Sender = sender;
            server.PluginManager.processHook(Hooks.CONSOLE_COMMAND, cSender.ConsoleCommand);
            if (cSender.ConsoleCommand.Cancelled)
            {
                return;
            }

            if (Line.Contains("\""))
            {
                String[] commands = new String[Line.Substring(0, Line.IndexOf("\"")).Split(' ').Length + Line.Substring(Line.LastIndexOf("\"")).Split(' ').Length - 1];
                String[] temp = Line.Substring(0, Line.IndexOf("\"")).Trim().Split(' ');
                String[] temp2 = Line.Substring(Line.LastIndexOf("\"") + 1).Trim().Split(' ');
                String[] temp3 = new String[temp.Length + 1];
                temp.CopyTo(temp3, 0);

                temp3[temp3.Length - 1] = Line.Substring(Line.IndexOf("\""), Line.LastIndexOf("\"") - Line.IndexOf("\"")).Remove(0,1);

                temp3.CopyTo(commands, 0);
                temp2.CopyTo(commands, temp3.Length);

                if (commands == null || commands.Length <= 0)
                {
                    Program.tConsole.WriteLine("Issue parsing Console Command for " + Hooks.CONSOLE_COMMAND.ToString());
                    return;
                }
                switchCommands(commands, cSender.ConsoleCommand.Sender);

            }
            else
            {
                String[] commands = Line.Trim().ToLower().Split(' ');

                if (commands == null || commands.Length <= 0)
                {
                    Program.tConsole.WriteLine("Issue parsing Console Command for " + Hooks.CONSOLE_COMMAND.ToString());
                    return;
                }
                switchCommands(commands, cSender.ConsoleCommand.Sender);
            }
        }
    public virtual bool runTest
        ()
    {
        System.Console.Error.WriteLine("String.EndsWith: Co1150EW runTest starting...");
        int nErrorBits = 0;

        System.String swrString2 = null;
        swrString2 = "nOpqRs";
        if (swrString2.EndsWith("qRs") != true)
        {
            nErrorBits = nErrorBits | 0x1;
        }
        if (swrString2.EndsWith("qrs") != false)
        {
            nErrorBits = nErrorBits | 0x2;
        }
        if (swrString2.EndsWith("nOp") != false)
        {
            nErrorBits = nErrorBits | 0x4;
        }
        Char[]      swrString3 = new Char[8];
        IntlStrings intl       = new IntlStrings();

        swrString2 = intl.GetString(10, true, true);
        swrString2.CopyTo(2, swrString3, 0, swrString2.Length - 2);
        String swrString4 = new String(swrString3);

        if (swrString2.EndsWith(swrString4) != true)
        {
            nErrorBits = nErrorBits | 0x1;
        }
        System.Console.Error.WriteLine(nErrorBits);
        if (nErrorBits == 0)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Example #14
0
        /*
        ** Name: setString
        **
        ** Description:
        **	Assign a String value as the data value.
        **	The data value will be NULL if the input
        **	value is null, otherwise non-NULL.
        **
        ** Input:
        **	value	String value (may be null).
        **
        ** Output:
        **	None.
        **
        ** Returns:
        **	void.
        **
        ** History:
        **	 1-Dec-03 (gordy)
        **	    Created.
        */
        public override void setString( String value )
        {
            if ( value == null )
            setNull();
            else
            {
            /*
            ** Apply length limit if applicable.
            */
            int length = value.Length;
            if (limit >= 0 && length >= limit) length = limit;

            /*
            ** Now assign the new value.
            */
            clear();
            ensure( length );
            value.CopyTo( 0, this.value, 0, length );
            this.length = length;
            }
            return;
        }
Example #15
0
 private String[] Union(String[] a1, String[] a2)
 {
     String[] tot = new String[a1.Length + a2.Length];
     a1.CopyTo(tot, 0);
     a2.CopyTo(tot, a1.Length);
     return tot;
 }
Example #16
0
        /// <summary>
        /// "Распаковка" имени файла из префиксного формата в исходный
        /// </summary>
        /// <param name="filename">Имя файла для "распаковки"</param>
        /// <param name="volNum">Номер текущего тома</param>
        /// <param name="dataCount">Количество основных томов</param>
        /// <param name="eccCount">Количество томов для восстановления</param>
        /// <returns>Булевский флаг операции</returns>
        public bool Unpack(ref String filename, ref int volNum, ref int dataCount, ref int eccCount)
        {            
            // Если имя файла для распаковки содержит менее одного символа
            // за исключением префикса, или если упакованное имя файла не
            // содержит специфического символа в начале и точки в конце,
            // то отказываем в обработке
            if (
                    (filename.Length < 15)
                 ||
                    (filename[0] != '@')
                 ||
                    (filename[13] != '.')
                )
            {
                return false;
            }

            // Инициализируем массив для хранения набора символов "HEX-представления"
            Char[] prefixPartChr = new Char[12];

            // Копируем данные "HEX-представления" volNum, dataCount, eccCount в массив Char
            filename.CopyTo(1, prefixPartChr, 0, 12);

            // Извлекаем номер тома            
            if (!HEXToInt16(ref volNum, prefixPartChr, 0))
            {
                return false;
            }

            // Извлекаем количество основных томов            
            if (!HEXToInt16(ref dataCount, prefixPartChr, 4))
            {
                return false;
            }

            // Извлекаем количество томов для восстановления
            if (!HEXToInt16(ref eccCount, prefixPartChr, 8))
            {
                return false;
            }

            // Убираем префикс из имени файла
            filename = filename.Substring(14, (filename.Length - 14));

            return true;
        }
	// Write a string to the stream writer.
	public override void Write(String value)
			{
				if(value == null)
					return;
				int temp;
				int index = 0;
				int count = value.Length;
				if(stream == null)
				{
					throw new ObjectDisposedException(_("IO_StreamClosed"));
				}
				while(count > 0)
				{
					temp = bufferSize - inBufferLen;
					if(temp > count)
					{
						temp = count;
					}
					value.CopyTo(index, inBuffer, inBufferLen, temp);
					index += temp;
					count -= temp;
					inBufferLen += temp;
					if(inBufferLen >= bufferSize)
					{
						Convert(false);
					}
				}
				if(autoFlush)
				{
					Convert(false);
					stream.Flush();
				}
			}
	public void TestCopyTo() {
		{
			bool errorThrown = false;
			try {
				Char[] c1 = new Char[2];
				c1.CopyTo(null, 2);
			} catch (ArgumentNullException) {
				errorThrown = true;
			}
			Assert("#E61", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[] c1 = new Char[2];
				Char[,] c2 = new Char[2,2];
				c1.CopyTo(c2, 2);
			} catch (ArgumentException) {
				errorThrown = true;
			}
			Assert("#E62", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[,] c1 = new Char[2,2];
				Char[] c2 = new Char[2];
				c1.CopyTo(c2, -1);
			} catch (RankException) {
				errorThrown = true;
			}
			Assert("#E63", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[,] c1 = new Char[2,2];
				Char[] c2 = new Char[2];
				c1.CopyTo(c2, 2);
			} catch (RankException) {
				errorThrown = true;
			}
			Assert("#E64", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[] c1 = new Char[2];
				Char[] c2 = new Char[2];
				c1.CopyTo(c2, -1);
			} catch (ArgumentOutOfRangeException) {
				errorThrown = true;
			}
			Assert("#E65", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[] c1 = new Char[2];
				Char[] c2 = new Char[2];
				c1.CopyTo(c2, 3);
			} catch (ArgumentException) {
				errorThrown = true;
			}
			Assert("#E66", errorThrown);
		}
		{
			bool errorThrown = false;
			try {
				Char[] c1 = new Char[2];
				Char[] c2 = new Char[2];
				c1.CopyTo(c2, 1);
			} catch (ArgumentException) {
				errorThrown = true;
			}
			Assert("#E67", errorThrown);
		}

		{
			bool errorThrown = false;
			try {
				String[] c1 = new String[2];
				// TODO: this crashes mono if there are null
				// values in the array.
				c1[1] = "hey";
				c1[0] = "you";
				Char[] c2 = new Char[2];
				c2[1] = 'a';
				c2[0] = 'z';
				c1.CopyTo(c2, 0);
			} catch (ArrayTypeMismatchException) {
				errorThrown = true;
			}
			Assert("#E68", errorThrown);
		}

		Char[] orig = {'a', 'b', 'c', 'd'};
		Char[] copy = new Char[10];
		Array.Clear(copy, 0, copy.Length);
		orig.CopyTo(copy, 3);
		AssertEquals("#E69", (char)0, copy[0]);
		AssertEquals("#E70", (char)0, copy[1]);
		AssertEquals("#E71", (char)0, copy[2]);
		AssertEquals("#E72", orig[0], copy[3]);
		AssertEquals("#E73", orig[1], copy[4]);
		AssertEquals("#E74", orig[2], copy[5]);
		AssertEquals("#E75", orig[3], copy[6]);
		AssertEquals("#E76", (char)0, copy[7]);
		AssertEquals("#E77", (char)0, copy[8]);
		AssertEquals("#E78", (char)0, copy[9]);

		{
			// The following is valid and must not throw an exception.
			bool errorThrown = false;
			try {
				int[] src = new int [0];
				int[] dest = new int [0];
				src.CopyTo (dest, 0);
			} catch (ArgumentException) {
				errorThrown = true;
			}
			Assert("#E79", !errorThrown);
		}

		{
			// bug #38812
			bool errorThrown = false;
			try {
				CClass[] src = new CClass [] { new CClass () };
				BClass[] dest = new BClass [1];

				src.CopyTo (dest, 0);

			} catch (ArrayTypeMismatchException) {
				errorThrown = true;
			}
			Assert("#E80", errorThrown);
		}
	}
Example #19
0
 private string[] BuildFinalArray(String[] arr1, int count)
 {
     arr1.CopyTo(FinaleArray, count);
     return FinaleArray;
 }
Example #20
0
        // Writes a string followed by a line terminator to the text stream.
        //
        public virtual void WriteLine(String value) {

            if (value==null) {
                WriteLine();
            }
            else {
                // We'd ideally like WriteLine to be atomic, in that one call
                // to WriteLine equals one call to the OS (ie, so writing to 
                // console while simultaneously calling printf will guarantee we
                // write out a string and new line chars, without any interference).
                // Additionally, we need to call ToCharArray on Strings anyways,
                // so allocating a char[] here isn't any worse than what we were
                // doing anyways.  We do reduce the number of calls to the 
                // backing store this way, potentially.
                int vLen = value.Length;
                int nlLen = CoreNewLine.Length;
                char[] chars = new char[vLen+nlLen];
                value.CopyTo(0, chars, 0, vLen);
                // CoreNewLine will almost always be 2 chars, and possibly 1.
                if (nlLen == 2) {
                    chars[vLen] = CoreNewLine[0];
                    chars[vLen+1] = CoreNewLine[1];
                }
                else if (nlLen == 1)
                    chars[vLen] = CoreNewLine[0];
                else
                    Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
                Write(chars, 0, vLen + nlLen);
            }
            /*
            Write(value);  // We could call Write(String) on StreamWriter...
            WriteLine();
            */
        }
        public override void Write(String value)
        {
            if (value != null)
            {

                CheckAsyncTaskInProgress();

                int count = value.Length;
                int index = 0;
                while (count > 0) {
                    if (charPos == charLen) Flush(false, false);
                    int n = charLen - charPos;
                    if (n > count) n = count;
                    Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");
                    value.CopyTo(index, charBuffer, charPos, n);
                    charPos += n;
                    index += n;
                    count -= n;
                }
                if (autoFlush) Flush(true, false);
            }
        }
Example #22
0
 //join 2 String arrays
 internal static String[] StrArray(String[] sa1, String[] sa2)
 {
     String[] ss = new String[sa1.Length + sa2.Length];
     sa1.CopyTo(ss, 0);
     sa2.CopyTo(ss, sa1.Length);
     return ss;
 }
Example #23
0
        public void ShellShortChangesInputArray()
        {
            IComparable[] inputArray = new String[]
            {
                "L", "E", "E", "A", "M", "H", "L", "E", "P", "S", "O", "L", "T", "S", "X", "R"
            };
            IComparable[] originalArray = new String[16];
            inputArray.CopyTo(originalArray, 0);

            sortAlgorithm.SetAlgorithm(new ShellSort());
            sortAlgorithm.Sort(ref inputArray);

            CollectionAssert.AreNotEqual(originalArray, inputArray);
        }
Example #24
0
		public static string ToNYSIISCode(string name)
		{
			int inNameCharOffset = 0;
			int stopSearchforSZ = 0;
			int maxLength = 200;
			int prevCharValue = 0;
			char firstChar = ' ';
			char[] inNameArray = new char[maxLength];
			char[] phonKeyArray = new char[maxLength];
			bool prependVowel = false;

			StringBuilder MyStringBuilder = new StringBuilder(" ");

			name = name.ToUpper();
			
			// copy inName to char array
			name.CopyTo(0, inNameArray, 0, name.Length);

			firstChar = inNameArray[0];

			// remove all 'S' and 'Z' chars from the end of the surname
			for(inNameCharOffset = (name.Length - 1); ((inNameCharOffset >= 1) && (stopSearchforSZ == 0)); inNameCharOffset--)
			{
				if(inNameArray[inNameCharOffset] == 'S' ||
					inNameArray[inNameCharOffset] == 'Z')
				{
					inNameArray[inNameCharOffset] = ' ';
				}
				else
				{
					stopSearchforSZ = 1;
				}
			}

			// copy char array to string
			name = new String(inNameArray, 0, name.Length);  
			MyStringBuilder = new StringBuilder(name);

			MyStringBuilder.Replace(" ", "");

			name = String.Format(MyStringBuilder + "");
			MyStringBuilder = new StringBuilder(name);
			
			// transcode initial strings MAC => MC 
			if(MyStringBuilder.Length > 2)
			{
				MyStringBuilder.Replace("MAC", "MC", 0, 3);
			}

			// transcode initial strings PF => F 

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("PF", "F", 0, 2);
			}

			// Transcode trailing strings as follows,	
			// IX => IC 
			// EX => EC 
			// YE,EE,IE => Y 
			// NT,ND => D 

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("IX", "IC", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("EX", "EC", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("YE", "Y", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("EE", "Y", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("IE", "Y", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("NT", "D", (MyStringBuilder.Length - 2), 2);
				MyStringBuilder.Replace("ND", "D", (MyStringBuilder.Length - 2), 2);
			}

			// transcode 'EV' to 'EF' if not at start of name

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("EV", "EF", 1, (MyStringBuilder.Length - 1));
			}

			// remove any 'W' that follows a vowel

			MyStringBuilder.Replace("AW", "A");
			MyStringBuilder.Replace("EW", "E");
			MyStringBuilder.Replace("IW", "I");
			MyStringBuilder.Replace("OW", "O");
			MyStringBuilder.Replace("UW", "U");

			// replace all vowels with 'A'

			MyStringBuilder.Replace("A", "A");
			MyStringBuilder.Replace("E", "A");
			MyStringBuilder.Replace("I", "A");
			MyStringBuilder.Replace("O", "A");
			MyStringBuilder.Replace("U", "A");

			// transcode 'GHT' to 'GT'

			MyStringBuilder.Replace("GHT", "GT");

			// transcode 'DG' to 'G'

			MyStringBuilder.Replace("DG", "G");

			// transcode 'PH' to 'F'

			MyStringBuilder.Replace("PH", "F");

			// if not first character, eliminate all 'H' preceded or followed by a vowel

			MyStringBuilder.Replace("AH", "A");
			if(MyStringBuilder.Length > 2)
			{
				MyStringBuilder.Replace("HA", "A", 1, (MyStringBuilder.Length - 1));
			}

			// change 'KN' to 'N', else 'K' to 'C'

			MyStringBuilder.Replace("KN", "N");
			MyStringBuilder.Replace("K", "C");

			// if not first character, change 'M' to 'N'

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("M", "N", 1, (MyStringBuilder.Length - 1));
			}

			// if not first character, change 'Q' to 'G'

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("Q", "G", 1, (MyStringBuilder.Length - 1));
			}

			// transcode 'SH' to 'S'

			MyStringBuilder.Replace("SH", "S");

			// transcode 'SCH' to 'S'

			MyStringBuilder.Replace("SCH", "S");

			// transcode 'YW' to 'Y'

			MyStringBuilder.Replace("YW", "Y");

			// if not first or last character, change 'Y' to 'A'

			if(MyStringBuilder.Length > 2)
			{
				MyStringBuilder.Replace("Y", "A", 1, (MyStringBuilder.Length - 2));
			}

			// transcode 'WR' to 'R'

			MyStringBuilder.Replace("WR", "R");

			// if not first character, change 'Z' to 'S'

			if(MyStringBuilder.Length > 1)
			{
				MyStringBuilder.Replace("Z", "S", 1, (MyStringBuilder.Length - 1));
			}

			// transcode terminal 'AY' to 'Y'

			if(MyStringBuilder.Length > 2)
			{
				MyStringBuilder.Replace("AY", "Y", 1, (MyStringBuilder.Length - 1));
			}

			name = String.Format(MyStringBuilder + "");
			
			// copy inName to char array
			name.CopyTo(0, inNameArray, 0, name.Length);   
			stopSearchforSZ = 0;

			// remove traling vowels
			for(inNameCharOffset = (name.Length - 1); ((inNameCharOffset >= 1) && (stopSearchforSZ == 0)); inNameCharOffset--)
			{
				if(inNameArray[inNameCharOffset] == 'A')
				{
					inNameArray[inNameCharOffset] = ' ';
				}
				else					
				{
					stopSearchforSZ = 1;
				}
			}

			// copy char array to string
			name = new String(inNameArray, 0, MyStringBuilder.Length);  
			MyStringBuilder = new StringBuilder(name);

			MyStringBuilder.Replace(" ", "");

			name = String.Format(MyStringBuilder + "");
			
			// copy inName to char array
			name.CopyTo(0, inNameArray, 0, name.Length);   

			// collapse all strings of repeated characters
			// (also removes non-alpha chars)

			for(inNameCharOffset = 0; inNameCharOffset < name.Length; inNameCharOffset++)
			{
				if(prevCharValue == inNameArray[inNameCharOffset] ||
					inNameArray[inNameCharOffset] < 'A' ||
					inNameArray[inNameCharOffset] > 'Z')
				{
					inNameArray[inNameCharOffset] = ' ';
				}
				else
				{
					prevCharValue = inNameArray[inNameCharOffset];
				}
			}

			// if first char of original surname is a vowel, prepend to code (or replace initial transcoded 'A')

			if(firstChar == 'A' ||
				firstChar == 'E' ||
				firstChar == 'I' ||
				firstChar == 'O' ||
				firstChar == 'U')
			{
				if(inNameArray[0] == 'A')
				{
					inNameArray[0] = firstChar;
				}
				else
				{
					prependVowel = true;
				}
			}

			// copy char array to string
			name = new String(inNameArray, 0, name.Length);  

			MyStringBuilder = new StringBuilder(name);

			MyStringBuilder.Replace(" ", "");

			if(prependVowel)
			{
				name = String.Format(firstChar.ToString() + MyStringBuilder + "");
			}
			else
			{
				name = String.Format(MyStringBuilder + "");
			}

			return(name);
		}
        /// <summary>
        /// Parses player commands
        /// </summary>
        /// <param name="player">Sending player</param>
        /// <param name="Line">Command to parse</param>
        public void parsePlayerCommand(Player player, String Line)
        {
            if (Line.StartsWith("/"))
            {
                Line = Line.Remove(0, 1);
            }
            if (Line.Contains("\""))
            {
                String[] commands = new String[Line.Substring(0, Line.IndexOf("\"")).Split(' ').Length + Line.Substring(Line.LastIndexOf("\"")).Split(' ').Length - 1];
                String[] temp = Line.Substring(0, Line.IndexOf("\"")).Trim().Split(' ');
                String[] temp2 = Line.Substring(Line.LastIndexOf("\"") + 1).Trim().Split(' ');
                String[] temp3 = new String[temp.Length + 1];
                temp.CopyTo(temp3, 0);

                temp3[temp3.Length - 1] = Line.Substring(Line.IndexOf("\""), Line.LastIndexOf("\"") - Line.IndexOf("\"")).Replace("\"", "");

                temp3.CopyTo(commands, 0);
                temp2.CopyTo(commands, temp3.Length);

                if (commands == null || commands.Length <= 0)
                {
                    Program.tConsole.WriteLine("Issue parsing Player Command for " + Hooks.PLAYER_COMMAND.ToString() + " from " + player.Name);
                    return;
                }
                switchCommands(commands, player);

            }
            else
            {
                String[] commands = Line.Trim().ToLower().Split(' ');

                if (commands == null || commands.Length <= 0)
                {
                    Program.tConsole.WriteLine("Issue parsing Player Command for " + Hooks.PLAYER_COMMAND.ToString() + " from " + player.Name);
                    return;
                }
                switchCommands(commands, player);
            }
        }
Example #26
0
 void WriteString(String text)
 {
     if (text == null)
     {
         Debug.Fail("text shouldn't be null!");
         text = "UNKNOWN ERROR: text shouldn't be null!";
     }
     if (m_tmpWrite.Length < text.Length)
     {
         Array.Resize(ref m_tmpWrite, Math.Max(m_tmpWrite.Length * 2, text.Length));
     }
     text.CopyTo(0, m_tmpWrite, 0, text.Length);
     m_streamWriter.Write(m_tmpWrite, 0, text.Length);
 }
Example #27
0
 void WriteString(String text)
 {
     if (m_tmpWrite.Length < text.Length)
     {
         Array.Resize(ref m_tmpWrite, Math.Max(m_tmpWrite.Length * 2, text.Length));
     }
     text.CopyTo(0, m_tmpWrite, 0, text.Length);
     m_streamWriter.Write(m_tmpWrite, 0, text.Length);
 }
Example #28
0
        private float minMax(String[] board, List<int> freeSpace, String aiMark, float bestScore)
        {
            int rows = (int)(Math.Sqrt(board.Length));
            int cols = rows;

            float avgCount = 0;
            float avgProb = 0;
            String[] tempBoard = new String[rows * cols];
            String[] tempBoardP = new String[rows * cols];
            board.CopyTo(tempBoard, 0);

            int aiID = 0;
            int playerID = 0;
            if (aiMark == "X")
            {
                aiID = 1;
                playerID = 2;
            }
            else
            {
                aiID = 2;
                playerID = 1;
            }


            if (victoryCheck(board) == aiID || victoryCheck(board) == 4)
            {
                //this is a winning leaf
                return 1;
            }
            else if (victoryCheck(board) == playerID)
            {
                //this is a losing leaf
                return 0;
            }

            else
            {
                //if not a tie, win, or loss, then there are more moves to make.
                for (int x = 0; x < freeSpace.Count; x++)
                {
                    List<int> passIn = new List<int>(freeSpace);
                    passIn.RemoveAt(x);

                    board.CopyTo(tempBoard, 0);
                    tempBoard[freeSpace[x]] = aiMark;

                    //did we win?
                    if (victoryCheck(tempBoard) == aiID || victoryCheck(tempBoard) == 4)
                    {
                        //this is a winning leaf
                        return 1;
                    }

                    if (passIn.Count > 0)
                    {
                        //player's possible response if we didn't win
                        for (int y = 0; y < passIn.Count; y++)
                        {
                            tempBoard.CopyTo(tempBoardP, 0);
                            if (aiMark == "X")
                            {
                                tempBoardP[passIn[y]] = "O";
                            }
                            else
                            {
                                tempBoardP[passIn[y]] = "X";
                            }
                            //displayGameBoard(tempBoardP);


                            List<int> pResponse = new List<int>(passIn);
                            pResponse.RemoveAt(y);
                            avgProb += minMax(tempBoardP, pResponse, aiMark, bestScore);
                            avgCount++;

                            if (((avgProb - (((y + 1) + ((x + 1) * passIn.Count)))) + 1) / ((passIn.Count) * (freeSpace.Count)) < bestScore)
                            {
                                //give up bad branch
                                //prune
                                //return 0;
                            }
                        }
                    }
                    else
                    {
                        avgProb += minMax(tempBoard, passIn, aiMark, bestScore);
                        avgCount++;
                    }
                }
                return (avgProb / avgCount);
            }
        }
Example #29
0
        private void AppendString(String value)
        {
            int valueLength;
            int lengthEncodingSize;
            int nextTop;


            valueLength = value.Length;

            lengthEncodingSize = valueLength >= 0x8000 ? 2 : 1;
            
            nextTop = this._sourceTop + lengthEncodingSize + valueLength;
            
            if (nextTop > this._sourceBuffer.Length)
            {
                this.IncreaseSourceCapacity(nextTop);
            }

            if (valueLength >= 0x8000)
            {
                // Use 2 chars to encode strings exceeding 32K, were the highest
                // bit in the first char indicates presence of the next byte
                // NOTE: There is no '>>>' in C#. Handle it via unsigned, shift, signed.
                //       Info found here: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1690218&SiteID=1
                uint x = Convert.ToUInt32(valueLength);
                this._sourceBuffer[this._sourceTop] = Convert.ToChar(0x8000 | Convert.ToInt32(x >> 16));
                this._sourceTop++;
            }

            this._sourceBuffer[this._sourceTop] = Convert.ToChar(valueLength);
            this._sourceTop++;
            value.CopyTo(0,
                this._sourceBuffer,
                this._sourceTop,
                valueLength);
            this._sourceTop = nextTop;
        }
Example #30
0
        private int DecideWithAttractiveness()
        {
            int len = _unusedSlots.Count;

            String[] board = new String[_tiles.Count];
            for (int i = 0; i < len; ++i)
            {
                board[i] = GetVisualMark(_tiles[i].mark);
            }

            String aiMark = _playerStartedFirst ? "O" : "X";

            int aiID = 0;
            int playerID = 0;

            if (aiMark == "X")
            { // AI started first
                aiID = 1;
                playerID = 2;
            }
            else
            { // player started first
                aiID = 2;
                playerID = 1;
            }

            String[] tempBoard = new String[_tiles.Count];
            String[] tempBoardP = new String[_tiles.Count];

            board.CopyTo(tempBoard, 0);
            float prob = 0;
            float probCount = 0;
            float maxProb = 0;
            int maxIndex = 0;

            for (int x = 0; x < _unusedSlots.Count; x++)
            {
                List<int> passIn = new List<int>(_unusedSlots);
                passIn.RemoveAt(x);

                board.CopyTo(tempBoard, 0);
                tempBoard[_unusedSlots[x]] = aiMark;

                // NOTE: This should have been resolved from the generic case. uncomment to make sure later
                //did we win?
                if (victoryCheck(tempBoard) == aiID)// || victoryCheck(tempBoard) == 4) // draw case should be handled by generic case
                {
                    //this is a winning leaf
                    maxIndex = x;
                    throw new Exception("Error: This should've been handled by the Generic Cases.");
                    //break;
                }

                if (passIn.Count > 0)
                {
                    //player's possible response if we didn't win
                    for (int y = 0; y < passIn.Count; y++)
                    {
                        tempBoard.CopyTo(tempBoardP, 0);
                        if (aiMark == "X")
                        {
                            tempBoardP[passIn[y]] = "O";
                        }
                        else
                        {
                            tempBoardP[passIn[y]] = "X";
                        }

                        List<int> pResponse = new List<int>(passIn);
                        pResponse.RemoveAt(y);
                        prob += minMax(tempBoardP, pResponse, aiMark, maxProb);
                        probCount++;
                    }
                }
                if ((prob / probCount) > maxProb)
                {
                    maxIndex = x;
                    maxProb = prob / probCount;
                }
                probCount = 0;
                prob = 0;
            }

            return _unusedSlots[maxIndex];
        }
        // We pass in private instance fields of this MarshalByRefObject-derived type as local params
        // to ensure performant access inside the state machine that corresponds this async method.
        // Fields that are written to must be assigned at the end of the method *and* before instance invocations.
        private static async Task WriteAsyncInternal(StreamWriter _this, String value,
                                                     Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
                                                     bool autoFlush, bool appendNewLine)
        {
            Contract.Requires(value != null);

            int count = value.Length;
            int index = 0;

            while (count > 0)
            {
                if (charPos == charLen) {
                    await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
                    Contract.Assert(_this.charPos == 0);
                    charPos = 0;
                }

                int n = charLen - charPos;
                if (n > count)
                    n = count;

                Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress!  This is most likely a race condition in user code.");

                value.CopyTo(index, charBuffer, charPos, n);

                charPos += n;
                index += n;
                count -= n;
            }

            if (appendNewLine)
            {
                for (Int32 i = 0; i < coreNewLine.Length; i++)   // Expect 2 iterations, no point calling BlockCopy
                {
                    if (charPos == charLen) {
                        await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
                        Contract.Assert(_this.charPos == 0);
                        charPos = 0;
                    }

                    charBuffer[charPos] = coreNewLine[i];
                    charPos++;
                }
            }

            if (autoFlush) {
                await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
                Contract.Assert(_this.charPos == 0);
                charPos = 0;
            }

            _this.CharPos_Prop = charPos;
        }
Example #32
0
        public override void Write(String value)
        {
            if (value != null)
            {

                int count = value.Length;
                int index = 0;
                while (count > 0)
                {
                    if (charPos == charLen) Flush(false, false);
                    int n = charLen - charPos;
                    if (n > count) n = count;
                    value.CopyTo(index, charBuffer, charPos, n);
                    charPos += n;
                    index += n;
                    count -= n;
                }
                if (autoFlush) Flush(true, false);
            }
        }
Example #33
0
 public static bool regionMatches(String orig, bool ignoreCase, int toffset,
     String other, int ooffset, int len)
 {
     char[] ta = new char[orig.Length];
     char[] pa = new char[other.Length];
     orig.CopyTo(0, ta, 0, orig.Length);
     int to = toffset;
     other.CopyTo(0, pa, 0, other.Length);
     int po = ooffset;
     // Note: toffset, ooffset, or len might be near -1>>>1.
     if ((ooffset < 0) || (toffset < 0) || (toffset > (long)orig.Length - len) ||
         (ooffset > (long)other.Length - len))
     {
         return false;
     }
     while (len-- > 0)
     {
         char c1 = ta[to++];
         char c2 = pa[po++];
         if (c1 == c2)
         {
             continue;
         }
         if (ignoreCase)
         {
             // If characters don't match but case may be ignored,
             // try converting both characters to uppercase.
             // If the results match, then the comparison scan should
             // continue.
             char u1 = char.ToUpper(c1);
             char u2 = char.ToUpper(c2);
             if (u1 == u2)
             {
                 continue;
             }
             // Unfortunately, conversion to uppercase does not work properly
             // for the Georgian alphabet, which has strange rules about case
             // conversion.  So we need to make one last check before
             // exiting.
             if (char.ToLower(u1) == char.ToLower(u2))
             {
                 continue;
             }
         }
         return false;
     }
     return true;
 }
Example #34
0
        internal static String NormalizePathSlow(String path, bool fullCheck) {
            BCLDebug.Assert(path != null, "path can't be null");
            // If we're doing a full path check, trim whitespace and look for
            // illegal path characters.

            if (fullCheck) {
                // Trim whitespace off the end of the string.
                path = path.TrimEnd();

                // Look for illegal path characters.
                CheckInvalidPathChars(path);
            }

            int index = 0;
            char[] newBuffer = new char[MaxPath];
            int newBufferIndex = 0;
            char[] finalBuffer = null;
            uint numSpaces = 0;
            uint numDots = 0;
            bool fixupDirectorySeparator = false;
            // Number of significant chars other than potentially suppressible
            // dots and spaces since the last directory or volume separator char
            uint numSigChars = 0;
            int lastSigChar = -1; // Index of last significant character.
            // Whether this segment of the path (not the complete path) started
            // with a volume separator char.  Reject "c:...".
            bool startedWithVolumeSeparator = false;
            bool firstSegment = true;
            bool mightBeShortFileName = false;

#if !PLATFORM_UNIX
            // Win9x fixup - //server/share becomes c://server/share.
            // This prevents our code from turning "\\server" into "\server".
            // On Win9x, //server/share becomes c://server/share
            if (path.Length > 0 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar)) {
                newBuffer[newBufferIndex++] = '\\';
                index++;
                lastSigChar = 0;
            }
#endif

            // Normalize the string, stripping out redundant dots, spaces, and 
            // slashes.
            while (index < path.Length) {
                char currentChar = path[index];

                // We handle both directory separators and dots specially.  For 
                // directory separators, we consume consecutive appearances.  
                // For dots, we consume all dots beyond the second in 
                // succession.  All other characters are added as is.  In 
                // addition we consume all spaces after the last other char
                // in a directory name up until the directory separator.

                if (currentChar == DirectorySeparatorChar || currentChar == AltDirectorySeparatorChar) {
                    // If we have a path like "123.../foo", remove the trailing dots.
                    // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", don't.
                    // Also remove trailing spaces from both files & directory names.
                    // This was agreed on with the OS team to fix undeletable directory
                    // names ending in spaces.

                    // If we saw a '\' as the previous last significant character and
                    // are simply going to write out dots, suppress them.
                    // If we only contain dots and slashes though, only allow
                    // a string like [dot]+ [space]*.  Ignore everything else.
                    // Legal: "\.. \", "\...\", "\. \"
                    // Illegal: "\.. .\", "\. .\", "\ .\"
                    if (numSigChars == 0) {
                        // Dot and space handling
                        if (numDots > 0) {
                            // Look for ".[space]*" or "..[space]*"
                            int start = lastSigChar + 1;
                            if (path[start] != '.')
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                            // Only allow "[dot]+[space]*", and normalize the 
                            // legal ones to "." or ".."
                            if (numDots >= 2) {
                                // Reject "C:..."
                                if (startedWithVolumeSeparator && numDots > 2)

                                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                                if (path[start + 1] == '.') {
                                    // Search for a space in the middle of the
                                    // dots and throw
                                    for(int i=start + 2; i < start + numDots; i++) {
                                        if (path[i] != '.')
                                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                    }

                                    numDots = 2;
                                }
                                else {
                                    if (numDots > 1)
                                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                                    numDots = 1;
                                }
                            }
                                    
                            if (newBufferIndex + numDots + 1 >= MaxPath)
                                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

                            if (numDots == 2) {
                                newBuffer[newBufferIndex++] = '.';
                            }

                            newBuffer[newBufferIndex++] = '.';
                            fixupDirectorySeparator = false;

                            // Continue in this case, potentially writing out '\'.
                        }

                        if (numSpaces > 0 && firstSegment) {
                            // Handle strings like " \\server\share".
                            if (index + 1 < path.Length && 
                                (path[index + 1] == DirectorySeparatorChar || path[index + 1] == AltDirectorySeparatorChar))
                            {
                                newBuffer[newBufferIndex++] = DirectorySeparatorChar;
                            }
                        }
                    }
                    numDots = 0;
                    numSpaces = 0;  // Suppress trailing spaces

                    if (!fixupDirectorySeparator) {
                        fixupDirectorySeparator = true;

                        if (newBufferIndex + 1 >= MaxPath)
                            throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

                        newBuffer[newBufferIndex++] = DirectorySeparatorChar;
                    }
                    numSigChars = 0;
                    lastSigChar = index;
                    startedWithVolumeSeparator = false;
                    firstSegment = false;

#if !PLATFORM_UNIX
                    // For short file names, we must try to expand each of them as
                    // soon as possible.  We need to allow users to specify a file
                    // name that doesn't exist using a path with short file names
                    // in it, such as this for a temp file we're trying to create:
                    // C:\DOCUME~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp
                    // We could try doing this afterwards piece by piece, but it's
                    // probably a lot simpler to do it here.
                    if (mightBeShortFileName) {
                        newBuffer[newBufferIndex] = '\0';
                        TryExpandShortFileName(newBuffer, ref newBufferIndex, MAX_PATH);
                        mightBeShortFileName = false;
                    }
#endif
                } // if (Found directory separator)
                else if (currentChar == '.') {
                    // Reduce only multiple .'s only after slash to 2 dots. For
                    // instance a...b is a valid file name.
                    numDots++;
                    // Don't flush out non-terminal spaces here, because they may in
                    // the end not be significant.  Turn "c:\ . .\foo" -> "c:\foo"
                    // which is the conclusion of removing trailing dots & spaces,
                    // as well as folding multiple '\' characters.
                }
                else if (currentChar == ' ') {
                    numSpaces++;
                }
                else {  // Normal character logic
#if !PLATFORM_UNIX
                    if (currentChar == '~')
                        mightBeShortFileName = true;
#endif

                    fixupDirectorySeparator = false;

#if !PLATFORM_UNIX
                    // To reject strings like "C:...\foo" and "C  :\foo"
                    if (firstSegment && currentChar == VolumeSeparatorChar) {
                        // Only accept "C:", not "c :" or ":"
                        // Get a drive letter or ' ' if index is 0.
                        char driveLetter = (index > 0) ? path[index-1] : ' ';
                        bool validPath = ((numDots == 0) && (numSigChars >= 1) && (driveLetter != ' '));
                        if (!validPath)
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                        startedWithVolumeSeparator = true;
                        // We need special logic to make " c:" work, we should not fix paths like "  foo::$DATA"
                        if (numSigChars > 1) { // Common case, simply do nothing
                            uint spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset.
                            while((spaceCount < newBufferIndex) && newBuffer[spaceCount] == ' ')
                                spaceCount++;
                            if (numSigChars - spaceCount == 1) {
                                newBuffer[0] = driveLetter; // Overwrite spaces, we need a special case to not break "  foo" as a relative path.
                                newBufferIndex=1;
                            }
                        }
                        numSigChars = 0;
                    }
                    else
#endif // !PLATFORM_UNIX
                    {
                        numSigChars += 1 + numDots + numSpaces;
                    }

                    // Copy any spaces & dots since the last significant character
                    // to here.  Note we only counted the number of dots & spaces,
                    // and don't know what order they're in.  Hence the copy.
                    if (numDots > 0 || numSpaces > 0) {
                        int numCharsToCopy = (lastSigChar >= 0) ? index - lastSigChar - 1 : index;
                        if (numCharsToCopy > 0) {
                            path.CopyTo(lastSigChar + 1, newBuffer, newBufferIndex, numCharsToCopy);
                            newBufferIndex += numCharsToCopy;
                        }
                        numDots = 0;
                        numSpaces = 0;
                    }

                    if (newBufferIndex + 1 >= MaxPath)
                        throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                        
                    newBuffer[newBufferIndex++] = currentChar;
                    lastSigChar = index;
                }
                
                index++;
            } // end while

            // Drop any trailing dots and spaces from file & directory names, EXCEPT
            // we MUST make sure that "C:\foo\.." is correctly handled.
            // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\"
            if (numSigChars == 0) {
                if (numDots > 0) {
                    // Look for ".[space]*" or "..[space]*"
                    int start = lastSigChar + 1;
                    if (path[start] != '.')
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                    // Only allow "[dot]+[space]*", and normalize the 
                    // legal ones to "." or ".."
                    if (numDots >= 2) {
                        // Reject "C:..."
                        if (startedWithVolumeSeparator && numDots > 2)
                            throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

                        if (path[start + 1] == '.') {
                            // Search for a space in the middle of the
                            // dots and throw
                            for(int i=start + 2; i < start + numDots; i++) {
                                if (path[i] != '.')
                                    throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            }
                            
                            numDots = 2;
                        }
                        else {
                            if (numDots > 1)
                                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));
                            numDots = 1;
                        }
                    }

                    if (newBufferIndex + numDots >= MaxPath)
                        throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

                    if (numDots == 2) {
                        newBuffer[newBufferIndex++] = '.';
                    }

                    newBuffer[newBufferIndex++] = '.';
                }
            } // if (numSigChars == 0)

            // If we ended up eating all the characters, bail out.
            if (newBufferIndex == 0)
                throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegal"));

            BCLDebug.Assert(newBufferIndex <= MaxPath, "Overflowed temporary path buffer" );
            newBuffer[newBufferIndex] = '\0';

            // Disallow URL's here.  Some of our other Win32 API calls will reject
            // them later, so we might be better off rejecting them here.
            // Note we've probably turned them into "file:\D:\foo.tmp" by now.
            // But for compatibility, ensure that callers that aren't doing a 
            // full check aren't rejected here.
            if (fullCheck && 
                (CharArrayStartsWithOrdinal(newBuffer, newBufferIndex, "http:", false) ||
                 CharArrayStartsWithOrdinal(newBuffer, newBufferIndex, "file:", false)))
                throw new ArgumentException(Environment.GetResourceString("Argument_PathUriFormatNotSupported"));
            
#if !PLATFORM_UNIX
            // If the last part of the path (file or directory name) had a tilde,
            // expand that too.
            if (mightBeShortFileName) {
                TryExpandShortFileName(newBuffer, ref newBufferIndex, MaxPath);
            }
#endif

            // Call the Win32 API to do the final canonicalization step.
            int result = 1;
            char[] pFinal;
            int len;

            if (fullCheck) {
                
                finalBuffer = new char[MaxPath + 1];
                result = Win32Native.GetFullPathName(newBuffer, MaxPath + 1, finalBuffer, IntPtr.Zero);
                
                // If success, the return buffer length does not account for the terminating null character.
                // If failure, the return buffer length does account for the path + the terminating null character.
                if (result > MaxPath) {
                    finalBuffer = new char[result];
                    result = Win32Native.GetFullPathName(newBuffer, result, finalBuffer, IntPtr.Zero);

                    // Fullpath is genuinely long
                    if (result > MaxPath)
                        throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                }

                BCLDebug.Assert(result <= MaxPath, "did we accidently remove a PathTooLongException check?");
                if (result == 0 && newBuffer[0] != '\0') {
                    __Error.WinIOError();
                }
                else if (result < MaxPath)  // May be necessary for empty strings
                    finalBuffer[result] = '\0';
                pFinal = finalBuffer;
                len = result;

#if !PLATFORM_UNIX
                // If we called GetFullPathName with something like "foo" and our
                // command window was in short file name mode (ie, by running edlin or
                // DOS versions of grep, etc), we might have gotten back a short file
                // name.  So, check to see if we need to expand it.
                mightBeShortFileName = false;
                for(uint i=0; i<len && !mightBeShortFileName; i++) {
                    if (finalBuffer[i] == '~')
                        mightBeShortFileName = true;
                }
                if (mightBeShortFileName) {
                    bool r = TryExpandShortFileName(finalBuffer, ref len, MaxPath);
                    if (!r) {
                        int lastSlash = Array.LastIndexOf(finalBuffer, DirectorySeparatorChar, len - 1, len);
                        if (lastSlash >= 0) {
                            BCLDebug.Assert(lastSlash < len, "path unexpectedly ended in a '\'");
                            char[] savedName = new char[len - lastSlash - 1];
                            Array.Copy(finalBuffer, lastSlash + 1, savedName, 0, len - lastSlash - 1);
                            finalBuffer[lastSlash] = '\0';
                            r = TryExpandShortFileName(finalBuffer, ref lastSlash, MaxPath);
                            
                            // Clean up changes made to the finalBuffer.
                            finalBuffer[lastSlash] = DirectorySeparatorChar;
                            
                            Array.Copy(savedName, 0, finalBuffer, lastSlash + 1, savedName.Length);
                            if (r)
                                len = lastSlash + 1 + savedName.Length;
                        }
                    }
                }
#endif
            }
            else {
                pFinal = newBuffer;
                len = newBufferIndex;
            }

            if (result != 0) {
                /* Throw an ArgumentException for paths like \\, \\server, \\server\
                   This check can only be properly done after normalizing, so
                   \\foo\.. will be properly rejected.  Also, reject \\?\GLOBALROOT\
                   (an internal kernel path) because it provides aliases for drives. */
                if (pFinal[0] == '\\' && pFinal[1] == '\\') {
                    int startIndex = 2;
                    while (startIndex < result) {
                        if (pFinal[startIndex] == '\\') {
                            startIndex++;
                            break;
                        }
                        else {
                            startIndex++;
                        }
                    }
                    if (startIndex == result)
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathIllegalUNC"));

                    // Check for \\?\Globalroot, an internal mechanism to the kernel
                    // that provides aliases for drives and other undocumented stuff.
                    // The kernel team won't even describe the full set of what
                    // is available here - we don't want managed apps mucking 
                    // with this for security reasons.
                    if (CharArrayStartsWithOrdinal(pFinal, len, "\\\\?\\globalroot", true))
                        throw new ArgumentException(Environment.GetResourceString("Arg_PathGlobalRoot"));
                }
            }

            // Check our result and form the managed string as necessary.
            
            if (len >= MaxPath)
                throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));

            if (result == 0) {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode == 0)
                    errorCode = Win32Native.ERROR_BAD_PATHNAME;
                __Error.WinIOError(errorCode, path);
                return null;  // Unreachable - silence a compiler error.
            }

            return new String(pFinal, 0, len);
        }
Example #35
0
        public static void Log(string log)
        {
            if (GameLog._LogLabel == null)
            {
                return;
            }

            GameLog._LogLabel.text = String.Empty;

            //make an empty string to copy over the old array
            string[] tempString = new String[GameLog._LogLines];
            for (int i = 1; i < GameLog._LogLines; ++i)
            {
                //copy second line to first
                tempString [i - 1] = GameLog._LogText [i];
            }

            tempString [GameLog._LogLines - 1] = line++.ToString() + ") " + log + "\n";
            tempString.CopyTo(GameLog._LogText, 0);
            String temp = String.Empty;
            for (int i = 0; i < GameLog._LogLines; ++i)
            {
                temp += tempString [i];
            }

            GameLog._LogLabel.text = temp;
        }
Example #36
0
 // This method is more efficient for long strings outputted to streams
 // than the one on TextWriter, and won't cause any problems in terms of 
 // hiding methods on TextWriter as long as languages respect the 
 // hide-by-name-and-sig metadata flag.
 public override void WriteLine(String value) { 
     if (value != null) {
         int count = value.Length;
         int index = 0;
         while (count > 0) { 
             if (charPos == charLen) Flush(false);
             int n = charLen - charPos; 
             if (n > count) n = count; 
             Contract.Assert(n > 0, "StreamWriter::WriteLine(String) isn't making progress!  This is most likely a race condition in user code.");
             value.CopyTo(index, charBuffer, charPos, n); 
             charPos += n;
             index += n;
             count -= n;
         } 
     }
     if (charPos >= charLen - 2) Flush(false); 
     Buffer.InternalBlockCopy(CoreNewLine, 0, charBuffer, charPos*2, CoreNewLine.Length * 2); 
     charPos += CoreNewLine.Length;
     if (autoFlush) Flush(true, false); 
 }