Esempio n. 1
0
    public static void Main( string[] args )
    {
        StringBuilder buffer =
         new StringBuilder( "Hello, how are you?" );

          // use Length and Capacity properties
          Console.WriteLine( "buffer = " + buffer +
         "\nLength = " + buffer.Length +
         "\nCapacity = " + buffer.Capacity );

          buffer.EnsureCapacity( 75 ); // ensure a capacity of at least 75
          Console.WriteLine( "\nNew capacity = " +
         buffer.Capacity );

          // truncate StringBuilder by setting Length property
          buffer.Length = 10;
          Console.Write( "\nNew length = " +
         buffer.Length + "\nbuffer = " );

          // use StringBuilder indexer
          for ( int i = 0; i < buffer.Length; i++ )
         Console.Write( buffer[ i ] );

          Console.WriteLine( "\n" );
    }
	static string[] LoadRenderModelNames()
	{
		var results = new List<string>();
		results.Add("None");

		using (var holder = new SteamVR_RenderModel.RenderModelInterfaceHolder())
		{
			var renderModels = holder.instance;
			if (renderModels != null)
			{
				uint count = renderModels.GetRenderModelCount();
				for (uint i = 0; i < count; i++)
				{
					var buffer = new StringBuilder();
					var requiredSize = renderModels.GetRenderModelName(i, buffer, 0);
					if (requiredSize == 0)
						continue;

					buffer.EnsureCapacity((int)requiredSize);
					renderModels.GetRenderModelName(i, buffer, requiredSize);
					results.Add(buffer.ToString());
				}
			}
		}

		return results.ToArray();
	}
Esempio n. 3
0
        internal static string GetOidValue(IntPtr asn1ObjectPtr)
        {
            // OBJ_obj2txt returns the number of bytes that should have been in the answer, but it does not accept
            // a NULL buffer.  The documentation says "A buffer length of 80 should be more than enough to handle
            // any OID encountered in practice", so start with a buffer of size 80, and try again if required.
            StringBuilder buf = new StringBuilder(80);

            int bytesNeeded = ObjObj2Txt(buf, buf.Capacity, asn1ObjectPtr);

            if (bytesNeeded < 0)
            {
                throw CreateOpenSslCryptographicException();
            }

            Debug.Assert(bytesNeeded != 0, "OBJ_obj2txt reported a zero-length response");

            if (bytesNeeded >= buf.Capacity)
            {
                int initialBytesNeeded = bytesNeeded;

                // bytesNeeded does not count the \0 which will be written on the end (based on OpenSSL 1.0.1f),
                // so make sure to leave room for it.
                buf.EnsureCapacity(bytesNeeded + 1);

                bytesNeeded = ObjObj2Txt(buf, buf.Capacity, asn1ObjectPtr);

                if (bytesNeeded < 0)
                {
                    throw CreateOpenSslCryptographicException();
                }

                Debug.Assert(
                    bytesNeeded == initialBytesNeeded,
                    "OBJ_obj2txt changed the required number of bytes for the realloc call");

                if (bytesNeeded >= buf.Capacity)
                {
                    // OBJ_obj2txt is demanding yet more memory
                    throw new CryptographicException();
                }
            }

            return buf.ToString();
        }
        protected virtual void Decode(Asn1BerDecodeBuffer buffer, bool explicitTagging, int implicitLength, Asn1Tag tag)
        {
            int num2;
            var elemLength = explicitTagging ? MatchTag(buffer, tag) : implicitLength;
            var num3       = elemLength;
            var num4       = 0;

            if (StringBuffer == null)
            {
                StringBuffer = new StringBuilder();
            }

            var lastTag = buffer.LastTag;

            if ((lastTag == null) || !lastTag.Constructed)
            {
                if (num3 < 0)
                {
                    throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidLengthException);
                }

                StringBuffer.Length = num3;

                while (num3 > 0)
                {
                    num2 = buffer.Read();

                    if (num2 == -1)
                    {
                        throw ExceptionUtility.CryptographicException(Resources.Asn1EndOfBufferException, buffer.ByteCount);
                    }

                    StringBuffer[num4++] = (char)num2;
                    num3--;
                }
            }
            else
            {
                var capacity = 0;
                var context  = new Asn1BerDecodeContext(buffer, elemLength);

                while (!context.Expired())
                {
                    var num5 = MatchTag(buffer, Asn1OctetString.Tag);

                    if (num5 <= 0)
                    {
                        throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidFormatOfConstructedValue, buffer.ByteCount);
                    }

                    capacity += num5;
                    StringBuffer.EnsureCapacity(capacity);

                    while (num5 > 0)
                    {
                        num2 = buffer.Read();

                        if (num2 == -1)
                        {
                            throw ExceptionUtility.CryptographicException(Resources.Asn1EndOfBufferException, buffer.ByteCount);
                        }

                        StringBuffer.Append((char)num2);
                        num5--;
                    }
                }

                if (elemLength == Asn1Status.IndefiniteLength)
                {
                    MatchTag(buffer, Asn1Tag.Eoc);
                }
            }

            Value           = StringBuffer.ToString();
            buffer.TypeCode = (short)tag.IdCode;
        }
Esempio n. 5
0
        private string Encode(string uriString, HashSet <char> unescapedUriSet)
        {
            var strLen = uriString.Length;

            _stringBuilder.EnsureCapacity(uriString.Length);
            _stringBuilder.Clear();

            for (var k = 0; k < strLen; k++)
            {
                var c = uriString[k];
                if (unescapedUriSet != null && unescapedUriSet.Contains(c))
                {
                    _stringBuilder.Append(c);
                }
                else
                {
                    if (c >= 0xDC00 && c <= 0xDBFF)
                    {
                        ExceptionHelper.ThrowUriError(_engine);
                    }

                    int v;
                    if (c < 0xD800 || c > 0xDBFF)
                    {
                        v = c;
                    }
                    else
                    {
                        k++;
                        if (k == strLen)
                        {
                            ExceptionHelper.ThrowUriError(_engine);
                        }

                        var kChar = (int)uriString[k];
                        if (kChar < 0xDC00 || kChar > 0xDFFF)
                        {
                            ExceptionHelper.ThrowUriError(_engine);
                        }

                        v = (c - 0xD800) * 0x400 + (kChar - 0xDC00) + 0x10000;
                    }

                    byte[] octets = System.ArrayExt.Empty <byte>();

                    if (v >= 0 && v <= 0x007F)
                    {
                        // 00000000 0zzzzzzz -> 0zzzzzzz
                        octets = new[] { (byte)v };
                    }
                    else if (v <= 0x07FF)
                    {
                        // 00000yyy yyzzzzzz ->	110yyyyy ; 10zzzzzz
                        octets = new[]
                        {
                            (byte)(0xC0 | (v >> 6)),
                            (byte)(0x80 | (v & 0x3F))
                        };
                    }
                    else if (v <= 0xD7FF)
                    {
                        // xxxxyyyy yyzzzzzz -> 1110xxxx; 10yyyyyy; 10zzzzzz
                        octets = new[]
                        {
                            (byte)(0xE0 | (v >> 12)),
                            (byte)(0x80 | ((v >> 6) & 0x3F)),
                            (byte)(0x80 | (v & 0x3F))
                        };
                    }
                    else if (v <= 0xDFFF)
                    {
                        ExceptionHelper.ThrowUriError(_engine);
                    }
                    else if (v <= 0xFFFF)
                    {
                        octets = new[]
                        {
                            (byte)(0xE0 | (v >> 12)),
                            (byte)(0x80 | ((v >> 6) & 0x3F)),
                            (byte)(0x80 | (v & 0x3F))
                        };
                    }
                    else
                    {
                        octets = new[]
                        {
                            (byte)(0xF0 | (v >> 18)),
                            (byte)(0x80 | (v >> 12 & 0x3F)),
                            (byte)(0x80 | (v >> 6 & 0x3F)),
                            (byte)(0x80 | (v >> 0 & 0x3F))
                        };
                    }

                    for (var j = 0; j < octets.Length; j++)
                    {
                        var jOctet = octets[j];
                        var x1     = HexaMap[jOctet / 16];
                        var x2     = HexaMap[jOctet % 16];
                        _stringBuilder.Append('%').Append(x1).Append(x2);
                    }
                }
            }

            return(_stringBuilder.ToString());
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            Console.WriteLine("----[ Задание #1 ] ----------------------------------------------------------------------");

            // Задание 1
            string str = "test";

            Console.WriteLine("Первый символ: {0}", str[0]);

            string str2 = new string('s', 5);

            char[] chararray = { 't', 'e', 's', 't' };
            string str3      = new string(chararray);

            Console.WriteLine("str= " + str + " str2= " + str2 + " str3= " + str3);

            // 3.   Протестируйте на созданных строках простейшие операции:
            str3 = "123";
            Console.WriteLine("str3= " + str3);
            Console.WriteLine("str3 == str2 - " + (str3 == str2) + "\nstr != str3 -  " + (str != str3) + "\nstr + str3 -  " + (str + str3));


            // 4.  Используя индексацию строк, выполните следующие задания:

            string str4 = "fjhj/* Это комментарий */";

            System.Text.StringBuilder temp = new System.Text.StringBuilder(100);
            int i = 0;
            int j = 0;

            while (i < str4.Length - 1)
            {
                if (str4[i] == '/' && str4[i + 1] == '*')
                {
                    i += 2;

                    while (!(str4[i] == '*' && str4[i + 1] == '/'))
                    {
                        temp.Insert(j, str4[i]);
                        Console.WriteLine("str4[i]= " + str4[i]);
                        i++;
                        j++;
                    }
                    break; //если ищется только один комментарий в строке
                }
                else
                {
                    i++;
                }

                string res = temp.ToString();
                Console.WriteLine(res);
            }

            // скопировать в новую строку все символы другой строки за исключением слова “student”;
            string str5 = "скопировать в новую строку все символы другой строки за исключением слова “student”;";

            if (str5.Contains("student"))
            {
                str5 = str5.Replace("student", "");
            }
            Console.WriteLine("str5= " + str5);

            Console.WriteLine("----[ end! Задание #1 ] -----------------------------------------------------------------\n\n");


            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

            Console.WriteLine("----[ Задание #2 ] ----------------------------------------------------------------------");


            // Задание 2

            Console.WriteLine("Введите число ");
            ulong digit = ulong.Parse(Console.ReadLine());

            Console.WriteLine(NumByWords.RurPhrase(digit));


            Console.WriteLine("----[ end! Задание #2 ] -----------------------------------------------------------------\n\n");


            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

            Console.WriteLine("----[ Задание #3 ] ----------------------------------------------------------------------");


            // Задание 3
            string str6 = "Как правило, строка delimiters состоит из одного символа, который и разделяет в результирующей строке элементы массива items; но в отдельных случаях ограничителем может быть строка из нескольких символов.";

            Console.WriteLine("\nИсходная строка:\n" + str6 + "\nПолученный массив :\n" + SplitJoin(str6));


            Console.WriteLine("----[ end! Задание #3 ] -----------------------------------------------------------------\n\n");


            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

            Console.WriteLine("----[ Задание #4 ] ----------------------------------------------------------------------");

            // Задание 4

            StringBuilder str7 = new StringBuilder("String – example of StringBuilder");
            StringBuilder str8 = new StringBuilder("String – example of StringBuilder2");

            Console.WriteLine("\n1 строка:\n" + str7 + "\n2 строка:\n" + str8);

            str7.Replace("String", "Text");
            Console.WriteLine("\n1 строка: Replace\n" + str7);
            str8.Append("dadwadawda");
            Console.WriteLine("\n2 строка: Append\n" + str8);
            str7.Insert(0, str8);
            Console.WriteLine("\n1 строка Insert:\n" + str7);
            str8.Remove(5, 5);
            Console.WriteLine("\n2 строка: Remove\n" + str8);


            string[] Words;
            // получим массив слов
            Words = str6.Split(' ');
            // очистим переменную
            str8.Remove(0, str8.Length);
            // соберем строку
            int num = 1;

            foreach (string word in Words)
            {
                str8.AppendFormat(" {0}: {1} ", num++, word);
            }
            Console.WriteLine("\n2 строка: AppendFormat\n" + str8);


            Console.WriteLine("----[ end! Задание #4 ] -----------------------------------------------------------------\n\n");

            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

            Console.WriteLine("----[ Задание #5 ] ----------------------------------------------------------------------");


            // Задание 5

            Console.WriteLine("\n2 строка: Capacity = " + str8.Capacity);
            Console.WriteLine("\n2 строка: MaxCapacity = " + str8.MaxCapacity);
            str8.EnsureCapacity(580);
            Console.WriteLine("\n2 строка: Capacity = " + str8.Capacity);


            Console.WriteLine("----[ end! Задание #5 ] -----------------------------------------------------------------\n\n");


            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

            Console.WriteLine("----[ Задание #6 ] ----------------------------------------------------------------------");


            // Задание 6

            // 6.2
            // char[] str10 = string.ToCharArray( "Hello, World!");
            string str11 = "Hello, World!";

            char[] str10 = str11.ToCharArray();
            string str9  = "Здравствуй, Мир!";

            // 6.3
            //Console.WriteLine("\nchar[]: " + str10);
            PrintCharAr(str10);
            PrintCharAr(str9.ToCharArray());

            // 6.4
            string str12 = CharArrayToString(str10);

            Console.WriteLine("\nstr12 строка: " + str12);

            // 6.5
            char[] str13 = new char[1];
            str13[0] = 'l';
            Console.WriteLine("\nIndexOfStr " + IndexOfStr(str10, str13));

            // 6.6
            TestIndexSym();
            /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */


            Console.ReadLine();

            Console.WriteLine("----[ end! Задание #6 ] -----------------------------------------------------------------\n\n");
        }
            // return true if is done
            public bool DoJob()
            {
                if (m_isDone)
                {
                    return(true);
                }

                if (!s_renderModelsCache.ContainsKey(m_name))
                {
                    var vrRenderModels = OpenVR.RenderModels;
                    if (vrRenderModels == null)
                    {
                        DoComplete(); return(true);
                    }

                    if (m_unreadyRM == null)
                    {
                        var childCount = (int)vrRenderModels.GetComponentCount(m_name);
                        if (childCount > 0)
                        {
                            var childCompNames  = new string[childCount];
                            var childModelNames = new string[childCount];
                            var strBuilder      = new StringBuilder(16);

                            for (int iChild = 0; iChild < childCount; ++iChild)
                            {
                                var strCap = vrRenderModels.GetComponentName(m_name, (uint)iChild, null, 0);
                                if (strCap == 0)
                                {
                                    continue;
                                }
                                strBuilder.Length = 0;
                                strBuilder.EnsureCapacity((int)strCap);
                                if (vrRenderModels.GetComponentName(m_name, (uint)iChild, strBuilder, strCap) == 0)
                                {
                                    continue;
                                }
                                childCompNames[iChild] = strBuilder.ToString();
                                if (s_verbose)
                                {
                                    Debug.Log("[" + m_jobID + "]+0 GetComponentName " + m_name + "[" + iChild + "]=" + childCompNames[iChild]);
                                }

                                strCap = vrRenderModels.GetComponentRenderModelName(m_name, childCompNames[iChild], null, 0);
                                if (strCap == 0)
                                {
                                    continue;
                                }
                                strBuilder.Length = 0;
                                strBuilder.EnsureCapacity((int)strCap);
                                if (vrRenderModels.GetComponentRenderModelName(m_name, childCompNames[iChild], strBuilder, strCap) == 0)
                                {
                                    continue;
                                }
                                childModelNames[iChild] = strBuilder.ToString();
                                if (s_verbose)
                                {
                                    Debug.Log("[" + m_jobID + "]+0 GetComponentRenderModelName " + m_name + "[" + childCompNames[iChild] + "]=" + System.IO.Path.GetFileName(childModelNames[iChild]));
                                }
                            }

                            m_unreadyRM = new RenderModel()
                            {
                                name            = m_name,
                                childCompNames  = childCompNames,
                                childModelNames = childModelNames,
                                childCount      = childCount,
                                textures        = new Dictionary <int, Texture2D>(),
                            };

                            m_loadedChildPtrs = new PtrPack[childCount];
                        }
                        else
                        {
                            m_unreadyRM = new RenderModel()
                            {
                                name     = m_name,
                                textures = new Dictionary <int, Texture2D>(),
                            };
                        }

                        m_startFrame = Time.frameCount;
                    }

                    if (m_unreadyRM.childCount == 0)
                    {
                        if (!DoLoadModelJob(vrRenderModels, m_name, m_unreadyRM.textures, ref m_loadedPtr.model, ref m_loadedPtr.texture, ref m_loadedPtr.textureD3D11))
                        {
                            return(false);
                        }

                        if (m_loadedPtr.texture != IntPtr.Zero)
                        {
                            vrRenderModels.FreeTexture(m_loadedPtr.texture);
                        }
                        if (m_loadedPtr.model != IntPtr.Zero)
                        {
                            vrRenderModels.FreeRenderModel(m_loadedPtr.model);
                        }
                    }
                    else
                    {
                        var loadChildModelsDone = true;
                        for (int i = 0, imax = m_unreadyRM.childCount; i < imax; ++i)
                        {
                            loadChildModelsDone = DoLoadModelJob(vrRenderModels, m_unreadyRM.childModelNames[i], m_unreadyRM.textures, ref m_loadedChildPtrs[i].model, ref m_loadedChildPtrs[i].texture, ref m_loadedChildPtrs[i].textureD3D11) && loadChildModelsDone;
                        }

                        if (!loadChildModelsDone)
                        {
                            return(false);
                        }

                        foreach (var ptrPack in m_loadedChildPtrs)
                        {
                            if (ptrPack.texture != IntPtr.Zero)
                            {
                                vrRenderModels.FreeTexture(ptrPack.texture);
                            }
                            if (ptrPack.model != IntPtr.Zero)
                            {
                                vrRenderModels.FreeRenderModel(ptrPack.model);
                            }
                        }
                    }

                    s_renderModelsCache.Add(m_name, m_unreadyRM);
                }

                DoComplete();
                return(true);
            }
        /* A good summary of the code used to process arguments in most windows programs can be found at :
         * http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINARGV
         */
        static void AppendEscaped(StringBuilder builder, string arg)
        {
            builder.EnsureCapacity(builder.Length + arg.Length);

            if (arg == "")
            {
                builder.Append(@"""""");
                return;
            }

            var needQuote = false;
            var containsQuoteOrBackslash = false;

            foreach (var c in arg)
            {
                needQuote |= (c == ' ');
                needQuote |= (c == '\t');
                containsQuoteOrBackslash |= (c == '"');
                containsQuoteOrBackslash |= (c == '\\');
            }

            if (needQuote)
            {
                builder.Append('"');
            }
            else if (!containsQuoteOrBackslash)
            {
                // No special characters are present, early exit
                builder.Append(arg);
                return;
            }

            var index       = 0;
            var backslashes = 0;

            while (index < arg.Length)
            {
                var c = arg[index];
                if (c == '\\')
                {
                    backslashes++;
                }
                else if (c == '"')
                {
                    AddBackslashes(builder, backslashes, true);
                    backslashes = 0;
                    builder.Append('\\');
                    builder.Append(c);
                }
                else
                {
                    AddBackslashes(builder, backslashes, false);
                    backslashes = 0;
                    builder.Append(c);
                }
                index += 1;
            }

            AddBackslashes(builder, backslashes, needQuote);

            if (needQuote)
            {
                builder.Append('"');
            }
        }
