EnsureCapacity() public method

public EnsureCapacity ( int capacity ) : int
capacity int
return int
Example #1
0
 public static StringBuilder AppendEscapedJson(StringBuilder builder, string value)
 {
   if (value == null) return builder;
   builder.EnsureCapacity(builder.Length + value.Length + 5);
   for (var i = 0; i < value.Length; i++)
   {
     switch (value[i])
     {
       case '\t':
         builder.Append(@"\t");
         break;
       case '\n':
         builder.Append(@"\n");
         break;
       case '\r':
         builder.Append(@"\r");
         break;
       case '"':
         builder.Append(@"\""");
         break;
       case '\\':
         builder.Append(@"\\");
         break;
       default:
         builder.Append(value[i]);
         break;
     }
   }
   return builder;
 }
        public static unsafe string GetUsername(this SecurityIdentifier securityIdentifier, string systemName = null)
        {
            var name = new StringBuilder();
            uint nameSize = (uint)name.Capacity;
            var domain = new StringBuilder();
            uint domainSize = (uint)domain.Capacity;
            SidNameUse use;

            fixed (void* ptr = GetBinaryForm(securityIdentifier))
            {
                var sid = new IntPtr(ptr);

                if (NativeMethods.LookupAccountSid(systemName, sid, name, ref nameSize, domain, ref domainSize, out use))
                {
                    return name.ToString();
                }

                var error = (SystemErrorCode)Marshal.GetLastWin32Error();
                if (error != SystemErrorCode.ErrorInsufficientBuffer)
                {
                    throw ErrorHelper.GetWin32Exception(error);
                }

                name.EnsureCapacity((int)nameSize);
                domain.EnsureCapacity((int)domainSize);
                if (!NativeMethods.LookupAccountSid(systemName, sid, name, ref nameSize, domain, ref domainSize, out use))
                {
                    throw ErrorHelper.GetWin32Exception();
                }
            }

            return name.ToString();
        }
Example #3
0
        public static char[] GetDriveLetters(string driveName)
        {
            List<char> results = new List<char>();

            StringBuilder sb = new StringBuilder(128);
            for (char ch = 'A'; ch < 'Z'; ch++)
            {
                uint result;
                do
                {
                    result = QueryDosDevice(ch + ":", sb, (uint)sb.Capacity);

                    if (result == 122)
                        sb.EnsureCapacity(sb.Capacity * 2);
                } while (result == 122);

                // Contains target?
                string[] drives = sb.ToString().Split('\0');

                if (drives.Any(s => s.Equals(driveName, StringComparison.InvariantCultureIgnoreCase)))
                    results.Add(ch);
            }

            return results.ToArray();
        }
Example #4
0
 public static string GetCompactPath(this FileSystemInfo info, int newWidth, Font drawFont)
 {
     using (Control ctrl = new Control())
        {
     Graphics g = ctrl.CreateGraphics();
     string longPath = info.FullName;
     int width = g.MeasureString(longPath, drawFont).ToSize().Width;
     if (width <= newWidth)
      return longPath;
     int aveCharWidth = width / longPath.Length;
     int charCount = newWidth / aveCharWidth;
     StringBuilder builder = new StringBuilder();
     builder.Append(longPath);
     builder.EnsureCapacity(charCount);
     while (g.MeasureString(builder.ToString(), drawFont).Width > newWidth)
     {
      if (!NativeMethods.PathCompactPathEx(builder, longPath,
       (uint)charCount--, 0))
      {
       return string.Empty;
      }
     }
     return builder.ToString();
        }
 }
 private string GetClassName(IntPtr hwnd)
 {
     StringBuilder sb = new StringBuilder();
     sb.EnsureCapacity(1024);
     Interop.GetClassName(hwnd, sb, sb.Capacity);
     return sb.ToString();
 }
Example #6
0
        /// <summary>
        /// Resolves A Specified LUID Value Into The Apropriate Windows Privilege
        /// </summary>
        public static String GetPrivilegeName(Win32API.LUID luid)
        {
            try
            {
                StringBuilder _PrivilegeName = new StringBuilder();

                //hold the length of the LuID Struct
                Int32 _NameLength = 0;

                //first method call is to get the _NameLength so we can allocate a buffer
                Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength);

                //make sure there is sufficient space in memory
                _PrivilegeName.EnsureCapacity(_NameLength);

                //look up the privilage name
                if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength))
                {
                    return _PrivilegeName.ToString();
                }//if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength))
            }
            catch (Exception)
            {
                Console.WriteLine("## ERROR ## - Problem Getting Privilege Name!\nWin32 Error: '{0}', LUID '{1}'", Marshal.GetLastWin32Error(), luid);
            }//end of try-catch

            //default catch all
            return String.Empty;
        }