Esempio n. 9
0
        public static Identity FindByName(string name)
        {
            byte[]       rawSid = null;
            uint         cbSid  = 0;
            var          referencedDomainName    = new StringBuilder();
            var          cchReferencedDomainName = (uint)referencedDomainName.Capacity;
            IdentityType sidUse;

            if (name.StartsWith(".\\"))
            {
                var username = name.Substring(2);
                name = string.Format("{0}\\{1}", Environment.MachineName, username);
                var identity = FindByName(name);
                if (identity == null)
                {
                    name     = string.Format("BUILTIN\\{0}", username);
                    identity = FindByName(name);
                }
                return(identity);
            }

            if (name.Equals("LocalSystem", StringComparison.InvariantCultureIgnoreCase))
            {
                name = "NT AUTHORITY\\SYSTEM";
            }

            if (LookupAccountName(null, name, rawSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))
            {
                throw new Win32Exception();
            }

            var err = Marshal.GetLastWin32Error();

            if (err == Win32ErrorCodes.InsufficientBuffer || err == Win32ErrorCodes.InvalidFlags)
            {
                rawSid = new byte[cbSid];
                referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                if (!LookupAccountName(null, name, rawSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                {
                    throw new Win32Exception();
                }
            }
            else if (err == Win32ErrorCodes.NoneMapped)
            {
                // Couldn't find the account.
                return(null);
            }
            else
            {
                throw new Win32Exception();
            }

            IntPtr ptrSid;

            if (!ConvertSidToStringSid(rawSid, out ptrSid))
            {
                throw new Win32Exception();
            }

            var sid = new SecurityIdentifier(rawSid, 0);

            LocalFree(ptrSid);
            var ntAccount   = sid.Translate(typeof(NTAccount));
            var domainName  = referencedDomainName.ToString();
            var accountName = ntAccount.Value;

            if (!string.IsNullOrEmpty(domainName))
            {
                var domainPrefix = string.Format("{0}\\", domainName);
                if (accountName.StartsWith(domainPrefix))
                {
                    accountName = accountName.Replace(domainPrefix, "");
                }
            }
            return(new Identity(domainName, accountName, sid, sidUse));
        }
Esempio n. 10
0
        /// <summary>
        ///   Quotes a string</summary>
        /// <param name="s">
        ///   String</param>
        /// <param name="sb">
        ///   StringBuilder</param>
        /// <param name="doubleQuote">
        ///   True to use double quotes</param>
        public static void QuoteString(string s, StringBuilder sb, bool doubleQuote)
        {
            if (String.IsNullOrEmpty(s))
            {
                if (doubleQuote)
                {
                    sb.Append(emptyDoubleQuote);
                }
                else
                {
                    sb.Append(emptySingleQuote);
                }
                return;
            }

            char c;
            int  len = s.Length;

            sb.EnsureCapacity(sb.Length + (s.Length * 2));

            char quoteChar = doubleQuote ? '"' : '\'';

            sb.Append(quoteChar);

            for (int i = 0; i < len; i++)
            {
                c = s[i];

                switch (c)
                {
                case '\r':
                    sb.Append(@"\r");
                    break;

                case '\n':
                    sb.Append(@"\n");
                    break;

                case '\t':
                    sb.Append(@"\t");
                    break;

                case '\'':
                    if (!doubleQuote)
                    {
                        sb.Append(@"\'");     // IE doesn't understand \' in double quoted strings!!!
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;

                case '\"':
                    if (doubleQuote)     // IE doesn't understand \" in single quoted strings!!!
                    {
                        sb.Append(@"\""");
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;

                case '\\':
                    sb.Append(@"\\");
                    break;

                case '/':
                    sb.Append(@"\/");
                    break;

                default:
                    if (c < ' ')
                    {
                        sb.Append(@"\u");
                        sb.Append(((int)c).ToString("X4"));
                    }
                    else
                    {
                        sb.Append(c);
                    }
                    break;
                }
            }

            sb.Append(quoteChar);
        }
Esempio n. 11
0
        ////////////////////////////////////////////////////////////////////////////////
        // Prints the tokens privileges
        ////////////////////////////////////////////////////////////////////////////////
        public static void EnumerateTokenPrivileges(IntPtr hToken)
        {
            ////////////////////////////////////////////////////////////////////////////////
            Console.WriteLine("[*] Enumerating Token Privileges");
            advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out UInt32 TokenInfLength);

            if (TokenInfLength < 0 || TokenInfLength > Int32.MaxValue)
            {
                GetWin32Error("GetTokenInformation - 1 " + TokenInfLength);
                return;
            }
            Console.WriteLine("[*] GetTokenInformation - Pass 1");
            IntPtr lpTokenInformation = Marshal.AllocHGlobal((Int32)TokenInfLength);

            ////////////////////////////////////////////////////////////////////////////////
            if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength))
            {
                GetWin32Error("GetTokenInformation - 2 " + TokenInfLength);
                return;
            }
            Console.WriteLine("[*] GetTokenInformation - Pass 2");
            Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY));
            Marshal.FreeHGlobal(lpTokenInformation);
            Console.WriteLine("[+] Enumerated {0} Privileges", tokenPrivileges.PrivilegeCount);
            Console.WriteLine();
            Console.WriteLine("{0,-45}{1,-30}", "Privilege Name", "Enabled");
            Console.WriteLine("{0,-45}{1,-30}", "--------------", "-------");
            ////////////////////////////////////////////////////////////////////////////////
            for (Int32 i = 0; i < tokenPrivileges.PrivilegeCount; i++)
            {
                StringBuilder lpName  = new StringBuilder();
                Int32         cchName = 0;
                IntPtr        lpLuid  = Marshal.AllocHGlobal(Marshal.SizeOf(tokenPrivileges.Privileges[i]));
                Marshal.StructureToPtr(tokenPrivileges.Privileges[i].Luid, lpLuid, true);

                advapi32.LookupPrivilegeName(null, lpLuid, null, ref cchName);
                if (cchName <= 0 || cchName > Int32.MaxValue)
                {
                    GetWin32Error("LookupPrivilegeName Pass 1");
                    Marshal.FreeHGlobal(lpLuid);
                    continue;
                }

                lpName.EnsureCapacity(cchName + 1);
                if (!advapi32.LookupPrivilegeName(null, lpLuid, lpName, ref cchName))
                {
                    GetWin32Error("LookupPrivilegeName Pass 2");
                    Marshal.FreeHGlobal(lpLuid);
                    continue;
                }

                Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET
                {
                    PrivilegeCount = 1,
                    Control        = Winnt.PRIVILEGE_SET_ALL_NECESSARY,
                    Privilege      = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] }
                };

                if (!advapi32.PrivilegeCheck(hToken, privilegeSet, out IntPtr pfResult))
                {
                    GetWin32Error("PrivilegeCheck");
                    Marshal.FreeHGlobal(lpLuid);
                    continue;
                }
                Console.WriteLine("{0,-45}{1,-30}", lpName.ToString(), Convert.ToBoolean(pfResult.ToInt32()));
                Marshal.FreeHGlobal(lpLuid);
            }
            Console.WriteLine();
        }
Esempio n. 12
0
File: JSON.cs Progetto: lulzzz/sito
        private static string stringifyImpl(string key, JSValue obj, Function replacer, HashSet <string> keys, string space, HashSet <JSValue> processed, Arguments args)
        {
            if (replacer != null)
            {
                args[0]         = "";
                args[0]._oValue = key;
                args[1]         = obj;
                args.length     = 2;
                var t = replacer.Call(args);
                if (t._valueType >= JSValueType.Object && t._oValue == null)
                {
                    return("null");
                }
                if (t._valueType <= JSValueType.Undefined)
                {
                    return(null);
                }
                obj = t;
            }

            obj = obj.Value as JSValue ?? obj;

            if (processed.Contains(obj))
            {
                ExceptionHelper.Throw(new TypeError("Unable to convert circular structure to JSON."));
            }
            processed.Add(obj);

            try
            {
                StringBuilder result      = null;
                string        stringValue = null;
                if (obj._valueType < JSValueType.Object)
                {
                    if (obj._valueType <= JSValueType.Undefined)
                    {
                        return(null);
                    }

                    if (obj._valueType == JSValueType.String)
                    {
                        result      = new StringBuilder("\"");
                        stringValue = obj.ToString();
                        for (var i = 0; i < stringValue.Length; i++)
                        {
                            escapeIfNeed(result, stringValue[i]);
                        }
                        result.Append('"');
                        return(result.ToString());
                    }

                    if (obj.ValueType == JSValueType.Double && double.IsNaN(obj._dValue) || double.IsInfinity(obj._dValue))
                    {
                        return("null");
                    }

                    return(obj.ToString());
                }

                if (obj.Value == null)
                {
                    return(null);
                }
                if (obj._valueType == JSValueType.Function)
                {
                    return(null);
                }

                var toJSONmemb = obj["toJSON"];
                toJSONmemb = toJSONmemb.Value as JSValue ?? toJSONmemb;
                if (toJSONmemb._valueType == JSValueType.Function)
                {
                    return(stringifyImpl("", (toJSONmemb._oValue as Function).Call(obj, null), null, null, space, processed, null));
                }

                if (obj._valueType >= JSValueType.Object && !typeof(JSValue).GetTypeInfo().IsAssignableFrom(obj.Value.GetType().GetTypeInfo()))
                {
                    var currentContext = Context.CurrentGlobalContext;
                    if (currentContext != null)
                    {
                        var value      = obj.Value;
                        var serializer = currentContext.JsonSerializersRegistry?.GetSuitableJsonSerializer(value);
                        if (serializer != null)
                        {
                            return(serializer.Serialize(key, value, replacer, keys, space, processed));
                        }
                    }
                }

                result = new StringBuilder(obj is Array ? "[" : "{");

                string prevKey = null;
                foreach (var member in obj)
                {
                    if (keys != null && !keys.Contains(member.Key))
                    {
                        continue;
                    }

                    var value = member.Value;
                    value = value.Value as JSValue ?? value;
                    if (value._valueType < JSValueType.Undefined)
                    {
                        continue;
                    }

                    value       = Tools.InvokeGetter(value, obj);
                    stringValue = stringifyImpl(member.Key, value, replacer, null, space, processed, args);

                    if (stringValue == null)
                    {
                        if (obj is Array)
                        {
                            stringValue = "null";
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (prevKey != null)
                    {
                        result.Append(",");
                    }

                    if (space != null)
                    {
                        result.Append(Environment.NewLine)
                        .Append(space);
                    }

                    if (result[0] == '[')
                    {
                        int curentIndex;
                        if (int.TryParse(member.Key, out curentIndex))
                        {
                            var prevIndex = int.Parse(prevKey ?? "-1");

                            var capacity = result.Length + ((space != null ? space.Length : 0) + "null,".Length) * (curentIndex - prevIndex);
                            if (capacity > result.Length) // Может произойти переполнение
                            {
                                result.EnsureCapacity(capacity);
                            }

                            for (var i = curentIndex - 1; i-- > prevIndex;)
                            {
                                result.Append(space)
                                .Append("null,");
                            }

                            result.Append(space)
                            .Append(stringValue);

                            prevKey = member.Key;
                        }
                    }
                    else
                    {
                        result.Append('"');
                        for (var i = 0; i < member.Key.Length; i++)
                        {
                            escapeIfNeed(result, member.Key[i]);
                        }

                        result.Append("\":")
                        .Append(space ?? "");

                        for (var i = 0; i < stringValue.Length; i++)
                        {
                            result.Append(stringValue[i]);
                            if (i >= Environment.NewLine.Length && stringValue.IndexOf(Environment.NewLine, i - 1, Environment.NewLine.Length) != -1)
                            {
                                result.Append(space);
                            }
                        }

                        prevKey = member.Key;
                    }
                }

                if (prevKey != null && space != null)
                {
                    result.Append(Environment.NewLine);
                }

                return(result.Append(obj is Array ? "]" : "}").ToString());
            }
            finally
            {
                processed.Remove(obj);
            }
        }
Esempio n. 13
0
        public static AccessTokenPrimaryGroup FromTokenHandle(AccessTokenHandle handle)
        {
            uint tokenInfLength = 0;
            bool success;

            IntPtr hToken = handle.GetHandle();

            success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrimaryGroup, IntPtr.Zero, tokenInfLength, out tokenInfLength);
            IntPtr tokenInfo = Marshal.AllocHGlobal(Convert.ToInt32(tokenInfLength));

            success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrimaryGroup, tokenInfo, tokenInfLength, out tokenInfLength);

            if (success)
            {
                // Same struct as the token owner, so lets just reuse it.
                TOKEN_OWNER tokenOwner = (TOKEN_OWNER)Marshal.PtrToStructure(tokenInfo, typeof(TOKEN_OWNER));
                IntPtr      sidPtr     = tokenOwner.Owner;
                int         sidLength  = Convert.ToInt32(Advapi32.GetLengthSid(tokenOwner.Owner));
                byte[]      sid        = new byte[sidLength];
                Marshal.Copy(tokenOwner.Owner, sid, 0, sidLength);
                StringBuilder lpname    = new StringBuilder();
                uint          cchname   = (uint)lpname.Capacity;
                StringBuilder lpdomain  = new StringBuilder();
                uint          cchdomain = (uint)lpdomain.Capacity;
                SID_NAME_USE  peUse;
                var           name   = "";
                var           domain = "";
                if (!Advapi32.LookupAccountSid(null, sid, lpname, ref cchname, lpdomain, ref cchdomain, out peUse))
                {
                    var err = Kernel32.GetLastError();
                    if (err == Constants.ERROR_INSUFFICIENT_BUFFER)
                    {
                        lpname.EnsureCapacity((int)cchname);
                        lpdomain.EnsureCapacity((int)cchdomain);
                        if (!Advapi32.LookupAccountSid(null, sid, lpname, ref cchname, lpdomain, ref cchdomain, out peUse))
                        {
                            Logger.GetInstance().Error($"Failed to lookup owner SID. LookupAccountSid failed with error: {Kernel32.GetLastError()}");
                            throw new TokenInformationException();
                        }
                        else
                        {
                            name   = lpname.ToString();
                            domain = lpdomain.ToString();
                        }
                    }
                    else
                    {
                        Logger.GetInstance().Error($"Failed to lookup owner SID. LookupAccountSid failed with error: {err}");
                        throw new TokenInformationException();
                    }
                }
                else
                {
                    name   = lpname.ToString();
                    domain = lpdomain.ToString();
                }

                Marshal.FreeHGlobal(tokenInfo);
                return(new AccessTokenPrimaryGroup(name, domain, sidPtr, peUse));
            }
            else
            {
                Marshal.FreeHGlobal(tokenInfo);
                Logger.GetInstance().Error($"Failed to retreive session id information for access token. GetTokenInformation failed with error: {Kernel32.GetLastError()}");
                throw new TokenInformationException();
            }
        }
Esempio n. 14
0
        private List <string> FieldParser(string source)
        {
            List <string>   fields = new List <string>();
            FieldParseState state  = FieldParseState.Init;

            _fieldBuffer.Clear();
            _fieldBuffer.EnsureCapacity(source.Length);
            for (int i = 0; i < source.Length; i++)
            {
                char c = source[i];
                switch (state)
                {
                case FieldParseState.Init:
                    if (c.Equals(_quote))
                    {
                        state = FieldParseState.QuotedField;
                    }
                    else if (c.Equals(_delimiter))
                    {
                        fields.Add(string.Empty);
                    }
                    else
                    {
                        state = FieldParseState.NormalField;
                        _fieldBuffer.Append(c);
                    }
                    break;

                case FieldParseState.NormalField:
                    if (c.Equals(_quote))
                    {
                        throw new Exception($"Malformed Error. File:{_filePath}({_lineNumber}) \n Data:\n{source}");
                    }
                    else if (c.Equals(_delimiter))
                    {
                        state = FieldParseState.Init;
                        _fieldBuffer.Append(c);
                        fields.Add(_fieldBuffer.ToString());
                        _fieldBuffer.Clear();
                    }
                    else
                    {
                        _fieldBuffer.Append(c);
                    }
                    break;

                case FieldParseState.QuotedField:
                    if (c.Equals(_quote))
                    {
                        state = FieldParseState.ClosingQuotedField;
                    }
                    else if (c.Equals(_delimiter))
                    {
                        _fieldBuffer.Append(c);
                    }
                    else
                    {
                        _fieldBuffer.Append(c);
                    }
                    break;

                case FieldParseState.ClosingQuotedField:
                    if (c.Equals(_quote))
                    {
                        // Cancel close quoted field, and add quote character.
                        state = FieldParseState.QuotedField;
                        _fieldBuffer.Append(c);
                    }
                    else if (c.Equals(_delimiter))
                    {
                        state = FieldParseState.Init;
                        fields.Add(_fieldBuffer.ToString());
                        _fieldBuffer.Clear();
                    }
                    else
                    {
                        throw new Exception($"Malformed Error. File:{_filePath}({_lineNumber}) \n Data:\n{source}");
                    }
                    break;
                }
            }

            // Init -> Add empty field.
            // NormalField -> Add last field.
            // ClosingQuotedField -> Add last quoted field.
            // QuotedField -> Quote Count logic defect ?
            if (state == FieldParseState.QuotedField)
            {
                throw new Exception();
            }

            fields.Add(_fieldBuffer.ToString());
            return(fields);
        }
    static string[] LoadRenderModelNames()
    {
        var results = new List<string>();
        results.Add("None");

        var error = HmdError.None;
        if (!SteamVR.active)
        {
            OpenVR.Init(ref error);
            if (error != HmdError.None)
                return results.ToArray();
        }

        var pRenderModels = OpenVR.GetGenericInterface(OpenVR.IVRRenderModels_Version, ref error);
        if (pRenderModels == System.IntPtr.Zero || error != HmdError.None)
        {
            if (!SteamVR.active)
                OpenVR.Shutdown();
            return results.ToArray();
        }

        var renderModels = new CVRRenderModels(pRenderModels);

        uint count = renderModels.GetRenderModelCount();
        for (uint i = 0; i < count; i++)
        {
            var buffer = new StringBuilder();
            var requiredSize = renderModels.GetRenderModelName(i, buffer, 0);
            if (requiredSize == 0)
                continue;

            buffer.EnsureCapacity((int)requiredSize);
            renderModels.GetRenderModelName(i, buffer, requiredSize);
            results.Add(buffer.ToString());
        }

        if (!SteamVR.active)
            OpenVR.Shutdown();

        return results.ToArray();
    }