Example #7
0
        /// <summary>
        /// Returns the version string and language string in the format that the installer
        /// expects to find them in the database.  If you just want version information, set
        /// lpLangBuf and pcchLangBuf to zero. If you just want language information, set
        /// lpVersionBuf and pcchVersionBuf to zero.
        /// </summary>
        /// <param name="filePath">Specifies the path to the file.</param>
        /// <param name="version">Returns the file version. Set to 0 for language information only.</param>
        /// <param name="language">Returns the file language. Set to 0 for version information only.</param>
        public static void FileVersion(string filePath, out string version, out string language)
        {
            int versionLength = 20;
            int languageLength = 20;
            StringBuilder versionBuffer = new StringBuilder(versionLength);
            StringBuilder languageBuffer = new StringBuilder(languageLength);

            uint er = MsiInterop.MsiGetFileVersion(filePath, versionBuffer, ref versionLength, languageBuffer, ref languageLength);
            if (234 == er)
            {
                versionBuffer.EnsureCapacity(++versionLength);
                languageBuffer.EnsureCapacity(++languageLength);
                er = MsiInterop.MsiGetFileVersion(filePath, versionBuffer, ref versionLength, languageBuffer, ref languageLength);
            }
            else if (1006 == er)
            {
                er = 0;   // file has no version or language, so no error
            }

            if (0 != er)
            {
                throw new System.Runtime.InteropServices.ExternalException(String.Format("Unknown error while getting version of file: {0}, system error: {1}", filePath, er));
            }

            version = versionBuffer.ToString();
            language = languageBuffer.ToString();
        }
        /* 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);

            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('"');
            }
        }
Example #9
0
        public MainWindow()
        {
            InitializeComponent();

            Output = new StringBuilder();
            Output.EnsureCapacity(MAX_CAPACITY);
            LastKnownFileName = "";
            Calculator = gcalc.gcalc_create();
            Title = string.Format("gkalk {0}", AppVersion.Get());
        }
        public void StringStringBuilder(string inArg, StringBuilder outArg)
        {
            // ɾ��ԭ������
            outArg.Remove(0, outArg.Length);

            // ȷ��StringBuilder���������㹻������
            outArg.EnsureCapacity(inArg.Length + "_�����(StringBuilder)".Length);

            outArg.Append(inArg);
            outArg.Append("_�����(StringBuilder)");
        }
        public override void Decode(Asn1BerDecodeBuffer buffer, bool explicitTagging, int implicitLength)
        {
            var elemLength = explicitTagging ? MatchTag(buffer, Tag) : implicitLength;
            var len = elemLength;
            var sb = new StringBuilder();

            var lastTag = buffer.LastTag;

            if ((lastTag == null) || !lastTag.Constructed)
            {
                sb.EnsureCapacity(elemLength / 2);
                ReadSegment(buffer, sb, len);
            }
            else
            {
                var capacity = 0;
                var context = new Asn1BerDecodeContext(buffer, elemLength);

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

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

                    capacity += num3;
                    sb.EnsureCapacity(capacity);
                    ReadSegment(buffer, sb, num3);
                }

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

            Value = sb.ToString();
            buffer.TypeCode = BmpStringTypeCode;
        }
Example #12
0
        public static void Main()
        {
            File.WriteAllText("steam_appid.txt", "630");

            Steamworks.Load(true);

            ISteamClient006 steamclient = Steamworks.CreateInterface<ISteamClient006>();

            int pipe = steamclient.CreateSteamPipe();
            int user = steamclient.ConnectToGlobalUser(pipe); // steamclient.CreateLocalUser(ref pipe); // steamclient.ConnectToGlobalUser(pipe);

            ISteamUser004 steamuser = steamclient.GetISteamUser<ISteamUser004>(user, pipe);


            ISteam003 steam003 = Steamworks.CreateSteamInterface<ISteam003>();

            StringBuilder version = new StringBuilder();
            version.EnsureCapacity(256);

            steam003.GetVersion(version);

            TSteamError error = new TSteamError();
            uint sz = 0;
            StringBuilder email = new StringBuilder();
            email.EnsureCapacity(256);

            steam003.GetCurrentEmailAddress(email, ref sz, ref error);

            CSteamID steamid = steamuser.GetSteamID();

            ISteamFriends003 friends = steamclient.GetISteamFriends<ISteamFriends003>(user, pipe);
            ISteamFriends002 friends2 = steamclient.GetISteamFriends<ISteamFriends002>(user, pipe);

            int num = friends.GetFriendCount(EFriendFlags.k_EFriendFlagAll);
            for (int i = 0; i < num; i++)
            {
                CSteamID id = friends.GetFriendByIndex(i, EFriendFlags.k_EFriendFlagAll);
                string name = friends.GetFriendPersonaName(id);

                if (name == "Stan")
                {
                    byte[] buff = Encoding.ASCII.GetBytes("Oidy.");
                    friends2.SendMsgToFriend(id, EChatEntryType.k_EChatEntryTypeChatMsg, buff);
                }

                Debug.WriteLine(name);
            }
             
        }
Example #13
0
		/// <summary>
		/// Quotes the string.
		/// </summary>
		/// <param name="s">The s.</param>
		/// <param name="quoteChar">The quote char.</param>
		/// <param name="sb">The sb.</param>
		internal static void QuoteString(string s, char quoteChar, StringBuilder sb)
		{
			if (s == null || (s.Length == 1 && s[0] == '\0'))
			{
				sb.Append(new String(quoteChar, 2));
				return;
			}

			char c;
			int len = s.Length;

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

			sb.Append(quoteChar);

			for (int i = 0; i < len; i++)
			{
				c = s[i];
				switch (c)
				{
					case '\\': sb.Append("\\\\"); break;
					case '\b': sb.Append("\\b"); break;
					case '\t': sb.Append("\\t"); break;
					case '\r': sb.Append("\\r"); break;
					case '\n': sb.Append("\\n"); break;
					case '\f': sb.Append("\\f"); break;
					default:
						if (c < ' ')
						{
							sb.Append("\\u");
							sb.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));

						}
						else if (c == quoteChar)
						{
							sb.Append("\\");
							sb.Append(c);
						}
						else
						{
							sb.Append(c);
						}
						break;
				}
			}

			sb.Append(quoteChar);
		}
Example #14
0
 static void Main(String[] args)
 {
     int numCases = int.Parse(Console.ReadLine());
     for (int i = 0; i < numCases; i++)
     {
         string first = Console.ReadLine();
         string second = Console.ReadLine();
         int current1 = 0;
         int current2 = 0;
         StringBuilder output = new StringBuilder();
         output.EnsureCapacity(first.Length + second.Length);
         while (current1 < first.Length && current2 < second.Length)
         {
             if (first[current1] < second[current2])
             {
                 output.Append(first[current1]);
                 current1++;
             }
             else if (first[current1] > second[current2])
             {
                 output.Append(second[current2]);
                 current2++;
             }
             else
             {
                 if (first.Substring(current1).CompareTo(second.Substring(current2)) < 0 )
                 {
                     output.Append(first[current1]);
                     current1++;
                 }
                 else
                 {
                     output.Append(second[current2]);
                     current2++;
                 }
             }
         }
         if (current1 < first.Length)
         {
             output.Append(first.Substring(current1));
         }
         else
         {
             output.Append(second.Substring(current2));
         }
         Console.WriteLine(output);
     }
 }
		/// <summary>
		///   Retrieves the multilingual string associated with the specified name. Returns null if the name/value pair does not exist in the registry.
		///   The key must have been opened using 
		/// </summary>
		/// <param name = "key">The registry key to load the string from.</param>
		/// <param name = "name">The name of the string to load.</param>
		/// <returns>The language-specific string, or null if the name/value pair does not exist in the registry.</returns>
		public static string LoadMuiStringValue( this RegistryKey key, string name )
		{
			const int initialBufferSize = 1024;
			var output = new StringBuilder( initialBufferSize );
			int requiredSize;
			IntPtr keyHandle = key.Handle.DangerousGetHandle();
			ErrorCode result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null );

			if ( result == ErrorCode.MoreData )
			{
				output.EnsureCapacity( requiredSize );
				result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null );
			}

			return result == ErrorCode.Success ? output.ToString() : null;
		}
		public static void SetFileLength(SafeFileHandle fileHandle, long length)
		{
			var lo = (int)(length & 0xffffffff);
			var hi = (int)(length >> 32);

			int lastError;

			if (SetFilePointer(fileHandle, lo, out hi, Win32NativeFileMoveMethod.Begin) == -1)
			{
				lastError = Marshal.GetLastWin32Error();
				if (lastError != 0)
					throw new Win32Exception(lastError);
			}

			if (SetEndOfFile(fileHandle) == false)
			{
				lastError = Marshal.GetLastWin32Error();

				if (lastError == (int) Win32NativeFileErrors.ERROR_DISK_FULL)
				{
					var filePath = new StringBuilder(256);

					while (GetFinalPathNameByHandle(fileHandle, filePath, filePath.Capacity, 0) > filePath.Capacity && 
						filePath.Capacity < 32767) // max unicode path length
					{
					    filePath.EnsureCapacity(filePath.Capacity*2);
					}

					filePath = filePath.Replace(@"\\?\", string.Empty); // remove extended-length path prefix

					var fullFilePath = filePath.ToString();
					var driveLetter = Path.GetPathRoot(fullFilePath);
					var driveInfo = new DriveInfo(driveLetter);

					throw new DiskFullException(driveInfo, fullFilePath, length);
				}

				var exception = new Win32Exception(lastError);

				if (lastError == (int) Win32NativeFileErrors.ERROR_NOT_READY || lastError == (int) Win32NativeFileErrors.ERROR_FILE_NOT_FOUND)
					throw new VoronUnrecoverableErrorException("Could not set the file size because it is inaccessible", exception);

				throw exception;
			}
		}
Example #17
0
	public static string _hexdump(WvBytes b)
	{
	    if (b.bytes == null)
		return "(nil)";
	    
            var sb = new StringBuilder();
	    
	    // This is overly complicated so that the body and header of
	    // the same buffer can be printed separately yet still show the
	    // proper alignment
 	    
	    int rowoffset = b.start & (~0xf);
	    
            // Note: it's important to set the right capacity when dealing 
            // with large quantities of data.  Assume about 80 chars per line.
            sb.EnsureCapacity((b.len / 16 + 2) * 80);

	    for (int i = rowoffset; i < b.len; i += 16)
	    {
		sb.Append('[').Append(i.ToString("x4")).Append("]");
		
		for (int j = 0; j < 16; j++)
		{
		    if ((j % 4)==0)
			sb.Append(' ');
		    sb.Append(hexbyte(b, i+j));
		}
		
		sb.Append(' ');
		
		for (int j = 0; j < 16; j++)
		{
		    if ((j % 4)==0)
			sb.Append(' ');
		    sb.Append(printable(b, i+j));
		}
		
		sb.Append('\n');
	    }
	
	    return sb.ToString();
	}
Example #18
0
        public static string ByteArrayToHexDump( byte[] aBytes , int aBytesPerLine = 16 , string aSplitter = " | " )
        {
            //<8 bytes address><aSplitter><aBytesPerLine's hex with (aBytesPerLine - 1)'s space><aSplitter><aBytesPerLine's ascii>
            int nOneLineSize = 8 + aSplitter.Length * 2 + aBytesPerLine * 4 - 1 + Environment.NewLine.Length;
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.EnsureCapacity( (int)Math.Ceiling((double)aBytes.Length/(double)aBytesPerLine) * nOneLineSize );
            for ( int i = 0 ; i < aBytes.Length ; i += aBytesPerLine )
            {
                strBuilder.AppendFormat( "{0:X8}{1}" , i , aSplitter );
                for ( int j = 0 ; j < aBytesPerLine ; j++ )
                {
                    int nCurr = i + j;
                    if ( nCurr >= aBytes.Length )
                    {
                        strBuilder.Append( ' ' , (aBytesPerLine - j) * 3 - 1 );
                        break;
                    }
                    var val = m_lookup32[aBytes[nCurr]];
                    strBuilder.Append( (char)val );
                    strBuilder.Append( (char)(val >> 16) );
                    if ( j + 1 < aBytesPerLine )
                    {
                        strBuilder.Append( ' ' );
                    }
                }

                strBuilder.Append( aSplitter );

                for ( int j = 0 ; j < aBytesPerLine ; j++ )
                {
                    int nCurr = i + j;
                    if ( nCurr >= aBytes.Length )
                    {
                        strBuilder.Append( ' ' , aBytesPerLine - j );
                        break;
                    }
                    strBuilder.Append( char.IsControl((char)aBytes[nCurr]) ? '.' : (char)aBytes[nCurr] );
                }
                strBuilder.AppendLine();
            }
            return strBuilder.ToString();
        }
Example #19
0
        public static string Serialize(Object target, bool prettyPrint)
        {
            StringBuilder sbSerialized = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();

            js.Serialize(target, sbSerialized);

            if (prettyPrint)
            {
                StringBuilder prettyPrintedResult = new StringBuilder();
                prettyPrintedResult.EnsureCapacity(sbSerialized.Length);

                JsonPrettyPrinter pp = new JsonPrettyPrinter();
                pp.PrettyPrint(sbSerialized, prettyPrintedResult);

                return prettyPrintedResult.ToString();
            }
            else
                return sbSerialized.ToString();
        }
Example #20
0
		public static void SetFileLength(SafeFileHandle fileHandle, long length)
		{
			var lo = (int)(length & 0xffffffff);
			var hi = (int)(length >> 32);

			int lastError;

			if (SetFilePointer(fileHandle, lo, out hi, Win32NativeFileMoveMethod.Begin) == -1)
			{
				lastError = Marshal.GetLastWin32Error();
				if (lastError != 0)
					throw new Win32Exception(lastError);
			}

			if (SetEndOfFile(fileHandle) == false)
			{
				lastError = Marshal.GetLastWin32Error();

				if (lastError == (int) Win32NativeFileErrors.DiskFull)
				{
					var filePath = new StringBuilder(256);

					while (GetFinalPathNameByHandle(fileHandle, filePath, filePath.Capacity, 0) > filePath.Capacity && 
						filePath.Capacity < 32767) // max unicode path length
					{
					    filePath.EnsureCapacity(filePath.Capacity*2);
					}

					filePath = filePath.Replace(@"\\?\", string.Empty); // remove extended-length path prefix

					var fullFilePath = filePath.ToString();
					var driveLetter = Path.GetPathRoot(fullFilePath);
					var driveInfo = new DriveInfo(driveLetter);

					throw new DiskFullException(driveInfo, fullFilePath, length);
				}

				throw new Win32Exception(lastError);
			}
		}
Example #21
0
        /// <summary>
        /// Searches for the given account name and returns the SID associated with that account.  Local machine accounts are searched first, then the primary domain, then trusted domains.  Using fully-qualified account names is highly recommended, but not required.
        /// </summary>
        /// <param name="AccountName">A string value containing the account name to search for.</param>
        /// <returns>A string value containing the SID for the specified account, or an error msg if the SID could not be retrieved.</returns>
        public static string GetUserSid(string AccountName)
        {
            byte[] Sid = null;
            uint cbSid = 0;
            StringBuilder refDomainName = new StringBuilder();
            uint cchRefDomainName = (uint)refDomainName.Capacity;
            SID_NAME_USE sidUse;

            int err = ERROR_SUCCESS;
            if (!LookupAccountName(null, AccountName, Sid, ref cbSid, refDomainName, ref cchRefDomainName, out sidUse))
            {
                err = Marshal.GetLastWin32Error();
                if (err == ERROR_INSUFFICIENT_BUFFER)
                {
                    Sid = new byte[cbSid];
                    refDomainName.EnsureCapacity((int)cchRefDomainName);
                    err = ERROR_SUCCESS;
                    if (!LookupAccountName(null, AccountName, Sid, ref cbSid, refDomainName, ref cchRefDomainName, out sidUse))
                        err = Marshal.GetLastWin32Error();
                }
            }
            if (err == 0)
            {
                IntPtr ptrSid;
                if (!ConvertSidToStringSid(Sid, out ptrSid))
                {
                    err = Marshal.GetLastWin32Error();
                    return "Could not convert SID to string. Error : " + err.ToString();
                }
                else
                {
                    string sidString = Marshal.PtrToStringAuto(ptrSid);
                    LocalFree(ptrSid);
                    return sidString;
                }
            }
            else
                return "Error : " + err.ToString();
        }
 /// <summary>
 /// Gets the set of installed components for products in the indicated context.
 /// </summary>
 /// <exception cref="InstallerException">The installer configuration data is corrupt</exception>
 /// <remarks><p>
 /// Win32 MSI API:
 /// <a href="http://msdn.microsoft.com/library/dd407947.aspx">MsiEnumComponentsEx</a>
 /// </p></remarks>
 public static IEnumerable<ComponentInstallation> Components(string szUserSid, UserContexts dwContext)
 {
     uint pcchSid = 32;
     StringBuilder szSid = new StringBuilder((int)pcchSid);
     StringBuilder buf = new StringBuilder(40);
     UserContexts installedContext;
     for (uint i = 0; true; i++)
     {
         uint  ret = NativeMethods.MsiEnumComponentsEx(szUserSid, dwContext, i, buf, out installedContext, szSid, ref pcchSid);
         if (ret == (uint) NativeMethods.Error.MORE_DATA)
         {
             szSid.EnsureCapacity((int) ++pcchSid);
             ret = NativeMethods.MsiEnumComponentsEx(szUserSid, dwContext, i, buf, out installedContext, szSid, ref pcchSid);
         }
         if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) break;
         if (ret != 0)
         {
             throw InstallerException.ExceptionFromReturnCode(ret);
         }
         yield return new ComponentInstallation(buf.ToString(), szSid.ToString(), installedContext);
     }
 }
Example #23
0
        /// <summary>
        /// Show the icon picker dialog.
        /// </summary>
        /// <param name="owner">Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.</param>
        /// <returns>DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel.</returns>
        public DialogResult ShowDialog(IWin32Window owner)
        {
            if (this.IconFile == null || this.iconIndex == -1)
            {
                throw new ArgumentException("The icon file or index has not yet been specified.");
            }

            int tempIconIndex = this.iconIndex;
            StringBuilder iconFileBuffer = new StringBuilder(String.Empty);
            iconFileBuffer.EnsureCapacity(2048);

            if (NativeMethods.PickIconDlg(owner.Handle, iconFileBuffer, iconFileBuffer.Capacity, ref tempIconIndex) != 0)
            {
                string tempIconFile = Environment.ExpandEnvironmentVariables(iconFileBuffer.ToString());

                IntPtr iconHandle = NativeMethods.ExtractIconW(Process.GetCurrentProcess().Handle, tempIconFile, tempIconIndex);
                if (iconHandle == IntPtr.Zero || iconHandle.ToInt32() == 1)
                {
                    throw new ApplicationException(String.Format("Cannot load icon from '{0}' with index {1}.", tempIconFile, tempIconIndex));
                }

                // hack to ensure the icon handle is properly freed
                Icon tempIcon = Icon.FromHandle(iconHandle);
                this.icon = (Icon)tempIcon.Clone();
                tempIcon.Dispose();
                NativeMethods.DestroyIcon(iconHandle);

                // save the new values
                this.iconFile = tempIconFile;
                this.iconIndex = tempIconIndex;

                return DialogResult.OK;
            }
            else
            {
                return DialogResult.Cancel;
            }
        }
        public static string GetUserName(this Process targetProcess)
        {
            string userName = String.Empty;

            var name = new StringBuilder();
            uint cchName = (uint)name.Capacity;

            StringBuilder referencedDomainName = new StringBuilder();
            uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;

            NativeMethods.SidNameUse sidUse;
            byte[] sid = GetProcessSidBytes(targetProcess);
            if (sid == null)
            {
                userName = "unknown";
            }
            else
            {
                if (!NativeMethods.LookupAccountSid(null, sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    if (errorCode == NativeMethods.Constants.ERROR_INSUFFICIENT_BUFFER)
                    {
                        name.EnsureCapacity((int)cchName);
                        referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                        if (!NativeMethods.LookupAccountSid(null, sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                        {
                            throw new Win32Exception();
                        }
                    }
                }

                userName = name.ToString();
            }

            return userName;
        }
Example #25
0
File: Sid.cs Project: vokac/F2B
        public static SecurityIdentifier Get(string accountName)
        {
            Log.Info("GetSid(" + accountName + ")");

            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, accountName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))
            {
                err = Marshal.GetLastWin32Error();
                if (err == ERROR_INSUFFICIENT_BUFFER || err == ERROR_INVALID_FLAGS)
                {
                    Sid = new byte[cbSid];
                    referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                    err = NO_ERROR;
                    if (!LookupAccountName(null, accountName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                        err = Marshal.GetLastWin32Error();
                }
            }
            else
            {
                throw new InvalidOperationException("Unable to find SID for account " + accountName + " (errno=" + err + ")");
            }
            if (err == NO_ERROR)
            {
                return new SecurityIdentifier(Sid, 0);
            }
            else
            {
                throw new InvalidOperationException("Unable to find SID for account " + accountName + " (errno=" + err + ")");
            }
        }
        public static string GetModuleFileName(IntPtr hModule)
        {
            var buffer = new StringBuilder((int)Win32Value.MAX_PATH);
            while (true)
            {
                int size = _GetModuleFileName(hModule, buffer, buffer.Capacity);
                if (size == 0)
                {
                    HRESULT.ThrowLastError();
                }

                // GetModuleFileName returns nSize when it's truncated but does NOT set the last error.
                // MSDN documentation says this has changed in Windows 2000+.
                if (size == buffer.Capacity)
                {
                    // Enlarge the buffer and try again.
                    buffer.EnsureCapacity(buffer.Capacity * 2);
                    continue;
                }

                return buffer.ToString();
            }
        }
Example #27
0
        // Returns a CLRRuntimeInfo for the runtime that the specified binary
        // will run against.
        public CLRRuntimeInfo GetRequestedRuntime(MetaHostPolicyFlags flags,
                                                    String binaryPath,
                                                    String configPath,
                                                    ref StringBuilder version,
                                                    ref StringBuilder imageVersion)
        {
            IStream configStream = null;

            if (configPath != null)
            {
                try
                {
                    NativeMethods.SHCreateStreamOnFileEx(configPath,
                                                        NativeMethods.Stgm.StgmRead,
                                                        0,      // We're not creating a file, so no flags needed.
                                                        false,  // Do NOT create a new file.
                                                        IntPtr.Zero,
                                                        out configStream);
                }
                catch (EntryPointNotFoundException)
                {
                    // Fall back on the older method.
                    NativeMethods.SHCreateStreamOnFile(configPath,
                                                        NativeMethods.Stgm.StgmRead,
                                                        out configStream);
                }
            }

            // In case they're empty.
            version.EnsureCapacity(MaxVersionStringLength);
            uint versionCapacity = System.Convert.ToUInt32(version.Capacity);
            imageVersion.EnsureCapacity(MaxVersionStringLength);
            uint imageVersionCapacity = System.Convert.ToUInt32(imageVersion.Capacity);


            Guid ifaceId = typeof(ICLRRuntimeInfo).GUID;
            uint configFlags;
            object o = m_MHPolicy.GetRequestedRuntime(flags,
                                                        binaryPath,
                                                        configStream,
                                                        version,
                                                        ref versionCapacity,
                                                        imageVersion,
                                                        ref imageVersionCapacity,
                                                        out configFlags,
                                                        ref ifaceId);

            return new CLRRuntimeInfo(o);
        }
Example #28
0
		/// <summary>
		///		If there is a message in GL info log then post it in the Axiom Log
		/// </summary>
		/// <param name="message">The info log message string is appended to this string.</param>
		/// <param name="handle">The GL object handle that is used to retrieve the info log</param>
		/// <returns></returns>
		public static string LogObjectInfo( string message, int handle )
		{
			StringBuilder logMessage = new StringBuilder();

			if ( handle > 0 )
			{
				int infologLength = 0;

				Gl.glGetObjectParameterivARB( handle, Gl.GL_OBJECT_INFO_LOG_LENGTH_ARB, out infologLength );

				if ( infologLength > 0 )
				{
					int charsWritten = 0;

				    logMessage.EnsureCapacity( infologLength + 1 );
					Gl.glGetInfoLogARB( handle, infologLength, out charsWritten, logMessage );
					if ( charsWritten > 0 )
					{
						logMessage.Append( "\n" );
						message += "\n" + logMessage.ToString();
					}
					LogManager.Instance.Write( message );
				}
			}

			return logMessage.ToString();

		}
Example #29
0
        public void Refresh()
        {
            StringBuilder sb = new StringBuilder();

            // get caption
            sb.EnsureCapacity(10240);

            bool WindowTimedOut = false;

            UIntPtr lRes = new UIntPtr(1860);
            int lResult = SendMessageTimeout(Handle, WM_GETTEXT, 10240, sb, SMTO_ABORTIFHUNG, 1000, out lRes);
            if (lResult == 0)
            {
                Trace.TraceError("SendMessageTimeout() failed with {0}", Marshal.GetLastWin32Error());
                WindowTimedOut = true;
                Objects[(int)WindowItemTypes.Title] = "?";
            }
            else
            {
                //Trace.TraceInformation("lResult: {0}, lRes: {1}", lResult, lRes.ToUInt32());
                Objects[(int)WindowItemTypes.Title] = sb.ToString();
            }

            // get class name
            sb = new StringBuilder();
            sb.EnsureCapacity(10240);
            GetClassName(Handle, sb, 10240);
            Objects[(int)WindowItemTypes.Class] = sb.ToString();

            uint style = GetWindowLong(Handle, GWL_STYLE);
            Objects[(int)WindowItemTypes.Style] = DecodeWindowStyle(style);
            Objects[(int)WindowItemTypes.ExStyle] = GetWindowLong(Handle, GWL_EXSTYLE);
            Objects[(int)WindowItemTypes.ID] = GetWindowLong(Handle, GWL_ID);

            RECT r = new RECT();
            GetWindowRect(Handle, ref r);

            Objects[(int)WindowItemTypes.Size] = string.Format("({0}, {1})", r.Width, r.Height);
            Objects[(int)WindowItemTypes.Position] = string.Format("({0}, {1})", r.Top, r.Left);

            UIntPtr ProcessID = new UIntPtr(0);
            uint ThreadID = GetWindowThreadProcessId(Handle, out ProcessID);
            Objects[(int)WindowItemTypes.TID] = ThreadID;
            Objects[(int)WindowItemTypes.PID] = ProcessID.ToUInt32();

            ForegroundColor = Color.Black;
            if ((r.Width == r.Height) && (r.Width == 0))
            {
                ForegroundColor = Color.Gray;
            }
            if ((style & WS_VISIBLE) == 0)
            {
                ForegroundColor = Color.Gray;
            }
            if (WindowTimedOut)
            {
                ForegroundColor = Color.Red;
            }
        }
Example #30
0
        static IEnumerable<Tuple<string, ICLRRuntimeInfo>> GetCLRRuntimeInfos(Process process)
        {
            var clsid = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE");
            var riid = typeof(ICLRMetaHost).GUID;
            var mh = (ICLRMetaHost)NativeMethods.CLRCreateInstance(ref clsid, ref riid);

            IEnumUnknown iter;
            int hr = mh.EnumerateLoadedRuntimes(process.Handle, out iter);
            if (hr < 0)
                yield break;
            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);

                yield return Tuple.Create(sb.ToString(), rtInfo);
            }
        }