Esempio n. 16
0
 public static void TestEnsureCapacity_Invalid()
 {
     var builder = new StringBuilder("Hello", 10);
     Assert.Throws<ArgumentOutOfRangeException>("capacity", () => builder.EnsureCapacity(-1)); // Capacity < 0
     Assert.Throws<ArgumentOutOfRangeException>("capacity", () => builder.EnsureCapacity(builder.MaxCapacity + 1)); // Capacity > builder.MaxCapacity
 }
        /// <summary>
        /// Gets the SID for the associated Windows user using the Windows API.
        /// </summary>
        /// <returns>
        /// The SID for the Windows user.
        /// </returns>
        private string GetSidApi()
        {
            // Verify that the username was provided
            if (string.IsNullOrWhiteSpace(Name))
            {
                return(string.Empty);
            }

            // The byte array that will hold the SID
            byte[] sid = null;
            // The SID buffer size
            uint cbSid = 0;
            // Then domain name
            StringBuilder referencedDomainName = new StringBuilder();
            // The buffer size for the domain name
            uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;

            // The type of SID
            WinApi.SID_NAME_USE sidUse;

            // Default the return value to indicate no error
            int err = WinApi.NO_ERROR;

            // Attempt to get the SID for the account name
            if (!WinApi.LookupAccountName(
                    null,
                    Name,
                    sid,
                    ref cbSid,
                    referencedDomainName,
                    ref cchReferencedDomainName,
                    out sidUse))
            {
                // Get the error from the LookupAccountName API call
                err = Marshal.GetLastWin32Error();

                // Check to see if either the buffer wasn't sufficient or the
                // invalid flags error was returned
                if (err == WinApi.ERROR_INSUFFICIENT_BUFFER || err == WinApi.ERROR_INVALID_FLAGS)
                {
                    // Create a new byte buffer with the size returned from the
                    // first LookupAccountName request
                    sid = new byte[cbSid];

                    // Make sure that the capacity of the StringBuilder object
                    // for the domain name is at the correct buffer size
                    referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);

                    // Reset the return value to indicate no error
                    err = WinApi.NO_ERROR;

                    // Attempt to get the account name after the correct buffer
                    // sizes have been set
                    if (!WinApi.LookupAccountName(
                            null,
                            Name,
                            sid,
                            ref cbSid,
                            referencedDomainName,
                            ref cchReferencedDomainName,
                            out sidUse))
                    {
                        // Return null if the SID could not be retrieved
                        return(null);
                    }
                }
            }
            // Any other error that occured when trying to get the SID for the
            // account name
            else
            {
                // Return null if the SID could not be retrieved
                return(null);
            }

            // No error occurred
            if (err == 0)
            {
                // Create the SID pointer
                IntPtr ptrSid;

                // Attempt to convert the SID byte array to a string
                if (!WinApi.ConvertSidToStringSid(sid, out ptrSid))
                {
                    // Return an empty string if the SID could not be
                    // retrieved
                    return(null);
                }
                else
                {
                    // Copy all characters from an unmanaged memory string to
                    // a manage string
                    string sidString = Marshal.PtrToStringAuto(ptrSid);
                    // Free up the memory
                    WinApi.LocalFree(ptrSid);

                    // Return the SID for the account name
                    return(sidString);
                }
            }
            else
            {
                // Return null if the SID could not be retrieved
                return(null);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Reads text from the input stream, and splits it into tokens, using whitespace and a list
        /// of separator characters as token delimiters.
        /// </summary>
        /// <remarks>This tokenizer does not return line number and column information.</remarks>
        /// <param name="inputReader">Input text reader containing textual data.</param>
        /// <returns>List of non-whitespace, or separator tokens.</returns>
        public IEnumerable <IToken> EnumerateTokens(System.IO.TextReader inputReader)
        {
            if (inputReader == null)
            {
                yield break;
            }

            // Initialize parser state.
            ParserState currentState = ParserState.Init;

            int tokenStart = -1;
            int position   = 0;

            StringBuilder tokenBuilder = new StringBuilder(1024);

            // Read all characters, one by one.
            for (int c = inputReader.Read(); c >= 0; c = inputReader.Read())
            {
                char currentChar = (char)c;
                switch (currentState)
                {
                case ParserState.Init:
                {
                    currentState = ParserState.Token;
                    if (IsSeparator(currentChar))
                    {
                        if (EmitSeparatorsAsTokens)
                        {
                            yield return(new Token(new string( currentChar, 1 ), TOKEN_TYPE_SEPARATOR, position, 1));
                        }
                        tokenStart = position + 1;
                    }
                    else
                    {
                        tokenBuilder.Append(currentChar);
                        tokenStart = position;
                    }
                }
                break;

                case ParserState.Token:
                {
                    if (IsSeparator(currentChar))
                    {
                        if (tokenBuilder.Length > 0)
                        {
                            string originalToken = tokenBuilder.ToString();
                            if (TrimTokens)
                            {
                                string trimmedToken = tokenBuilder.ToString().TrimStart();
                                int    trimOffset   = originalToken.Length - trimmedToken.Length;
                                trimmedToken = trimmedToken.TrimEnd();
                                yield return(new Token(trimmedToken, TOKEN_TYPE_NONWHITESPACE, tokenStart + trimOffset, trimmedToken.Length));
                            }
                            else
                            {
                                yield return(new Token(originalToken, TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart));
                            }
                        }
                        if (EmitSeparatorsAsTokens)
                        {
                            yield return(new Token(new String(currentChar, 1), TOKEN_TYPE_SEPARATOR, position, 1));
                        }
                        tokenBuilder.Clear();
                        tokenBuilder.EnsureCapacity(1024);
                        tokenStart = position + 1;
                    }
                    else
                    {
                        tokenBuilder.Append(currentChar);
                    }
                }
                break;
                }
                ++position;
            }
            if (tokenStart >= 0 && tokenBuilder.Length > 0)
            {
                yield return(new Token(tokenBuilder.ToString(), TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart));
            }
        }
Esempio n. 19
0
 private void Reset()
 {
     Builder.Length = 0;
     Builder.EnsureCapacity(256);
 }
 public int EnsureCapacity(int capacity)
 {
     return(mStringBuilder.EnsureCapacity(capacity));
 }
Esempio n. 21
0
        private ClientConfigPaths(string exePath, bool includeUserConfig)
        {
            _includesUserConfig = includeUserConfig;

            Assembly exeAssembly         = null;
            string   applicationUri      = null;
            string   applicationFilename = null;

            // get the assembly and applicationUri for the file
            if (exePath == null)
            {
                // First check if a configuration file has been set for this app domain. If so, we will use that.
                // The CLR would already have normalized this, so no further processing necessary.
                AppDomain      domain = AppDomain.CurrentDomain;
                AppDomainSetup setup  = domain.SetupInformation;
                _applicationConfigUri = setup.ConfigurationFile;

                // Now figure out the application path.
                exeAssembly = Assembly.GetEntryAssembly();
                if (exeAssembly != null)
                {
                    _hasEntryAssembly = true;
                    applicationUri    = exeAssembly.CodeBase;

                    bool isFile = false;

                    // If it is a local file URI, convert it to its filename, without invoking Uri class.
                    // example: "file:///C:/WINNT/Microsoft.NET/Framework/v2.0.x86fre/csc.exe"
                    if (StringUtil.StartsWithIgnoreCase(applicationUri, FILE_URI_LOCAL))
                    {
                        isFile         = true;
                        applicationUri = applicationUri.Substring(FILE_URI_LOCAL.Length);
                    }
                    // If it is a UNC file URI, convert it to its filename, without invoking Uri class.
                    // example: "file://server/share/csc.exe"
                    else if (StringUtil.StartsWithIgnoreCase(applicationUri, FILE_URI_UNC))
                    {
                        isFile         = true;
                        applicationUri = applicationUri.Substring(FILE_URI.Length);
                    }

                    if (isFile)
                    {
                        applicationUri      = applicationUri.Replace('/', '\\');
                        applicationFilename = applicationUri;
                    }
                    else
                    {
                        applicationUri = exeAssembly.EscapedCodeBase;
                    }
                }
                else
                {
                    StringBuilder sb        = new StringBuilder(MAX_PATH);
                    int           noOfTimes = 1;
                    int           length    = 0;
                    // Iterating by allocating chunk of memory each time we find the length is not sufficient.
                    // Performance should not be an issue for current MAX_PATH length due to this change.
                    while (((length = UnsafeNativeMethods.GetModuleFileName(new HandleRef(null, IntPtr.Zero), sb, sb.Capacity)) == sb.Capacity) &&
                           Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER &&
                           sb.Capacity < MAX_UNICODESTRING_LEN)
                    {
                        noOfTimes += 2; // increasing buffer size by 520 in each iteration - perf.
                        int capacity = noOfTimes * MAX_PATH < MAX_UNICODESTRING_LEN ? noOfTimes * MAX_PATH : MAX_UNICODESTRING_LEN;
                        sb.EnsureCapacity(capacity);
                    }
                    sb.Length           = length;
                    applicationUri      = Path.GetFullPath(sb.ToString());
                    applicationFilename = applicationUri;
                }
            }
            else
            {
                applicationUri = Path.GetFullPath(exePath);
                if (!FileUtil.FileExists(applicationUri, false))
                {
                    throw ExceptionUtil.ParameterInvalid("exePath");
                }

                applicationFilename = applicationUri;
            }

            // Fallback if we haven't set the app config file path yet.
            if (_applicationConfigUri == null)
            {
                _applicationConfigUri = applicationUri + ConfigExtension;
            }

            // Set application path
            _applicationUri = applicationUri;

            // In the case when exePath was explicitly supplied, we will not be able to
            // construct user.config paths, so quit here.
            if (exePath != null)
            {
                return;
            }

            // Skip expensive initialization of user config file information if requested.
            if (!_includesUserConfig)
            {
                return;
            }

            bool isHttp = StringUtil.StartsWithIgnoreCase(_applicationConfigUri, HTTP_URI);

            SetNamesAndVersion(applicationFilename, exeAssembly, isHttp);

            // Check if this is a clickonce deployed application. If so, point the user config
            // files to the clickonce data directory.
            if (this.IsClickOnceDeployed(AppDomain.CurrentDomain))
            {
                string dataPath      = AppDomain.CurrentDomain.GetData(ClickOnceDataDirectory) as string;
                string versionSuffix = Validate(_productVersion, false);

                // NOTE: No roaming config for clickonce - not supported.
                if (Path.IsPathRooted(dataPath))
                {
                    _localConfigDirectory = CombineIfValid(dataPath, versionSuffix);
                    _localConfigFilename  = CombineIfValid(_localConfigDirectory, UserConfigFilename);
                }
            }
            else if (!isHttp)
            {
                // If we get the config from http, we do not have a roaming or local config directory,
                // as it cannot be edited by the app in those cases because it does not have Full Trust.

                // suffix for user config paths

                string part1 = Validate(_companyName, true);

                string validAppDomainName  = Validate(AppDomain.CurrentDomain.FriendlyName, true);
                string applicationUriLower = !String.IsNullOrEmpty(_applicationUri) ? _applicationUri.ToLower(CultureInfo.InvariantCulture) : null;
                string namePrefix          = !String.IsNullOrEmpty(validAppDomainName) ? validAppDomainName : Validate(_productName, true);
                string hashSuffix          = GetTypeAndHashSuffix(AppDomain.CurrentDomain, applicationUriLower);

                string part2 = (!String.IsNullOrEmpty(namePrefix) && !String.IsNullOrEmpty(hashSuffix)) ? namePrefix + hashSuffix : null;

                string part3 = Validate(_productVersion, false);

                string dirSuffix = CombineIfValid(CombineIfValid(part1, part2), part3);

                string roamingFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                if (Path.IsPathRooted(roamingFolderPath))
                {
                    _roamingConfigDirectory = CombineIfValid(roamingFolderPath, dirSuffix);
                    _roamingConfigFilename  = CombineIfValid(_roamingConfigDirectory, UserConfigFilename);
                }

                string localFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                if (Path.IsPathRooted(localFolderPath))
                {
                    _localConfigDirectory = CombineIfValid(localFolderPath, dirSuffix);
                    _localConfigFilename  = CombineIfValid(_localConfigDirectory, UserConfigFilename);
                }
            }
        }
        public string GetTrackerSerialNumber(uint deviceIndex)
        {
            if (openVR == null)
            {
                return(null);
            }

            var buffer = new StringBuilder();
            var error  = default(ETrackedPropertyError);
            //Capacity取得
            var capacity = (int)openVR.GetStringTrackedDeviceProperty(deviceIndex, ETrackedDeviceProperty.Prop_SerialNumber_String, null, 0, ref error);

            if (capacity < 1)
            {
                return(null);             // "No Serial Number";
            }
            openVR.GetStringTrackedDeviceProperty(deviceIndex, ETrackedDeviceProperty.Prop_SerialNumber_String, buffer, (uint)buffer.EnsureCapacity(capacity), ref error);
            if (error != ETrackedPropertyError.TrackedProp_Success)
            {
                return(null);                                                   // "No Serial Number";
            }
            return(buffer.ToString());
        }
Esempio n. 23
0
        /// <summary>
        /// Gets a summary information property.
        /// </summary>
        /// <param name="index">Index of the summary information property.</param>
        /// <returns>The summary information property.</returns>
        public object GetProperty(int index)
        {
            uint          dataType;
            StringBuilder stringValue = new StringBuilder("");
            int           bufSize     = 0;
            int           intValue;
            FILETIME      timeValue;

            timeValue.dwHighDateTime = 0;
            timeValue.dwLowDateTime  = 0;
            uint ret = MsiInterop.MsiSummaryInfoGetProperty(handle, index, out dataType, out intValue, ref timeValue, stringValue, ref bufSize);

            //if(ret != (dataType == (uint) VT.LPSTR ? (uint) MsiInterop.Error.MORE_DATA : 0))
            if (234 == ret)
            {
                stringValue.EnsureCapacity(++bufSize);
                ret = MsiInterop.MsiSummaryInfoGetProperty(handle, index, out dataType, out intValue, ref timeValue, stringValue, ref bufSize);
            }
            if (0 != ret)
            {
                throw new ArgumentNullException();   // TODO: come up with a real exception to throw
            }
            switch ((VT)dataType)
            {
            case VT.EMPTY:
            {
                return("");
                //if(type == typeof(DateTime)) return DateTime.MinValue;
                //else if(type == typeof(string)) return "";
                //else if(type == typeof(short)) return (short) 0;
                //else if(type == typeof(int)) return (int) 0;
                //else throw new ArgumentNullException(); // TODO: come up with a real exception to throw
            }

            case VT.LPSTR:
            {
                return(stringValue.ToString());
                //if(type == typeof(string)) return stringValue.ToString();
                //else if(type == typeof(short) || type == typeof(int) || type == typeof(DateTime)) throw new InstallerException();
                //else throw new ArgumentNullException();// TODO: come up with a real exception to throw
            }

            case VT.I2:
            case VT.I4:
            {
                return("" + intValue);
                //if(type == typeof(short)) return (short) intValue;
                //else if(type == typeof(int)) return intValue;
                //else if(type == typeof(string)) return "" + intValue;
                //else if(type == typeof(DateTime)) throw new InstallerException();
                //else throw new ArgumentException();
            }

            case VT.FILETIME:
            {
                return(timeValue.ToString());
                //if(type == typeof(DateTime)) return DateTime.FromFileTime(timeValue);
                //else if(type == typeof(string)) return "" + DateTime.FromFileTime(timeValue);
                //else if(type == typeof(short) || type == typeof(int)) throw new InstallerException();
                //else throw new ArgumentException();
            }

            default:
            {
                throw new ArgumentNullException();     // TODO: come up with a real exception to throw
            }
            }
        }
Esempio n. 24
0
 public int EnsureCapacity(int capacity)
 {
     return(_builder.EnsureCapacity(capacity));
 }
Esempio n. 25
0
        public static void ReportTable(string tablename, TableDefn table, int width)
        {
            string query = "SELECT " + table.SelectCols() + " FROM " + tablename + ";";

            int           capacity = 4096;
            StringBuilder sb       = new StringBuilder(capacity);
            int           rows     = 0;

            IDbConnection dbConn = Connection.Me.GetConnection();

            try
            {
                dbConn.Open();
                IDbCommand dbCmd = dbConn.CreateCommand();
                dbCmd.CommandType = CommandType.Text;
                dbCmd.CommandText = query;

                using (IDataReader rdr = dbCmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        ++rows;
                        for (int i = 0; i < rdr.FieldCount; i++)
                        {
                            object fldvalue = rdr.GetValue(i);
                            if (fldvalue != DBNull.Value)
                            {
                                string value = Convert.ChangeType(fldvalue, rdr.GetFieldType(i)).ToString().TrimEnd();
                                string type  = table.FindColumn(rdr.GetName(i)).ColumnType;
                                if (type == "BIT")
                                {
                                    if (value == "0" || value.ToLower() == "false")
                                    {
                                        value = "false";
                                    }
                                    else if (value == "1" || value.ToLower() == "true")
                                    {
                                        value = "true";
                                    }
                                    else
                                    {
                                        Console.WriteLine(value);
                                    }
                                }
                                else if (type == "DATETIME")
                                {
                                    value = value.Left(10);
                                }
                                if (sb.Length + value.Length > capacity)
                                {
                                    capacity = capacity * 2;
                                    sb.EnsureCapacity(capacity);
                                }
                                sb.Append(EscapeXML(value));
                            }
                        }
                    }
                }

                if (rows > 0)
                {
                    string hash = MakeHash(sb.ToString());
                    Console.WriteLine(tablename.PadRight(width) + " has " + rows.ToString().PadRight(5) + " rows and hash=" + hash);
                }
                else
                {
                    Console.WriteLine(tablename.PadRight(width) + " is empty.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("There was a problem loading table from query [" + query + "] - " + ex.Message, ex);
            }
            finally
            {
                dbConn.Close();
                dbConn = null;
            }
        }
Esempio n. 26
0
        private static string GetDomainSid(string accountName)
        {
            uint sidLength        = 0;
            uint domainNameLength = 0;

            byte[]        sid        = null;
            StringBuilder domainName = new StringBuilder();

            NativeMethods.SID_NAME_USE peUse;

            // Query buffer size requirement by passing in NULL for Sid and ReferencedDomainName
            if (!NativeMethods.LookupAccountName(null,       // lpSystemName
                                                 accountName,
                                                 null,       // Sid
                                                 ref sidLength,
                                                 domainName, // ReferencedDomainName
                                                 ref domainNameLength,
                                                 out peUse))
            {
                int errorCode = Marshal.GetLastWin32Error();

                if (errorCode != NativeMethods.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                sid = new byte[sidLength];
                domainName.EnsureCapacity((int)domainNameLength);

                if (!NativeMethods.LookupAccountName(null,
                                                     accountName,
                                                     sid,
                                                     ref sidLength,
                                                     domainName,
                                                     ref domainNameLength,
                                                     out peUse))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }
            else
            {
                throw new TransferException("Unexpected LookupAccountName success");
            }

            // Get domain Sid from User Sid
            uint domainSidLength = 0;

            byte[] domainSid = null;
            if (!NativeMethods.GetWindowsAccountDomainSid(sid, domainSid, ref domainSidLength))
            {
                int errorCode = Marshal.GetLastWin32Error();

                if (errorCode != NativeMethods.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                domainSid = new byte[domainSidLength];

                if (!NativeMethods.GetWindowsAccountDomainSid(sid, domainSid, ref domainSidLength))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }
            else
            {
                throw new TransferException("Unexpected GetWindowsAccountDomainSid success");
            }

            // Get string corresponding to SID
            IntPtr domainSidPtr;

            if (!NativeMethods.ConvertSidToStringSid(domainSid, out domainSidPtr))
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            try
            {
                return(Marshal.PtrToStringAuto(domainSidPtr));
            }
            finally
            {
                NativeMethods.LocalFree(domainSidPtr);
            }
        }
        public static void SetRight(string ComputerName, string domainAccount, string privilegeName, bool bRemove)
        {
            StringBuilder domainName = new StringBuilder(20);
            IntPtr        pSid       = IntPtr.Zero;
            uint          sidSize    = 0,
                          nameSize   = 0;
            SID_NAME_USE accountType;
            int          winErrorCode;
            string       errorMessage;

            // This first call makes sure we get the buffer sizes correctly. We use NULL for system name, because it needs to be sent to the domains trusted by local system
            if (!LookupAccountName(null, domainAccount, pSid, ref sidSize, domainName, ref nameSize, out accountType))
            {
                winErrorCode = Marshal.GetLastWin32Error();
                if (winErrorCode == ERROR_INSUFFICIENT_BUFFER || winErrorCode == ERROR_INVALID_FLAGS)
                {
                    domainName.EnsureCapacity((int)nameSize);
                    pSid = Marshal.AllocHGlobal((int)sidSize);

                    if (!LookupAccountName(null, domainAccount, pSid, ref sidSize, domainName, ref nameSize, out accountType))
                    {
                        // Got the sizes corretly but other bad things happened.
                        winErrorCode = Marshal.GetLastWin32Error();
                        errorMessage = string.Format("LookupAccountName failed: {0}", winErrorCode);
                        throw new Win32Exception(winErrorCode, errorMessage);
                    }
                }
            }


            LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING();

            systemName.SetTo(ComputerName);

            IntPtr policyHandle = IntPtr.Zero;
            LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject();

            // We are asking for too many permissions here - need to tone it down
            int desiredAccess = (int)(LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                                      LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                                      LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                                      LSA_AccessPolicy.POLICY_CREATE_SECRET |
                                      LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                                      LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                                      LSA_AccessPolicy.POLICY_NOTIFICATION |
                                      LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                                      LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                                      LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                                      LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                                      LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                                      LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                                      );
            uint resultPolicy = LsaOpenPolicy(ref systemName, ref objectAttributes, desiredAccess, out policyHandle);

            winErrorCode = LsaNtStatusToWinError(resultPolicy);

            if (winErrorCode != NO_ERROR)
            {
                errorMessage = string.Format("OpenPolicy failed: {0} ", winErrorCode);
                throw new Win32Exception(winErrorCode, errorMessage);
            }
            else
            {
                try
                {
                    LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1];
                    userRights[0] = new LSA_UNICODE_STRING();
                    userRights[0].SetTo(privilegeName);

                    if (bRemove)
                    {
                        // Removes a privilege from an account
                        uint result = LsaRemoveAccountRights(policyHandle, pSid, false, userRights, 1);
                        winErrorCode = LsaNtStatusToWinError(result);
                        if (winErrorCode != NO_ERROR)
                        {
                            errorMessage = string.Format("LsaRemoveAccountRights failed: {0}", winErrorCode);
                            throw new Win32Exception((int)winErrorCode, errorMessage);
                        }
                    }
                    else
                    {
                        // Adds a privilege to an account
                        uint res = LsaAddAccountRights(policyHandle, pSid, userRights, 1);
                        winErrorCode = LsaNtStatusToWinError(res);
                        if (winErrorCode != 0)
                        {
                            errorMessage = string.Format("LsaAddAccountRights failed: {0}", winErrorCode);
                            throw new Win32Exception((int)winErrorCode, errorMessage);
                        }
                    }
                }
                finally
                {
                    LsaClose(policyHandle);
                }
            }
            FreeSid(pSid);
        }
Esempio n. 28
0
        public IEnumerable <Info> FindAll(CancellationToken cancellationToken)
        {
            var clsid = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE");
            var riid  = typeof(ICLRMetaHost).GUID;
            var mh    = (ICLRMetaHost)CLRCreateInstance(ref clsid, ref riid);

            int ourPid    = Process.GetCurrentProcess().Id;
            var processes = new List <Process>();

            foreach (var process in Process.GetProcesses())
            {
                cancellationToken.ThrowIfCancellationRequested();
                int pid;
                try {
                    pid = process.Id;
                }
                catch {
                    continue;
                }
                if (pid == ourPid)
                {
                    continue;
                }
                // Prevent slow exceptions by filtering out processes we can't access
                using (var fh = OpenProcess(PROCESS_ALL_ACCESS, false, process.Id)) {
                    if (fh.IsInvalid)
                    {
                        continue;
                    }
                }
                if (Environment.Is64BitOperatingSystem)
                {
                    bool isWow64Process;
                    if (IsWow64Process(process.Handle, out isWow64Process))
                    {
                        if (IntPtr.Size == 4 && !isWow64Process)
                        {
                            continue;
                        }
                    }
                }
                if (process.HasExited)
                {
                    continue;
                }
                processes.Add(process);

                IEnumUnknown iter;
                int          hr = mh.EnumerateLoadedRuntimes(process.Handle, out iter);
                if (hr >= 0)
                {
                    for (;;)
                    {
                        object obj;
                        uint   fetched;
                        hr = iter.Next(1, out obj, out fetched);
                        if (hr < 0 || fetched == 0)
                        {
                            break;
                        }

                        var  rtInfo   = (ICLRRuntimeInfo)obj;
                        uint chBuffer = 0;
                        var  sb       = new StringBuilder(300);
                        hr = rtInfo.GetVersionString(sb, ref chBuffer);
                        sb.EnsureCapacity((int)chBuffer);
                        hr = rtInfo.GetVersionString(sb, ref chBuffer);

                        var info = new Info(process, sb.ToString(), new DesktopCLRTypeAttachInfo(sb.ToString()));

                        yield return(info);
                    }
                }
            }

            // Finding CoreCLR assemblies is much slower so do it last
            foreach (var process in processes)
            {
                if (process.HasExited)
                {
                    continue;
                }
                ProcessModule[] modules;
                try {
                    modules = process.Modules.Cast <ProcessModule>().ToArray();
                }
                catch {
                    continue;
                }
                foreach (var module in modules)
                {
                    var moduleFilename = module.FileName;
                    var dllName        = Path.GetFileName(moduleFilename);
                    if (dllName.Equals("coreclr.dll", StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (var info in TryGetCoreCLRInfos(process, moduleFilename))
                        {
                            yield return(info);
                        }
                        break;
                    }
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Link this ShaderProgram.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> used for linking this ShaderProgram.
        /// </param>
        /// <param name="cctx">
        /// A <see cref="ShaderCompilerContext"/> that specify additional compiler parameters.
        /// </param>
        /// <remarks>
        /// <para>
        /// Generate shader program source code, compile and link it. After a successfull
        /// link, obtain every information about active uniform and input variables.
        /// </para>
        /// <para>
        /// This routine generate the source code of each attached ShaderObject instance and
        /// compile it. This step is performed only if really required (tendentially every
        /// shader object is already compiled).
        /// </para>
        /// <para>
        /// After having compiled every attached shader object, it's performed the linkage between
        /// shader objects. After this process the ShaderProgram instance can be bound to issue
        /// rendering commands.
        /// </para>
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Exception thrown in the case this ShaderProgram is already linked.
        /// </exception>
        /// <exception cref="ShaderException">
        /// Exception throw in the case this ShaderProgram is not linkable.
        /// </exception>
        private void Link(GraphicsContext ctx, ShaderCompilerContext cctx)
        {
            CheckCurrentContext(ctx);

            if (cctx == null)
            {
                throw new ArgumentNullException("cctx");
            }

            // Using a deep copy of the shader compiler context, since it will be modified by this ShaderProgram
            // instance and the attached ShaderObject instances
            cctx = new ShaderCompilerContext(cctx);

            #region Compile and Attach Shader Objects

            // Be sure to take every attached shader
            uint[] shadersObject = null;
            int    shadersCount;

            Gl.GetProgram(ObjectName, Gl.ATTACHED_SHADERS, out shadersCount);

            if (shadersCount > 0)
            {
                shadersObject = new uint[shadersCount];
                Gl.GetAttachedShaders(ObjectName, out shadersCount, shadersObject);
                Debug.Assert(shadersCount == shadersObject.Length);
            }

            foreach (ShaderObject shaderObject in _ProgramObjects)
            {
                // Create shader object, if necessary
                if (shaderObject.Exists(ctx) == false)
                {
                    shaderObject.Create(ctx, cctx);
                }

                // Do not re-attach the same shader object
                if ((shadersObject != null) && Array.Exists(shadersObject, delegate(uint item) { return(item == shaderObject.ObjectName); }))
                {
                    continue;
                }

                // Attach shader object
                Gl.AttachShader(ObjectName, shaderObject.ObjectName);
            }

            #endregion

            #region Transform Feedback Definition

            IntPtr[] feedbackVaryingsPtrs = null;

            if ((_FeedbackVaryings != null) && (_FeedbackVaryings.Count > 0))
            {
                sLog.Debug("Feedback varyings ({0}):", cctx.FeedbackVaryingsFormat);
                sLog.Indent();
                foreach (string feedbackVarying in _FeedbackVaryings)
                {
                    sLog.Debug("- {0}", feedbackVarying);
                }
                sLog.Unindent();

                if (ctx.Caps.GlExtensions.TransformFeedback2_ARB || ctx.Caps.GlExtensions.TransformFeedback_EXT)
                {
                    string[] feedbackVaryings = _FeedbackVaryings.ToArray();

                    // Bug in NVIDIA drivers? Not exactly, but the NVIDIA driver hold the 'feedbackVaryings' pointer until
                    // glLinkProgram is executed, causing linker errors like 'duplicate varying names are not allowed' or garbaging
                    // part of the returned strings via glGetTransformFeedbackVarying
                    feedbackVaryingsPtrs = feedbackVaryings.AllocHGlobal();

                    // Specify feedback varyings
                    Gl.TransformFeedbackVaryings(ObjectName, feedbackVaryingsPtrs, (int)cctx.FeedbackVaryingsFormat);
                }
                else if (ctx.Caps.GlExtensions.TransformFeedback2_NV)
                {
                    // Nothing to do ATM
                }
                else
                {
                    throw new InvalidOperationException("transform feedback not supported");
                }
            }

            #endregion

            #region Bind Fragment Locations

            if (ctx.Caps.GlExtensions.GpuShader4_EXT)
            {
                // Setup fragment locations, where defined
                foreach (KeyValuePair <string, int> pair in _FragLocations)
                {
                    if (pair.Value >= 0)
                    {
                        Gl.BindFragDataLocation(ObjectName, (uint)pair.Value, pair.Key);
                    }
                }
            }

            #endregion

            #region Link Shader Program Objects

            int lStatus;

            sLog.Debug("Link shader program {0}", Identifier ?? "<Unnamed>");

            // Link shader program
            Gl.LinkProgram(ObjectName);
            // Check for linking errors
            Gl.GetProgram(ObjectName, Gl.LINK_STATUS, out lStatus);

            // Release feedback varyings unmanaged memory
            if (feedbackVaryingsPtrs != null)
            {
                feedbackVaryingsPtrs.FreeHGlobal();
            }

            if (lStatus != Gl.TRUE)
            {
                const int MaxInfoLength = 4096;

                StringBuilder logInfo = new StringBuilder(MaxInfoLength);
                int           logLength;

                // Obtain compilation log
                Gl.GetProgramInfoLog(ObjectName, MaxInfoLength, out logLength, logInfo);

                // Stop link process
                StringBuilder sb = new StringBuilder(logInfo.Capacity);

                string[] compilerLogLines = logInfo.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string logLine in compilerLogLines)
                {
                    sb.AppendLine("  $ " + logLine);
                }

                sLog.Error("Shader program \"{0}\" linkage failed: {1}", Identifier ?? "<Unnamed>", sb.ToString());

                throw new ShaderException("shader program is not valid. Linker output for {0}: {1}\n", Identifier ?? "<Unnamed>", sb.ToString());
            }
            // Set linked flag
            _Linked = true;

            #endregion

            #region Collect Active Program Uniforms

            int uniformBufferSize, attributeBufferSize;
            int uniformCount;

            // Get active uniforms count
            Gl.GetProgram(ObjectName, Gl.ACTIVE_UNIFORMS, out uniformCount);
            // Get uniforms maximum length for name
            Gl.GetProgram(ObjectName, Gl.ACTIVE_UNIFORM_MAX_LENGTH, out uniformBufferSize);

            // Clear uniform mapping
            _UniformMap.Clear();
            _DefaultBlockUniformSlots = 0;

            // Collect uniform information
            for (uint i = 0; i < (uint)uniformCount; i++)
            {
                int uniformNameLength, uniformSize, uniformType;

                // Mono optimize StringBuilder capacity after P/Invoke... ensure enought room
                StringBuilder uNameBuilder = new StringBuilder(uniformBufferSize + 2);
                uNameBuilder.EnsureCapacity(uniformBufferSize);

                // Obtain active uniform informations
                Gl.GetActiveUniform(ObjectName, i, uniformBufferSize, out uniformNameLength, out uniformSize, out uniformType, uNameBuilder);

                string uniformName = uNameBuilder.ToString();

                // Obtain active uniform location
                int uLocation = Gl.GetUniformLocation(ObjectName, uniformName);

                UniformBinding uniformBinding = new UniformBinding(uniformName, i, uLocation, (ShaderUniformType)uniformType);

                // Map active uniform
                _UniformMap[uniformName] = uniformBinding;
                // Keep track of used slot
                _DefaultBlockUniformSlots += GetUniformSlotCount(uniformBinding.UniformType);
            }

            // Log uniform location mapping
            List <string> uniformNames = new List <string>(_UniformMap.Keys);

            // Make uniform list invariant respect the used driver (ease log comparation)
            uniformNames.Sort();

            sLog.Debug("Shader program active uniforms:");
            foreach (string uniformName in uniformNames)
            {
                sLog.Debug("\tUniform {0} (Type: {1}, Location: {2})", uniformName, _UniformMap[uniformName].UniformType, _UniformMap[uniformName].Location);
            }

            sLog.Debug("Shader program active uniform slots: {0}", _DefaultBlockUniformSlots);

            #endregion

            #region Collect Active Program Inputs

            // Get active inputs count
            int activeInputs;

            Gl.GetProgram(ObjectName, Gl.ACTIVE_ATTRIBUTES, out activeInputs);
            // Get inputs maximum length for name
            Gl.GetProgram(ObjectName, Gl.ACTIVE_ATTRIBUTE_MAX_LENGTH, out attributeBufferSize);

            // Clear input mapping
            _AttributesMap.Clear();

            // Collect input location mapping
            for (uint i = 0; i < (uint)activeInputs; i++)
            {
                StringBuilder nameBuffer = new StringBuilder(attributeBufferSize);
                int           nameLength, size, type;

                // Mono optimize StringBuilder capacity after P/Invoke... ensure enought room for the current loop
                nameBuffer.EnsureCapacity(attributeBufferSize);

                // Obtain active input informations
                Gl.GetActiveAttrib(ObjectName, i, attributeBufferSize, out nameLength, out size, out type, nameBuffer);
                // Obtain active input location
                string name = nameBuffer.ToString();

                int location = Gl.GetAttribLocation(ObjectName, name);
                // Map active input
                _AttributesMap[name] = new AttributeBinding((uint)location, (ShaderAttributeType)type);
            }

            // Log attribute mapping
            List <string> attributeNames = new List <string>(_AttributesMap.Keys);

            // Make attribute list invariant respect the used driver (ease log comparation)
            attributeNames.Sort();

            sLog.Debug("Shader program active attributes:");
            foreach (string attributeName in attributeNames)
            {
                sLog.Debug("\tAttribute {0} (Type: {1}, Location: {2})", attributeName, _AttributesMap[attributeName].Type, _AttributesMap[attributeName].Location);
            }

            #endregion

            #region Collect Fragment Locations

            if (ctx.Caps.GlExtensions.GpuShader4_EXT)
            {
                // Get fragment locations, just in the case automatically assigned
                foreach (string fragOutputName in new List <string>(_FragLocations.Keys))
                {
                    _FragLocations[fragOutputName] = Gl.GetFragDataLocation(ObjectName, fragOutputName);
                }
            }

            #endregion

            #region Collect Feedback Varyings

            if ((_FeedbackVaryings != null) && (_FeedbackVaryings.Count > 0))
            {
                if (ctx.Caps.GlExtensions.TransformFeedback2_ARB || ctx.Caps.GlExtensions.TransformFeedback_EXT)
                {
                    // Map active feedback
                    int feebackVaryings, feebackVaryingsMaxLength;

                    Gl.GetProgram(ObjectName, Gl.TRANSFORM_FEEDBACK_VARYINGS, out feebackVaryings);
                    Gl.GetProgram(ObjectName, Gl.TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, out feebackVaryingsMaxLength);

                    for (uint i = 0; i < feebackVaryings; i++)
                    {
                        StringBuilder sb = new StringBuilder(feebackVaryingsMaxLength);
                        int           length = 0, size = 0, type = 0;

                        Gl.GetTransformFeedbackVarying(ObjectName, (uint)i, feebackVaryingsMaxLength, out length, out size, out type, sb);
                        _FeedbacksMap.Add(sb.ToString(), new FeedbackBinding((ShaderAttributeType)type, (uint)size));
                    }
                }
                else if (ctx.Caps.GlExtensions.TransformFeedback2_NV)
                {
                    // Activate varyings
                    foreach (string feedbackVaryingName in _FeedbackVaryings)
                    {
                        Gl.ActiveVaryingNV(ObjectName, feedbackVaryingName);
                    }

                    // Map active feedback
                    int feebackVaryings, feebackVaryingsMaxLength;

                    Gl.GetProgram(ObjectName, Gl.ACTIVE_VARYINGS_NV, out feebackVaryings);
                    Gl.GetProgram(ObjectName, Gl.ACTIVE_VARYING_MAX_LENGTH_NV, out feebackVaryingsMaxLength);

                    for (uint i = 0; i < feebackVaryings; i++)
                    {
                        StringBuilder sb = new StringBuilder(feebackVaryingsMaxLength * 2);
                        int           length = 0, size = 0, type = 0;

                        Gl.GetActiveVaryingNV(ObjectName, (uint)i, feebackVaryingsMaxLength * 2, out length, out size, out type, sb);

                        _FeedbacksMap.Add(sb.ToString(), new FeedbackBinding((ShaderAttributeType)type, (uint)size));
                    }

                    // Specify feedback varyings
                    List <int> feedbackLocations = new List <int>();

                    foreach (string feedbackVaryingName in _FeedbackVaryings)
                    {
                        int location = Gl.GetVaryingLocationNV(ObjectName, feedbackVaryingName);

                        if (location >= 0)
                        {
                            feedbackLocations.Add(location);
                        }
                    }

                    Gl.TransformFeedbackVaryingsNV(ObjectName, feedbackLocations.ToArray(), (int)cctx.FeedbackVaryingsFormat);

                    // Map active feedback
                }

                Debug.Assert(_FeedbacksMap.Count > 0);

                // Log feedback mapping
                sLog.Debug("Shader program active feedbacks:");
                foreach (string feedbackName in _FeedbacksMap.Keys)
                {
                    sLog.Debug("\tFeedback {0} (Type: {1})", feedbackName, _FeedbacksMap[feedbackName].Type);
                }
            }

            #endregion
        }
Esempio n. 30
0
 public int EnsureCapacity(int capacity)
 {
     return(_sb.EnsureCapacity(capacity));
 }
Esempio n. 31
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            String  InfPath         = "";
            Boolean NeedsRebootFlag = false;
            UInt32  ReturnErrorCode;
            String  ReturnErrorCodeString;
            UInt32  NumberOfCharsToGet          = 0;
            backgroundWorkerArgs backgroundArgs = new backgroundWorkerArgs();

            //Arguments must be cast into backgroundWorkerArgs class and
            //copied into a new object in order to be accessed
            backgroundArgs = (backgroundWorkerArgs)e.Argument;

            if (backgroundArgs.operation == INSTALL_DRIVERS)
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(".\\");
                    //Look for all *.inf files in the current directory.
                    FileInfo[] files = di.GetFiles("*.inf", SearchOption.TopDirectoryOnly);
                    //Check if there were no .inf files found.  If so, set error code so status box is updated meaningfully.
                    if (files.Length == 0)
                    {
                        //OutputSatus_lstbx.Items.Add("Driver installation failed.  No .inf file(s) provided.");
                        backgroundArgs.resultStrings.Add("Driver installation failed.  No .inf files provided.");
                        if (backgroundArgs.mode == AUTO_INSTALL)
                        {
                            MessageBox.Show("Error: Driver installation failed, no .inf files provided.", "Error");
                        }
                    }
                    else
                    {
                        //For each .inf file found, install/pre-install the driver.
                        for (uint i = 0; i < files.Length; i++)
                        {
                            InfPath         = files[i].FullName;
                            ReturnErrorCode = DriverPackageInstallW(InfPath, DRIVER_PACKAGE_FORCE | DRIVER_PACKAGE_LEGACY_MODE, IntPtr.Zero, ref NeedsRebootFlag);
                            if (ReturnErrorCode == ERROR_SUCCESS)
                            {
                                backgroundArgs.resultStrings.Add("Complete: Driver installation successful.");
                            }
                            else if (ReturnErrorCode == ERROR_ACCESS_DENIED)
                            {
                                MessageBox.Show("The drivers cannot be installed without administrator privileges.", "Info");
                                backgroundArgs.resultStrings.Add("Driver install failed.  Please restart this application with admin privileges.");
                            }
                            else if (ReturnErrorCode == ERROR_NO_SUCH_DEVINST)
                            {
                                backgroundArgs.resultStrings.Add("Complete: Driver was pre-installed to the driver store successfully.");
                                backgroundArgs.resultStrings.Add("Note: If the Found New Hardware Wizard appears upon plugging in");
                                backgroundArgs.resultStrings.Add("the device, allow Windows to search automatically for the driver.");
                            }
                            else if ((ReturnErrorCode == ERROR_DIALOG_NOT_ACCEPTED) || (ReturnErrorCode == ERROR_DIALOG_NOT_ACCEPTED2))
                            {
                                MessageBox.Show("The driver cannot be installed unless you accept security warning or driver signature dialogs.", "Info");
                                backgroundArgs.resultStrings.Add("The driver was not installed.  Please try again.");
                            }
                            else
                            {
                                //Convert the error code to a hexadecimal formatted string, for easier human readability.
                                ReturnErrorCodeString = String.Format("{0:X}", ReturnErrorCode);
                                backgroundArgs.resultStrings.Add("Driver installation failed.  Error code = 0x" + ReturnErrorCodeString + ".");
                                if (backgroundArgs.mode == AUTO_INSTALL)
                                {
                                    MessageBox.Show("Driver installation failed.  Error code = 0x" + ReturnErrorCodeString + ".", "Error");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    backgroundArgs.resultStrings.Add("Driver installation failed.  Exception: " + ex.ToString() + ".");
                    if (backgroundArgs.mode == AUTO_INSTALL)
                    {
                        MessageBox.Show("Driver installation failed.  Exception: " + ex.ToString() + ".", "Error");
                    }
                }
            }
            else if (backgroundArgs.operation == REMOVE_DRIVERS)
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(".\\");
                    //Look for all *.inf files in the current directory, as well as all subdirectories.
                    FileInfo[] files = di.GetFiles("*.inf", SearchOption.AllDirectories);
                    //Check if there were no .inf files found.  If so, set error code so status box is updated meaningfully.
                    if (files.Length == 0)
                    {
                        backgroundArgs.resultStrings.Add("Driver removal failed.  No .inf file(s) provided.");
                        if (backgroundArgs.mode == AUTO_INSTALL)
                        {
                            MessageBox.Show("Driver removal failed.  No .inf file(s) provided.", "Error");
                        }
                    }
                    else
                    {
                        //For each .inf file found, remove the driver.
                        for (uint i = 0; i < files.Length; i++)
                        {
                            InfPath = files[i].FullName;
                            //Call DriverPackageGetPathW() function first time with num chars = 0, to get the proper/real NumberOfCharsToGet of the entire path.
                            NumberOfCharsToGet = 0;
                            //Allocate a stringbuilder to eventually receive the DriverStoreInfPath return value.  However,
                            //we don't know how large to make it yet, so it is important that the NumberOfCharsToGet is
                            //set = 0 before the first call to DriverPackageGetPathW().
                            StringBuilder DriverStoreInfPath = new StringBuilder();
                            ReturnErrorCode = DriverPackageGetPathW(InfPath, DriverStoreInfPath, ref NumberOfCharsToGet);
                            //Now resize our StringBuilder to be large enough to hold the entire driver store path.
                            DriverStoreInfPath.EnsureCapacity((int)NumberOfCharsToGet);
                            //Call the function a second time to get the actual path.  Path is returned in the DriverStoreInfPath.
                            ReturnErrorCode = DriverPackageGetPathW(InfPath, DriverStoreInfPath, ref NumberOfCharsToGet);

                            if (ReturnErrorCode == ERROR_SUCCESS)
                            {
                                //If we get to here, success, we have the path to the driver .inf file and package in the driver store (typically: C:\Windows\System32\DRVSTORE\[driver name + guid identifier])
                                //Try to remove the driver from the driver store, and from any PnP nodes currently using it.
                                NeedsRebootFlag = false;
                                ReturnErrorCode = DriverPackageUninstallW(DriverStoreInfPath.ToString(), DRIVER_PACKAGE_FORCE, IntPtr.Zero, ref NeedsRebootFlag);

                                if (ReturnErrorCode == ERROR_SUCCESS)
                                {
                                    if (NeedsRebootFlag == true)
                                    {
                                        backgroundArgs.resultStrings.Add("Complete: Driver removal successful.  Please reboot to complete the process.");
                                    }
                                    else
                                    {
                                        backgroundArgs.resultStrings.Add("Complete: Driver removal successful.");
                                    }
                                }
                                else if (ReturnErrorCode == ERROR_ACCESS_DENIED)
                                {
                                    MessageBox.Show("The drivers cannot be removed without administrator privileges.", "Info");
                                    backgroundArgs.resultStrings.Add("Driver removal failed.  Please restart this application with admin privileges.");
                                }
                                else
                                {
                                    //Convert the error code to a hexadecimal formatted string, for easier human readability.
                                    ReturnErrorCodeString = String.Format("{0:X}", ReturnErrorCode);
                                    backgroundArgs.resultStrings.Add("Driver removal failed.  DriverPackageUninstall() error code = 0x" + ReturnErrorCodeString + ".");
                                    if (backgroundArgs.mode == AUTO_INSTALL)
                                    {
                                        MessageBox.Show("Driver removal failed.  DriverPackageUninstall() error code = 0x" + ReturnErrorCodeString + ".", "Error");
                                    }
                                }
                            }
                            else if (ReturnErrorCode == ERROR_ACCESS_DENIED)
                            {
                                MessageBox.Show("The drivers cannot be removed without administrator privileges.", "Info");
                                backgroundArgs.resultStrings.Add("Driver removal failed.  Please restart this application with admin privileges.");
                            }
                            else if (ReturnErrorCode == ERROR_DRIVER_PACKAGE_NOT_IN_STORE)
                            {
                                //In this case, the driver wasn't in the driver store.
                                backgroundArgs.resultStrings.Add("Complete: Driver was not present in the driver store.");
                            }
                            else
                            {
                                //Convert the error code to a hexadecimal formatted string, for easier human readability.
                                ReturnErrorCodeString = String.Format("{0:X}", ReturnErrorCode);
                                backgroundArgs.resultStrings.Add("Driver removal failed.  DriverPackageGetPath() error code = 0x" + ReturnErrorCodeString + ".");
                                if (backgroundArgs.mode == AUTO_INSTALL)
                                {
                                    MessageBox.Show("Driver removal failed.  DriverPackageGetPath() error code = 0x" + ReturnErrorCodeString + ".", "Error");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    backgroundArgs.resultStrings.Add("Driver removal failed.  Exception: " + ex.ToString() + ".");
                    if (backgroundArgs.mode == AUTO_INSTALL)
                    {
                        MessageBox.Show("Driver removal failed.  Exception: " + ex.ToString() + ".", "Error");
                    }
                }
            }

            //Cannot directly update the form from the thread.  Therefore, we pass the result
            //strings to the backgroundWorker1_RunWorkerCompleted() event handler,
            //so that it can then print the strings to the list box on the form.
            e.Result = (backgroundWorkerArgs)backgroundArgs;
        }
Esempio n. 32
0
    public static void TestEnsureCapacity()
    {
        var builder = new StringBuilder(40);

        builder.EnsureCapacity(20);
        Assert.True(builder.Capacity >= 20);

        builder.EnsureCapacity(20000);
        Assert.True(builder.Capacity >= 20000);

        // Ensuring a capacity less than the current capacity does not change anything
        int oldCapacity = builder.Capacity;
        builder.EnsureCapacity(10);
        Assert.Equal(oldCapacity, builder.Capacity);
    }
Esempio n. 33
0
    /// <summary>
    /// Alternative ToString() method that appends to a StringBuilder to avoid creating a new string.
    /// Set optional argument appendNewLineAtEnd append a new line at the end.
    /// Set optional argument insertIndex to Insert instead of Append.
    /// </summary>
    public void ToString(StringBuilder sb, bool appendNewLineAtEnd = false, int insertIndex = -1)
    {
        StringBuilder tsb;         // Temp String Builder

        if (insertIndex >= 0)
        {
            if (_toStringSB == null)
            {
                _toStringSB = new StringBuilder();
            }
            else
            {
                _toStringSB.Clear();
            }
            tsb = _toStringSB;
        }
        else
        {
            tsb = sb;
        }

        tsb.Append(_address);
        for (int i = 0; i < _argInfo.Count; i++)
        {
            tsb.Append(' ');

            OscArgType type;
            if (!TryGetArgType(i, out type))
            {
                continue;
            }

            switch (type)
            {
            case OscArgType.Null:
                tsb.Append("Null"); break;

            case OscArgType.Impulse:
                tsb.Append("Impulse"); break;

            case OscArgType.Bool:
                bool boolValue;
                if (TryGet(i, out boolValue))
                {
                    tsb.Append(boolValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Float:
                float floatValue;
                if (TryGet(i, out floatValue))
                {
                    tsb.Append(floatValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Int:
                int intValue;
                if (TryGet(i, out intValue))
                {
                    tsb.Append(intValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Char:
                char charValue;
                if (TryGet(i, out charValue))
                {
                    tsb.Append("'"); tsb.Append(charValue); tsb.Append("'");
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Color:
                Color32 colorValue;
                if (TryGet(i, out colorValue))
                {
                    tsb.Append(colorValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Double:
                double doubleValue;
                if (TryGet(i, out doubleValue))
                {
                    tsb.Append(doubleValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Long:
                long longValue;
                if (TryGet(i, out longValue))
                {
                    tsb.Append(longValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.TimeTag:
                OscTimeTag timeTagValue;
                if (TryGet(i, out timeTagValue))
                {
                    tsb.Append(timeTagValue);
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.String:
                string stringValue = string.Empty;
                if (TryGet(i, ref stringValue))
                {
                    tsb.Append("\""); tsb.Append(stringValue); tsb.Append("\"");
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;

            case OscArgType.Blob:
                byte[] blobValue = null;
                if (TryGet(i, ref blobValue))
                {
                    tsb.Append("Blob["); tsb.Append(blobValue.Length); tsb.Append("]");
                }
                else
                {
                    tsb.Append("ERROR");
                }
                break;
            }
        }

        if (appendNewLineAtEnd)
        {
            tsb.AppendLine();
        }

        if (insertIndex >= 0)
        {
            sb.EnsureCapacity(sb.Length + tsb.Length);
            // It seems to produce a bit less garbage if we insert each char instead of the string.
            for (int i = 0; i < tsb.Length; i++)
            {
                sb.Insert(insertIndex++, tsb[i]);
            }
        }
    }
    public static string GetSid(string username, string domain)
    {
        byte [] Sid = null;
            uint cbSid = 0;
            StringBuilder referencedDomainName = new StringBuilder();
            uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
            SID_NAME_USE sidUse;

            int err = NO_ERROR;
            if (!LookupAccountName(null,username,Sid,ref cbSid,referencedDomainName,ref cchReferencedDomainName,out sidUse))
            {
                err = Marshal.GetLastWin32Error();
                if (err == ERROR_INSUFFICIENT_BUFFER)
                {
                    Sid = new byte[cbSid];
                    referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                    err = NO_ERROR;
                    if (!LookupAccountName(null,username,Sid,ref cbSid,referencedDomainName,ref cchReferencedDomainName,out sidUse))
                        err = Marshal.GetLastWin32Error();
                }
            }
            if (err == 0)
            {
                IntPtr ptrSid;
                if (!ConvertSidToStringSid(Sid,out ptrSid))
                {
                    err = Marshal.GetLastWin32Error();
                    return(null);
                }
                else
                {
                    string sidString = Marshal.PtrToStringAuto(ptrSid);
                    LocalFree(ptrSid);
                    return(sidString);
                }
            }
            else
                return(null);
    }
Esempio n. 35
0
        private object ReadCollection(DbType dbType, BinaryReader reader, StringBuilder stringBuilder)
        {
            var itemCount = RowData.Read7BitEncodedInt(reader);

            switch (dbType)
            {
            //case DbType.VarNumeric:
            //    break;
            case DbType.AnsiString:
            case DbType.String:
            case DbType.AnsiStringFixedLength:
            case DbType.StringFixedLength:
            case DbType.Xml:
            {
                var result = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                for (var x = 0; x < itemCount; x++)
                {
                    var len = RowData.Read7BitEncodedInt(reader);
                    if (len > 0)
                    {
                        stringBuilder.Clear();
                        stringBuilder.EnsureCapacity(len);
                        for (var i = 0; i < len; i++)
                        {
                            stringBuilder.Append((char)RowData.Read7BitEncodedInt(reader));
                        }
                        result.Add(stringBuilder.ToString());
                    }
                    else if (len >= -1)
                    {
                        // client supplies -1 to indicate that collection element is null
                        // ignore ReSharper's warning about notnull, no exception here

                        // ReSharper disable AssignNullToNotNullAttribute
                        result.Add(len == 0 ? string.Empty : null);
                        // ReSharper restore AssignNullToNotNullAttribute
                    }
                    else
                    {
                        throw new Exception("Invalid length value: " + len);
                    }
                }
                return(result);
            }

            case DbType.Binary:
            case DbType.Object:
            {
                var result = new HashSet <SizableArrayOfByte>(SizableArrayOfByte.DefaultComparer.Instance);

                for (var x = 0; x < itemCount; x++)
                {
                    var len = RowData.Read7BitEncodedInt(reader);
                    if (len >= 0)
                    {
                        var data = new SizableArrayOfByte();
                        data.SetLength(len);
                        var bytesRead = 0;
                        while (bytesRead < data.Length)
                        {
                            var count = reader.Read(data.Data, bytesRead, data.Length - bytesRead);
                            if (count == 0)
                            {
                                throw new DataException("Unexpected end of stream");
                            }
                            bytesRead += count;
                        }

                        result.Add(data);
                    }
                    else if (len == -1)
                    {
                        // client supplies -1 to indicate that collection element is null
                        // ignore ReSharper's warning about notnull, no exception here

                        // ReSharper disable AssignNullToNotNullAttribute
                        result.Add(null);
                        // ReSharper restore AssignNullToNotNullAttribute
                    }
                    else
                    {
                        throw new Exception("Invalid length value: " + len);
                    }
                }
                return(result);
            }

            case DbType.SByte:
            {
                var result = new HashSet <SByte>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add((sbyte)reader.ReadByte());
                }
                return(result);
            }

            case DbType.Byte:
            {
                var result = new HashSet <Byte>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadByte());
                }
                return(result);
            }

            case DbType.Boolean:
            {
                var result = new HashSet <bool>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadBoolean());
                }
                return(result);
            }

            case DbType.Decimal:
            case DbType.Currency:
            {
                var result = new HashSet <Decimal>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadDecimal());
                }
                return(result);
            }

            case DbType.Guid:
            {
                var result = new HashSet <Guid>();
                for (var x = 0; x < itemCount; x++)
                {
                    var buf = new DriverRowData.ValueHolder16Bytes {
                        Lo = reader.ReadInt64(), Hi = reader.ReadInt64()
                    };
                    result.Add(buf.AsGuid);
                }
                return(result);
            }

            case DbType.DateTimeOffset:
            {
                var result = new HashSet <DateTimeOffset>();
                for (var x = 0; x < itemCount; x++)
                {
                    var buf = new DriverRowData.ValueHolder16Bytes {
                        Lo = reader.ReadInt64(), Hi = reader.ReadInt64()
                    };
                    result.Add(buf.AsDateTimeOffset);
                }
                return(result);
            }

            case DbType.Int16:
            {
                var result = new HashSet <Int16>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadInt16());
                }
                return(result);
            }

            case DbType.UInt16:
            {
                var result = new HashSet <UInt16>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadUInt16());
                }
                return(result);
            }

            case DbType.Int32:
            {
                var result = new HashSet <Int32>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadInt32());
                }
                return(result);
            }

            case DbType.UInt32:
            {
                var result = new HashSet <UInt32>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadUInt32());
                }
                return(result);
            }

            case DbType.Single:
            {
                var result = new HashSet <Single>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadSingle());
                }
                return(result);
            }

            case DbType.Date:
            case DbType.DateTime:
            case DbType.DateTime2:
            {
                var result = new HashSet <DateTime>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(DateTime.FromBinary(reader.ReadInt64()));
                }
                return(result);
            }

            case DbType.Time:
            {
                var result = new HashSet <TimeSpan>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(new TimeSpan(reader.ReadInt64()));
                }
                return(result);
            }

            case DbType.Int64:
            {
                var result = new HashSet <Int64>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadInt64());
                }
                return(result);
            }

            case DbType.UInt64:
            {
                var result = new HashSet <UInt64>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadUInt64());
                }
                return(result);
            }

            case DbType.Double:
            {
                var result = new HashSet <Double>();
                for (var x = 0; x < itemCount; x++)
                {
                    result.Add(reader.ReadDouble());
                }
                return(result);
            }

            default:
                throw new DataException("Invalid DbType: " + dbType);
            }
        }
Esempio n. 36
0
        private void ReadPrimitiveValue(DriverRowData rowData, int ordinal, BinaryReader reader, StringBuilder stringBuilder)
        {
            var indexInArray = rowData.FieldArrayIndexes[ordinal];

            switch (rowData.FieldTypes[ordinal])
            {
            //case DbType.VarNumeric:
            //    break;
            case DbType.AnsiString:
            case DbType.String:
            case DbType.AnsiStringFixedLength:
            case DbType.StringFixedLength:
            case DbType.Xml:
            {
                var len = RowData.Read7BitEncodedInt(reader);
                if (len > 0)
                {
                    stringBuilder.Clear();
                    stringBuilder.EnsureCapacity(len);
                    for (var i = 0; i < len; i++)
                    {
                        stringBuilder.Append((char)RowData.Read7BitEncodedInt(reader));
                    }
                    rowData.StringData[indexInArray] = stringBuilder.ToString();
                }
                else
                {
                    rowData.StringData[indexInArray] = string.Empty;
                }
            }
            break;

            case DbType.Binary:
            case DbType.Object:
            {
                var data = rowData.BinaryData[indexInArray];
                data.SetLength(RowData.Read7BitEncodedInt(reader));
                var bytesRead = 0;
                while (bytesRead < data.Length)
                {
                    var count = reader.Read(data.Data, bytesRead, data.Length - bytesRead);
                    if (count == 0)
                    {
                        throw new DataException("Unexpected end of stream");
                    }
                    bytesRead += count;
                }
            }
            break;

            case DbType.SByte:
            case DbType.Byte:
                rowData.ValueData8Bytes[indexInArray].AsByte = reader.ReadByte();
                break;

            case DbType.Boolean:
                rowData.ValueData8Bytes[indexInArray].AsBoolean = reader.ReadBoolean();
                break;

            case DbType.Decimal:
            case DbType.Currency:
            case DbType.Guid:
            case DbType.DateTimeOffset:
                rowData.ValueData16Bytes[indexInArray].Lo = reader.ReadInt64();
                rowData.ValueData16Bytes[indexInArray].Hi = reader.ReadInt64();
                break;

            case DbType.Int16:
            case DbType.UInt16:
                rowData.ValueData8Bytes[indexInArray].AsInt16 = reader.ReadInt16();
                break;

            case DbType.Int32:
            case DbType.UInt32:
            case DbType.Single:
                rowData.ValueData8Bytes[indexInArray].AsInt32 = reader.ReadInt32();
                break;

            case DbType.Date:
            case DbType.DateTime:
            case DbType.DateTime2:
            case DbType.Time:
            case DbType.Int64:
            case DbType.UInt64:
            case DbType.Double:
                rowData.ValueData8Bytes[indexInArray].AsInt64 = reader.ReadInt64();
                break;

            default:
                throw new DataException("Invalid DbType: " + rowData.FieldTypes[ordinal]);
            }
        }
Esempio n. 37
0
        public static string EliminateForbiddenFileNameCharacters(string str)
        {
            //StringBuilder strBuilder = new StringBuilder(str.Length);
#if NET40
            m_StrBuilder.Clear();
#else
            m_StrBuilder.Length = 0;
#endif //NET40
            m_StrBuilder.EnsureCapacity(str.Length);

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

                if (c == Path.DirectorySeparatorChar ||
                    c == Path.AltDirectorySeparatorChar ||
                    c == '/' ||
                    c == '\\')
                {
                    m_StrBuilder.Append(UNDERSCORE);
                }
                else if (c == ':' ||
                         c == '*' ||
                         c == '?' ||
                         c == '<' ||
                         c == '>' ||
                         c == '|' ||
                         c == '\"' ||
                         c == '\'' ||
                         c == ','
                         )
                {
                    m_StrBuilder.Append(HYPHEN);
                }
                else
                {
                    bool added = false;
                    foreach (char cc in INVALID_CHARS)
                    {
                        if (c == cc)
                        {
                            m_StrBuilder.Append(UNDERSCORE);
                            added = true;
                            break;
                        }
                    }
                    if (!added)
                    {
                        if (c == '.'
                            &&
                            (
                                m_StrBuilder.Length == 0
                                ||
                                m_StrBuilder[m_StrBuilder.Length - 1] == '.'
                            )
                            )
                        {
                            //let's avoid two consecutive dots, or dot at begining of filename
                            bool debug = true;
                        }
                        else
                        {
                            m_StrBuilder.Append(c);
                        }
                    }
                }
            }

            return(m_StrBuilder.ToString());
        }