public void Initialize()
        {
            //
            // Attach to any existing consoles we have
            // failing that, create a new one.
            //
            if ( !AttachConsole( 0x0ffffffff ) )
            {
                AllocConsole();
            }

            oldOutput = Console.Out;

            try
            {
                IntPtr stdHandle = GetStdHandle( STD_OUTPUT_HANDLE );
                Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle( stdHandle, true );
                FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
                System.Text.Encoding encoding = System.Text.Encoding.ASCII;
                StreamWriter standardOutput = new StreamWriter( fileStream, encoding );
                standardOutput.AutoFlush = true;
                Console.SetOut( standardOutput );
            }
            catch ( System.Exception e )
            {
                Debug.Log( "Couldn't redirect output: " + e.Message );
            }
        }
Example #2
0
		static void ApplyMOTW(string path)
		{
			int generic_write = 0x40000000;
			int file_share_write = 2;
			int create_always = 2;
			var adsHandle = CreateFileW(path + ":Zone.Identifier", generic_write, file_share_write, 0, create_always, 0, 0);
			using (var sfh = new Microsoft.Win32.SafeHandles.SafeFileHandle(adsHandle, true))
			{
				var adsStream = new System.IO.FileStream(sfh, FileAccess.Write);
				StreamWriter sw = new StreamWriter(adsStream);
				sw.Write("[ZoneTransfer]\r\nZoneId=3");
				sw.Flush();
				adsStream.Close();
			}
		}
Example #3
0
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access) :
     this(handle, access, DefaultBufferSize)
 {
 }
Example #4
0
        private FileStream WindowsCreateFile(string fileName, bool allowConcurrentWrite)
        {
            int fileShare = Win32FileHelper.FILE_SHARE_READ;

            if (allowConcurrentWrite)
                fileShare |= Win32FileHelper.FILE_SHARE_WRITE;

            if (_createParameters.EnableFileDelete && PlatformDetector.GetCurrentRuntimeOS() != RuntimeOS.Windows)
                fileShare |= Win32FileHelper.FILE_SHARE_DELETE;

            IntPtr hFile = Win32FileHelper.CreateFile(
                fileName,
                Win32FileHelper.FileAccess.GenericWrite,
                fileShare,
                IntPtr.Zero,
                Win32FileHelper.CreationDisposition.OpenAlways,
                _createParameters.FileAttributes, IntPtr.Zero);

            if (hFile.ToInt32() == -1)
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

            FileStream returnValue;

#if DOTNET_2_0 || NETCF_2_0
            Microsoft.Win32.SafeHandles.SafeFileHandle safeHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(hFile, true);
            returnValue = new FileStream(safeHandle, FileAccess.Write, _createParameters.BufferSize);
#else
            returnValue = new FileStream(hFile, FileAccess.Write, true, _createParameters.BufferSize);
#endif
            returnValue.Seek(0, SeekOrigin.End);
            return returnValue;
        }
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access)
 {
 }
Example #6
0
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
 {
     this._innerStream = new Win32FileStream(handle, access, bufferSize, isAsync);
 }
        static int __CreateInstance(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
                if (LuaAPI.lua_gettop(L) == 3 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3))
                {
                    string             _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode _mode; translator.Get(L, 3, out _mode);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 4 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.IO.FileAccess>(L, 4))
                {
                    string               _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode   _mode; translator.Get(L, 3, out _mode);
                    System.IO.FileAccess _access; translator.Get(L, 4, out _access);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _access);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 5 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.IO.FileAccess>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5))
                {
                    string               _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode   _mode; translator.Get(L, 3, out _mode);
                    System.IO.FileAccess _access; translator.Get(L, 4, out _access);
                    System.IO.FileShare  _share; translator.Get(L, 5, out _share);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _access, _share);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 6 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.IO.FileAccess>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6))
                {
                    string               _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode   _mode; translator.Get(L, 3, out _mode);
                    System.IO.FileAccess _access; translator.Get(L, 4, out _access);
                    System.IO.FileShare  _share; translator.Get(L, 5, out _share);
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 6);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _access, _share, _bufferSize);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 7 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.IO.FileAccess>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6) && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 7))
                {
                    string               _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode   _mode; translator.Get(L, 3, out _mode);
                    System.IO.FileAccess _access; translator.Get(L, 4, out _access);
                    System.IO.FileShare  _share; translator.Get(L, 5, out _share);
                    int  _bufferSize = LuaAPI.xlua_tointeger(L, 6);
                    bool _useAsync   = LuaAPI.lua_toboolean(L, 7);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _access, _share, _bufferSize, _useAsync);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 7 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.IO.FileAccess>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6) && translator.Assignable <System.IO.FileOptions>(L, 7))
                {
                    string               _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode   _mode; translator.Get(L, 3, out _mode);
                    System.IO.FileAccess _access; translator.Get(L, 4, out _access);
                    System.IO.FileShare  _share; translator.Get(L, 5, out _share);
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 6);
                    System.IO.FileOptions _options; translator.Get(L, 7, out _options);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _access, _share, _bufferSize, _options);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 3 && translator.Assignable <Microsoft.Win32.SafeHandles.SafeFileHandle>(L, 2) && translator.Assignable <System.IO.FileAccess>(L, 3))
                {
                    Microsoft.Win32.SafeHandles.SafeFileHandle _handle = (Microsoft.Win32.SafeHandles.SafeFileHandle)translator.GetObject(L, 2, typeof(Microsoft.Win32.SafeHandles.SafeFileHandle));
                    System.IO.FileAccess _access; translator.Get(L, 3, out _access);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_handle, _access);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 4 && translator.Assignable <Microsoft.Win32.SafeHandles.SafeFileHandle>(L, 2) && translator.Assignable <System.IO.FileAccess>(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4))
                {
                    Microsoft.Win32.SafeHandles.SafeFileHandle _handle = (Microsoft.Win32.SafeHandles.SafeFileHandle)translator.GetObject(L, 2, typeof(Microsoft.Win32.SafeHandles.SafeFileHandle));
                    System.IO.FileAccess _access; translator.Get(L, 3, out _access);
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 4);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_handle, _access, _bufferSize);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 5 && translator.Assignable <Microsoft.Win32.SafeHandles.SafeFileHandle>(L, 2) && translator.Assignable <System.IO.FileAccess>(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4) && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 5))
                {
                    Microsoft.Win32.SafeHandles.SafeFileHandle _handle = (Microsoft.Win32.SafeHandles.SafeFileHandle)translator.GetObject(L, 2, typeof(Microsoft.Win32.SafeHandles.SafeFileHandle));
                    System.IO.FileAccess _access; translator.Get(L, 3, out _access);
                    int  _bufferSize = LuaAPI.xlua_tointeger(L, 4);
                    bool _isAsync    = LuaAPI.lua_toboolean(L, 5);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_handle, _access, _bufferSize, _isAsync);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 7 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.Security.AccessControl.FileSystemRights>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6) && translator.Assignable <System.IO.FileOptions>(L, 7))
                {
                    string             _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode _mode; translator.Get(L, 3, out _mode);
                    System.Security.AccessControl.FileSystemRights _rights; translator.Get(L, 4, out _rights);
                    System.IO.FileShare _share; translator.Get(L, 5, out _share);
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 6);
                    System.IO.FileOptions _options; translator.Get(L, 7, out _options);

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _rights, _share, _bufferSize, _options);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 8 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <System.IO.FileMode>(L, 3) && translator.Assignable <System.Security.AccessControl.FileSystemRights>(L, 4) && translator.Assignable <System.IO.FileShare>(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6) && translator.Assignable <System.IO.FileOptions>(L, 7) && translator.Assignable <System.Security.AccessControl.FileSecurity>(L, 8))
                {
                    string             _path = LuaAPI.lua_tostring(L, 2);
                    System.IO.FileMode _mode; translator.Get(L, 3, out _mode);
                    System.Security.AccessControl.FileSystemRights _rights; translator.Get(L, 4, out _rights);
                    System.IO.FileShare _share; translator.Get(L, 5, out _share);
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 6);
                    System.IO.FileOptions _options; translator.Get(L, 7, out _options);
                    System.Security.AccessControl.FileSecurity _fileSecurity = (System.Security.AccessControl.FileSecurity)translator.GetObject(L, 8, typeof(System.Security.AccessControl.FileSecurity));

                    System.IO.FileStream gen_ret = new System.IO.FileStream(_path, _mode, _rights, _share, _bufferSize, _options, _fileSecurity);
                    translator.Push(L, gen_ret);

                    return(1);
                }
            }
            catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
            return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.FileStream constructor!"));
        }
Example #8
0
 private void Write2File(string outFile, ref byte[] data, FileMode fileMode = FileMode.Append, long pos = 0, long datalen = 0)
 {
     if ((datalen == 0) || (datalen > (data.Length - pos))) datalen = data.Length - pos;
     try {
         if (this.play) {
             Stream stdout = (this.redir2Proc) ? Program.redir2Prog.StandardInput.BaseStream : Console.OpenStandardOutput();
             stdout.Write(data, (int)pos, (int)datalen);
             stdout.Flush();
         } else {
             if (this.pipeWriter == null) {
                 if (usePipe) {
                     if (this.pipeStream != null) this.pipeStream.Close();
                     if (this.pipeHandle != null) this.pipeHandle.Close();
                     this.pipeHandle = NativeMethods.CreateFile(outFile, NativeMethods.GENERIC_WRITE, 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_FLAG_OVERLAPPED, IntPtr.Zero);
                     if (this.pipeHandle.IsInvalid) Program.Quit("<c:Red>Cannot create pipe for writting.");
                     this.pipeStream = new FileStream(this.pipeHandle, FileAccess.Write, 4096, true);
                     this.pipeWriter = new BinaryWriter(this.pipeStream);
                 } else {
                     if (this.pipeStream != null) this.pipeStream.Close();
                     if (this.pipeHandle != null) this.pipeHandle.Close();
                     this.pipeStream = new FileStream(outFile, fileMode);
                     this.pipeWriter = new BinaryWriter(this.pipeStream);
                 }
             }
             this.pipeWriter.Write(data, (int)pos, (int)datalen);
             this.pipeWriter.Flush();
         }
         this.currentFilesize += datalen;
     } catch (Exception e) {
         if (Program.ConsolePresent) {
             Program.DebugLog("Error while writing to file! Message: " + e.Message);
             Program.DebugLog("Exception: " + e.ToString());
             Program.Quit("<c:Red>Error while writing to file! <c:DarkCyan>Message: <c:Magenta>" + e.Message);
         }
     }
 }
        private FileStream WindowsCreateFile(string fileName, bool allowConcurrentWrite)
        {
            int fileShare = Win32FileNativeMethods.FILE_SHARE_READ;

            if (allowConcurrentWrite)
            {
                fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE;
            }

            if (this.CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows)
            {
                fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE;
            }

            IntPtr handle = Win32FileNativeMethods.CreateFile(
                fileName,
                Win32FileNativeMethods.FileAccess.GenericWrite,
                fileShare,
                IntPtr.Zero,
                Win32FileNativeMethods.CreationDisposition.OpenAlways,
                this.CreateFileParameters.FileAttributes, 
                IntPtr.Zero);

            if (handle.ToInt32() == -1)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            var safeHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(handle, true);
            var returnValue = new FileStream(safeHandle, FileAccess.Write, this.CreateFileParameters.BufferSize);
            returnValue.Seek(0, SeekOrigin.End);
            return returnValue;
        }
Example #10
0
        private void ReallyRender()
        {
            var text = ParseInput();

            _codePage        = NativeMethods.GetConsoleOutputCP();
            _istmInitialized = false;
            ConsoleHandle        consoleHandle = _outputHandle.Value;
            CONSOLE_FONT_INFO_EX fontInfo      = GetConsoleFontInfo(consoleHandle);
            int fontType = fontInfo.FontFamily & NativeMethods.FontTypeMask;

            _trueTypeInUse = (fontType & NativeMethods.TrueTypeFont) == NativeMethods.TrueTypeFont;

            int  statusLineCount = GetStatusLineCount();
            int  j = _initialX + (_bufferWidth * Options.ExtraPromptLineCount);
            var  backgroundColor = _initialBackgroundColor;
            var  foregroundColor = _initialForegroundColor;
            bool afterLastToken  = false;
            int  totalBytes      = j;
            int  bufferWidth     = Console.BufferWidth;

            var tokenStack = new Stack <SavedTokenState>();

            tokenStack.Push(new SavedTokenState
            {
                Tokens          = _tokens,
                Index           = 0,
                BackgroundColor = _initialBackgroundColor,
                ForegroundColor = _initialForegroundColor
            });

            int bufferLineCount;

            try
            {
                bufferLineCount = ConvertOffsetToCoordinates(text.Length).Y - _initialY + 1 + statusLineCount;
                if (_consoleBuffer.Length != bufferLineCount * bufferWidth)
                {
                    var newBuffer = new CHAR_INFO[bufferLineCount * bufferWidth];
                    Array.Copy(_consoleBuffer, newBuffer, _initialX + (Options.ExtraPromptLineCount * _bufferWidth));
                    if (_consoleBuffer.Length > bufferLineCount * bufferWidth)
                    {
                        int consoleBufferOffset = ConvertOffsetToConsoleBufferOffset(text.Length, _initialX + (Options.ExtraPromptLineCount * _bufferWidth));
                        // Need to erase the extra lines that we won't draw again
                        for (int i = consoleBufferOffset; i < _consoleBuffer.Length; i++)
                        {
                            _consoleBuffer[i] = _space;
                        }
                        WriteBufferLines(_consoleBuffer, ref _initialY);
                    }
                    _consoleBuffer = newBuffer;
                }

                for (int i = 0; i < text.Length; i++)
                {
                    SavedTokenState state = null;
                    totalBytes = totalBytes % bufferWidth;
                    if (!afterLastToken)
                    {
                        // Figure out the color of the character - if it's in a token,
                        // use the tokens color otherwise use the initial color.
                        state = tokenStack.Peek();
                        var token = state.Tokens[state.Index];
                        if (i == token.Extent.EndOffset)
                        {
                            if (token == state.Tokens[state.Tokens.Length - 1])
                            {
                                tokenStack.Pop();
                                if (tokenStack.Count == 0)
                                {
                                    afterLastToken  = true;
                                    token           = null;
                                    foregroundColor = _initialForegroundColor;
                                    backgroundColor = _initialBackgroundColor;
                                }
                                else
                                {
                                    state = tokenStack.Peek();
                                }
                            }

                            if (!afterLastToken)
                            {
                                foregroundColor = state.ForegroundColor;
                                backgroundColor = state.BackgroundColor;

                                token = state.Tokens[++state.Index];
                            }
                        }

                        if (!afterLastToken && i == token.Extent.StartOffset)
                        {
                            GetTokenColors(token, out foregroundColor, out backgroundColor);

                            var stringToken = token as StringExpandableToken;
                            if (stringToken != null)
                            {
                                // We might have nested tokens.
                                if (stringToken.NestedTokens != null && stringToken.NestedTokens.Any())
                                {
                                    var tokens = new Token[stringToken.NestedTokens.Count + 1];
                                    stringToken.NestedTokens.CopyTo(tokens, 0);
                                    // NestedTokens doesn't have an "EOS" token, so we use
                                    // the string literal token for that purpose.
                                    tokens[tokens.Length - 1] = stringToken;

                                    tokenStack.Push(new SavedTokenState
                                    {
                                        Tokens          = tokens,
                                        Index           = 0,
                                        BackgroundColor = backgroundColor,
                                        ForegroundColor = foregroundColor
                                    });
                                }
                            }
                        }
                    }

                    if (text[i] == '\n')
                    {
                        while ((j % bufferWidth) != 0)
                        {
                            _consoleBuffer[j++] = _space;
                        }

                        for (int k = 0; k < Options.ContinuationPrompt.Length; k++, j++)
                        {
                            _consoleBuffer[j].UnicodeChar     = Options.ContinuationPrompt[k];
                            _consoleBuffer[j].ForegroundColor = Options.ContinuationPromptForegroundColor;
                            _consoleBuffer[j].BackgroundColor = Options.ContinuationPromptBackgroundColor;
                        }
                    }
                    else
                    {
                        int size = LengthInBufferCells(text[i]);
                        totalBytes += size;

                        //if there is no enough space for the character at the edge, fill in spaces at the end and
                        //put the character to next line.
                        int filling = totalBytes > bufferWidth ? (totalBytes - bufferWidth) % size : 0;
                        for (int f = 0; f < filling; f++)
                        {
                            _consoleBuffer[j++] = _space;
                            totalBytes++;
                        }

                        if (char.IsControl(text[i]))
                        {
                            _consoleBuffer[j].UnicodeChar = '^';
                            MaybeEmphasize(ref _consoleBuffer[j++], i, foregroundColor, backgroundColor);
                            _consoleBuffer[j].UnicodeChar = (char)('@' + text[i]);
                            MaybeEmphasize(ref _consoleBuffer[j++], i, foregroundColor, backgroundColor);
                        }
                        else if (size > 1 && IsCJKOutputCodePage() && _trueTypeInUse)
                        {
                            _consoleBuffer[j].UnicodeChar = text[i];
                            _consoleBuffer[j].Attributes  = (ushort)((uint)_consoleBuffer[j].Attributes |
                                                                     (uint)CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE);
                            MaybeEmphasize(ref _consoleBuffer[j++], i, foregroundColor, backgroundColor);
                            _consoleBuffer[j].UnicodeChar = text[i];
                            _consoleBuffer[j].Attributes  = (ushort)((uint)_consoleBuffer[j].Attributes |
                                                                     (uint)CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE);
                            MaybeEmphasize(ref _consoleBuffer[j++], i, foregroundColor, backgroundColor);
                        }
                        else
                        {
                            _consoleBuffer[j].UnicodeChar = text[i];
                            MaybeEmphasize(ref _consoleBuffer[j++], i, foregroundColor, backgroundColor);
                        }
                    }
                }
            }
            finally
            {
                if (_hwnd != (IntPtr)0 && _hDC != (IntPtr)0)
                {
                    NativeMethods.ReleaseDC(_hwnd, _hDC);
                }
            }

            for (; j < (_consoleBuffer.Length - (statusLineCount * _bufferWidth)); j++)
            {
                _consoleBuffer[j] = _space;
            }

            if (_statusLinePrompt != null)
            {
                foregroundColor = _statusIsErrorMessage ? Options.ErrorForegroundColor : Console.ForegroundColor;
                backgroundColor = _statusIsErrorMessage ? Options.ErrorBackgroundColor : Console.BackgroundColor;

                for (int i = 0; i < _statusLinePrompt.Length; i++, j++)
                {
                    _consoleBuffer[j].UnicodeChar     = _statusLinePrompt[i];
                    _consoleBuffer[j].ForegroundColor = foregroundColor;
                    _consoleBuffer[j].BackgroundColor = backgroundColor;
                }
                for (int i = 0; i < _statusBuffer.Length; i++, j++)
                {
                    _consoleBuffer[j].UnicodeChar     = _statusBuffer[i];
                    _consoleBuffer[j].ForegroundColor = foregroundColor;
                    _consoleBuffer[j].BackgroundColor = backgroundColor;
                }

                for (; j < _consoleBuffer.Length; j++)
                {
                    _consoleBuffer[j] = _space;
                }
            }

            bool rendered = false;

            if (_parseErrors.Length > 0)
            {
                int promptChar = _initialX - 1 + (_bufferWidth * Options.ExtraPromptLineCount);

                while (promptChar >= 0)
                {
                    var c = (char)_consoleBuffer[promptChar].UnicodeChar;
                    if (char.IsWhiteSpace(c))
                    {
                        promptChar -= 1;
                        continue;
                    }

                    ConsoleColor prevColor = _consoleBuffer[promptChar].ForegroundColor;
                    _consoleBuffer[promptChar].ForegroundColor = ConsoleColor.Red;
                    WriteBufferLines(_consoleBuffer, ref _initialY);
                    rendered = true;
                    _consoleBuffer[promptChar].ForegroundColor = prevColor;
                    break;
                }
            }

            if (!rendered)
            {
                WriteBufferLines(_consoleBuffer, ref _initialY);
            }

            PlaceCursor();

            if ((_initialY + bufferLineCount) > (Console.WindowTop + Console.WindowHeight))
            {
                Console.WindowTop = _initialY + bufferLineCount - Console.WindowHeight;
            }

            _lastRenderTime.Restart();
        }
Example #11
0
        internal bool Run(string uuid, string mode)
        {
            bool run = false;
            XcDiagProcessInfo xcdiagProcessInfo = GetXcDiagProcessInfo(mode);

            if (xcdiagProcessInfo != null) // If got xcdiag process info
            {
                this.log.Info("Received xcdiag request");
                xcdiagProcessInfo.processStartInfo.CreateNoWindow         = true;
                xcdiagProcessInfo.processStartInfo.ErrorDialog            = false;
                xcdiagProcessInfo.processStartInfo.RedirectStandardError  = true;
                xcdiagProcessInfo.processStartInfo.RedirectStandardOutput = true;
                xcdiagProcessInfo.processStartInfo.UseShellExecute        = false;
                xcdiagProcessInfo.processStartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;

                System.Diagnostics.Process xcdiagProcess = null;
                try
                {
                    xcdiagProcess = System.Diagnostics.Process.Start(xcdiagProcessInfo.processStartInfo);
                    if (xcdiagProcess == null)
                    {
                        log.Info("xcdiag process already running in: \"{0}\"", xcdiagProcessInfo.processStartInfo.FileName);
                    }
                }
                catch (System.IO.FileNotFoundException filenotfoundEx)
                {
                    log.Exception("Cannot launch xcdiag (file not found)", filenotfoundEx);
                }
                catch (System.ObjectDisposedException objdisposedEx)
                {
                    log.Exception("Cannot launch xcdiag (object disposed)", objdisposedEx);
                }
                catch (System.InvalidOperationException invalidopEx)
                {
                    log.Exception("Cannot launch xcdiag (invalid operation)", invalidopEx);
                }
                catch (System.ComponentModel.Win32Exception win32Ex)
                {
                    log.Exception("Cannot launch xcdiag (win32 error)", win32Ex);
                }
                catch (System.Exception ex)
                {
                    log.Exception("Cannot launch xcdiag", ex);
                }

                if (xcdiagProcess != null) // If launched xcdiag
                {
                    // Tends to block until process finishes.
                    string xcdiagError = xcdiagProcess.StandardError.ReadToEnd();
                    if (!string.IsNullOrEmpty(xcdiagError))
                    {
                        log.Error("xcdiag produced error output: {0}", xcdiagError);
                    }

                    xcdiagProcess.WaitForExit();     // Oooooh.

                    if (xcdiagProcess.ExitCode != 0) // If xcdiag reported an error
                    {
                        log.Error("xcdiag exited with error code '{0}'", xcdiagProcess.ExitCode);
                    }    // Ends if xcdiag reported an error
                    else // else xcdiag ran ok
                    {
                        System.Text.StringBuilder dataBuffer = null;
                        // Make a big ol' string containing the data, encoding each byte as 2-digit ASCII hex.
#if MEMORYMAPFILE_SUPPORTED
                        using (System.IO.MemoryMappedFiles.MemoryMappedFile memmapXcDiag = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(xcdiagProcessInfo.xcDiagOutputPath))
#else // !MEMORYMAPFILE_SUPPORTED
                        //// Create a memory mapped view of the zip file
                        //hFile = CreateFileA(szXcDiagOut,
                        //    GENERIC_READ | GENERIC_WRITE,
                        //    0,
                        //    NULL,
                        //    OPEN_EXISTING,
                        //    FILE_ATTRIBUTE_NORMAL,
                        //    NULL);
                        using (Microsoft.Win32.SafeHandles.SafeFileHandle mapHandle = wcf.Native.FileFunctions.CreateFile(xcdiagProcessInfo.xcDiagOutputPath
                                                                                                                          , global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_READ | global::XenClientGuestService.Native.EFileAccess.FILE_GENERIC_WRITE
                                                                                                                          , System.IO.FileShare.None
                                                                                                                          , IntPtr.Zero
                                                                                                                          , System.IO.FileMode.Open
                                                                                                                          , System.IO.FileAttributes.Normal
                                                                                                                          , IntPtr.Zero))
#endif // MEMORYMAPFILE_SUPPORTED
                        {
                            // Finish creating the native mapping, and then work out how to read bytes...
#if MEMORYMAPFILE_SUPPORTED
                            using (System.IO.MemoryMappedFiles.MemoryMappedViewStream streamXcDiag = memmapXcDiag.CreateViewStream())
#else // !MEMORYMAPFILE_SUPPORTED
                            long fileSize = new System.IO.FileInfo(xcdiagProcessInfo.xcDiagOutputPath).Length;
                            //hMapFile = CreateFileMapping(
                            //    hFile,          // current file handle
                            //    NULL,           // default security
                            //    PAGE_READWRITE, // read/write permission
                            //    0,              // size of mapping object, high
                            //    filesize,       // size of mapping object, low
                            //    NULL);          // name of mapping object
                            using (Microsoft.Win32.SafeHandles.SafeFileHandle xcDiagOutputMappingHandle = wcf.Native.MappingFunctions.CreateFileMapping(mapHandle
                                                                                                                                                        , IntPtr.Zero
                                                                                                                                                        , global::XenClientGuestService.Native.FileMapProtection.PageReadWrite
                                                                                                                                                        , 0
                                                                                                                                                        , checked ((uint)fileSize)
                                                                                                                                                        , null))
#endif // MEMORYMAPFILE_SUPPORTED
                            {
#if MEMORYMAPFILE_SUPPORTED
                                long fileSize = streamXcDiag.Length;
#else // !MEMORYMAPFILE_SUPPORTED
                                //// Map the view
                                //lpMapAddress = (unsigned char *)MapViewOfFile(
                                //    hMapFile,			 // handle to mapping object
                                //    FILE_MAP_ALL_ACCESS, // read/write
                                //    0,                   // high-order 32 bits of file offset
                                //    0,                   // low-order 32 bits of file offset
                                //    filesize);           // number of bytes to map
                                using (wcf.Native.FileMappingViewHandle mappingViewHandler = wcf.Native.MappingFunctions.MapViewOfFile(xcDiagOutputMappingHandle
                                                                                                                                       , global::XenClientGuestService.Native.FileMapAccess.FileMapAllAccess
                                                                                                                                       , 0
                                                                                                                                       , 0
                                                                                                                                       , (checked ((UInt32)fileSize))))
#endif // !MEMORYMAPFILE_SUPPORTED
                                {
#if MEMORYMAPFILE_SUPPORTED
                                    System.IO.BinaryReader reader = new System.IO.BinaryReader(streamXcDiag);
#else // !MEMORYMAPFILE_SUPPORTED
                                    wcf.Native.FileMappingViewHandle.ViewReader reader = mappingViewHandler.CreateViewReader();
#endif // !MEMORYMAPFILE_SUPPORTED
                                    int resultSize = checked ((int)(fileSize * 2));
                                    dataBuffer = new StringBuilder(resultSize, resultSize);
                                    for (int byteIter = 0; byteIter < fileSize; ++byteIter)
                                    {
                                        byte b = reader.ReadByte();
                                        dataBuffer.Append(b.ToString("x2"));
                                    } // Ends loop over bytes
                                }     // Ends using map view handle
                            }         // Ends using Memory Map view
                        }             // Ends using Memory Map file

                        string data        = dataBuffer.ToString();
                        byte[] stringBytes = System.Text.Encoding.Default.GetBytes(data);
                        byte[] asciiBytes  = System.Text.ASCIIEncoding.Convert(Encoding.Default, Encoding.ASCII, stringBytes);
                        data = System.Text.Encoding.ASCII.GetString(asciiBytes);
                        Gather(uuid, data);
                    } // Ends else xcdiag ran ok
                }     // Ends if launched xcdiag
            }         // Ends if got xcdiag process info

            return(run);
        }
Example #12
0
 internal static extern int iaxc_set_files(Microsoft.Win32.SafeHandles.SafeFileHandle input, Microsoft.Win32.SafeHandles.SafeFileHandle output);
Example #13
0
 public TerminalInputBuffer(TerminalEmulator Terminal, Microsoft.Win32.SafeHandles.SafeFileHandle Handle)
     : base(Handle)
 {
     BaseTerminal = Terminal;
 }
 public static extern int NtOpenDirectoryObject(
     out Microsoft.Win32.SafeHandles.SafeFileHandle DirectoryHandle,
     uint DesiredAccess,
     ref OBJECT_ATTRIBUTES ObjectAttributes);
Example #15
0
 private void WriteData(byte[] data, FileMode fileMode = FileMode.Append)
 {
     try {
         if (usePipe)
         {
             // write to named pipe
             if (Writer == null)
             {
                 if (Stream != null)
                 {
                     Stream.Close();
                 }
                 if (pipeHandle != null)
                 {
                     pipeHandle.Close();
                 }
                 pipeHandle = NativeMethods.CreateFile(outFile, NativeMethods.GENERIC_WRITE, 0, IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_FLAG_OVERLAPPED, IntPtr.Zero);
                 if (pipeHandle.IsInvalid)
                 {
                     throw new InvalidOperationException("Can not open an existing pipe for writting.");
                 }
                 Stream = new FileStream(pipeHandle, FileAccess.Write, 4096, true);
                 Writer = new BinaryWriter(Stream);
             }
             Writer.Write(data, 0, data.Length);
             Writer.Flush();
         }
         else if (Program.redir2Prog != null)
         {
             // write to standart input of redirected process
             if (Program.redir2Prog.HasExited)
             {
                 throw new InvalidOperationException("Redirected process was exited");
             }
             Stream stream = Program.redir2Prog.StandardInput.BaseStream;
             if (stream == System.IO.Stream.Null)
             {
                 throw new InvalidOperationException("Redirected process was exited");
             }
             stream.Write(data, 0, data.Length);
             stream.Flush();
         }
         else if (play || Program.isRedirected)
         {
             // write to standart output
             Stream stdout = Console.OpenStandardOutput();
             if (stdout == System.IO.Stream.Null)
             {
                 throw new InvalidOperationException("Redirected process was exited");
             }
             stdout.Write(data, 0, data.Length);
             stdout.Flush();
         }
         else
         {
             // write in file
             if (Writer == null)
             {
                 if (Stream != null)
                 {
                     Stream.Close();
                 }
                 if (pipeHandle != null)
                 {
                     pipeHandle.Close();
                 }
                 Stream = new FileStream(Program.outDir + outFile, fileMode);
                 Writer = new BinaryWriter(Stream);
             }
             Writer.Write(data, 0, data.Length);
             Writer.Flush();
         }
         Filesize += (uint)data.Length;
     } catch (Exception e) {
         Program.DebugLog("Error while writing to file! Message: " + e.Message);
         Program.DebugLog("Exception: " + e.ToString());
         throw;
     }
 }
Example #16
0
 public static extern bool GetFileTime(
     Microsoft.Win32.SafeHandles.SafeFileHandle hFile,
     out long lpCreationTime,
     out long lpLastAccessTime,
     out long lpLastWriteTime
     );
Example #17
0
 static extern int FlushFileBuffers(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle);
Example #18
0
        private static void Main(string[] args)
        {
            // Quit if already running https://stackoverflow.com/a/6392264
            System.Threading.Mutex mutex = new System.Threading.Mutex(false, ProductName);
            var runBenchmark             = false;
            var runHashTest = false;

            try
            {
                if (mutex.WaitOne(0, false))
                {
                    if (args != null && args.Length > 0)
                    {
                        for (var i = 0; i < args.Length; i++)
                        {
                            var s = args[i];
                            if (s == "--debug")
                            {
                                // Throw everything inside a new console window. This code works.
                                AllocConsole();
                                System.IntPtr stdHandle = GetStdHandle(StdOutputHandle);
                                Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
                                System.IO.FileStream   fileStream     = new System.IO.FileStream(safeFileHandle, System.IO.FileAccess.Write);
                                System.Text.Encoding   encoding       = System.Text.Encoding.GetEncoding(MyCodePage);
                                System.IO.StreamWriter standardOutput = new System.IO.StreamWriter(fileStream, encoding)
                                {
                                    AutoFlush = true
                                };
                                System.Console.SetOut(standardOutput);
                            }
                            if (s == "--benchmark")
                            {
                                runBenchmark = true;
                            }
                            if (s == "--test")
                            {
                                runHashTest = true;
                            }
                        }
                    }
                    if (!runBenchmark)
                    {
                        // Show the system tray icon.
                        System.Windows.Forms.Application.EnableVisualStyles();

                        System.Timers.Timer aTimer = new System.Timers.Timer();
                        aTimer.Elapsed += OnTimedEvent;
                        aTimer.Interval = 1000 * 7200; // 120 minutes
                        aTimer.Enabled  = true;

                        // Put the icon in the system tray
                        STrayIcon.Icon    = Properties.Resources.HatSync;
                        STrayIcon.Text    = "HatSync";
                        STrayIcon.Visible = true;

                        // Run once at startup
                        IPUpdater.Init();

                        // Attach a context menu.
                        MenuGenerator.RegenerateMenu();

                        if (runHashTest)
                        {
                            //==============================================================
                            // TEST Hash a file. The value should always be the same
                            // otherwise something went wrong with the implementation.

                            // Create dummy file
                            const string data = "Hello, world!";
                            const string name = "test.bin";
                            System.IO.File.WriteAllText(name, data);
                            // Hash it
                            UniqueFile result = new UniqueFile(name);
                            Log.WriteLine("Hash of test file: " + result.GetHashAsString());

                            if (result.GetHashAsString() == "B5DA441CFE72AE042EF4D2B17742907F675DE4DA57462D4C3609C2E2ED755970")
                            {
                                Log.WriteLine("Test Sucessful");
                            }
                            else
                            {
                                Log.WriteLine("Shit.");
                            }

                            if (System.IO.File.Exists(name))
                            {
                                System.IO.File.Delete(name);
                            }
                        }

                        System.Windows.Forms.Application.Run();
                    }
#if USE_BENCHMARKDOTNET
                    else
                    {
                        BenchmarkDotNet.Running.BenchmarkRunner.Run <Md5VsSha256VsBlake2>();
                    }
#endif
                }
            }
            finally
            {
                mutex.Close();
                mutex = null;
            }
        }
Example #19
0
 private static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out ByHandleFileInformation fileInformation);
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access)
 {
     Contract.Requires(handle != null);
 }
Example #21
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue) {
                if (disposing) {
                    pipeWriter.Close();
                    pipeStream.Close();
                    if (!pipeHandle.IsClosed)
                        pipeHandle.Close();
                }
                pipeStream = null;
                pipeWriter = null;
                pipeHandle = null;

                disposedValue = true;
            }
        }
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
 {
     Contract.Requires(handle != null);
 }
Example #23
0
 /// <summary>
 /// Creates a stream to the current drive
 /// </summary>
 /// <returns>Stream for the current drive</returns>
 public System.IO.Stream Stream()
 {
     // Else, try closing the stream, then re-create it, and return it
     if (thisStream == null || IsClosed)
     {
         switch (DriveType)
         {
             case DriveType.Backup:
                 thisStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open);
                 break;
             case DriveType.HardDisk:
                 DeviceHandle = VariousFunctions.CreateHandle(DeviceIndex);
                 thisStream = new System.IO.FileStream(DeviceHandle, System.IO.FileAccess.ReadWrite);
                 break;
             case DriveType.USB:
                 thisStream = new Streams.USBStream(USBPaths, System.IO.FileMode.Open);
                 break;
         }
     }
     return thisStream;
 }
Example #24
0
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access, int bufferSize)
 {
     _innerStream = new Win32FileStream(handle, access, bufferSize, this);
 }
Example #25
0
 static extern bool GetFileInformationByHandle(SafeFileHandle handle, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access, int bufferSize)
 {
 }
Example #27
0
 public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync)
 {
 }
Example #28
0
 internal static extern IntPtr CreateFileMapping(Microsoft.Win32.SafeHandles.SafeFileHandle hFile, IntPtr lpAttributes,
                                                 uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
Example #29
0
 internal static extern bool UnlockFileEx(Microsoft.Win32.SafeHandles.SafeFileHandle handle, uint reserved, uint countLow, uint countHigh, ref System.Threading.NativeOverlapped overlapped);
 public void CallPInvoke_GetError_valid()
 {
     SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle ((IntPtr)0, true);
     MessageBeep (5);
     IntPtr a = IntPtr.Zero;
     IntPtr b = IntPtr.Zero;
     if (a == b)
         return;
     if (handle.IsInvalid)
         return;
     Marshal.GetLastWin32Error ();
 }
Example #31
0
        internal void TrackStdOutput(Microsoft.Win32.SafeHandles.SafeFileHandle outputPipe, Microsoft.Win32.SafeHandles.SafeFileHandle errorPipe)
        {
            Thread outputReader = new Thread(delegate()
            {
                ReadOutput(outputPipe, false);
            });

            outputReader.Name         = "Debugger output reader";
            outputReader.IsBackground = true;
            outputReader.Start();

            Thread errorReader = new Thread(delegate()
            {
                ReadOutput(outputPipe, true);
            });

            errorReader.Name         = "Debugger error reader";
            errorReader.IsBackground = true;
            errorReader.Start();
        }
Example #32
0
 internal static extern uint NtOpenFile(out Microsoft.Win32.SafeHandles.SafeFileHandle handle, UInt32 access, ref OBJECT_ATTRIBUTES objectAttributes, out IO_STATUS_BLOCK ioStatus, System.IO.FileShare share, uint openOptions);
        private void ReadScriptContents()
        {
            if (_scriptContents == null)
            {
                // make sure we can actually load the script and that it's non-empty
                // before we call it.

                // Note, although we are passing ASCII as the encoding, the StreamReader
                // class still obeys the byte order marks at the beginning of the file
                // if present. If not present, then ASCII is used as the default encoding.

                try
                {
                    using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read))
                    {
                        Encoding defaultEncoding = ClrFacade.GetDefaultEncoding();
                        Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle;

                        using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding))
                        {
                            _scriptContents   = scriptReader.ReadToEnd();
                            _originalEncoding = scriptReader.CurrentEncoding;

                            // Check if this came from a trusted path. If so, set its language mode to FullLanguage.
                            if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None)
                            {
                                SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle);
                                if (scriptSpecificPolicy != SystemEnforcementMode.Enforce)
                                {
                                    this.DefiningLanguageMode = PSLanguageMode.FullLanguage;
                                }
                                else
                                {
                                    this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage;
                                }
                            }
                            else
                            {
                                if (this.Context != null)
                                {
                                    this.DefiningLanguageMode = this.Context.LanguageMode;
                                }
                            }
                        }
                    }
                }
                catch (ArgumentException e)
                {
                    // This catches PSArgumentException as well.
                    ThrowCommandNotFoundException(e);
                }
                catch (IOException e)
                {
                    ThrowCommandNotFoundException(e);
                }
                catch (NotSupportedException e)
                {
                    ThrowCommandNotFoundException(e);
                }
                catch (UnauthorizedAccessException e)
                {
                    // this is unadvertised exception thrown by the StreamReader ctor when
                    // no permission to read the script file
                    ThrowCommandNotFoundException(e);
                }
            }
        }
Example #34
0
        /// <summary>
        /// Tries to fetch the console that created this process or creates a new one if the parent process has no 
        /// console.   Returns true if a NEW console has been created.  
        /// </summary>
        internal static bool CreateConsole()
        {
            bool newConsoleCreated = false;
            // TODO AttachConsole is not reliable (GetStdHandle returns an invalid handle about half the time)
            // So I have given up on it.
            AllocConsole();
            newConsoleCreated = true;

            IntPtr stdHandle = GetStdHandle(-11);       // Get STDOUT
            var safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
            Thread.Sleep(100);
            FileStream fileStream;
            try
            {
                fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            }
            catch (System.IO.IOException)
            {
                return false;       // This will simply fail.
            }

            var encoding = System.Text.Encoding.GetEncoding(437);   // MSDOS Code page.
            StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
            s_threadToInterrupt = Thread.CurrentThread;

            Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate(object sender, ConsoleCancelEventArgs e)
            {
                if (Interlocked.CompareExchange(ref s_controlCPressed, 1, 0) == 0)
                {
                    Console.WriteLine("Control C Pressed.  Aborting.");
                    if (s_threadToInterrupt != null)
                    {
                        s_threadToInterrupt.Interrupt();
                        Thread.Sleep(30000);
                        Console.WriteLine("Thread did not die after 30 seconds.  Killing process.");
                    }
                    Environment.Exit(-20);
                }
                e.Cancel = true;
            });

            return newConsoleCreated;
        }
Example #35
0
 private static extern bool GetFileInformationByHandle(
     Microsoft.Win32.SafeHandles.SafeFileHandle hFile,
     out BY_HANDLE_FILE_INFORMATION lpFileInformation
     );
Example #36
0
 internal static extern int /*HRESULT*/ CreateDecoderFromFileHandle(
     IntPtr pICodecFactory,
     Microsoft.Win32.SafeHandles.SafeFileHandle /*ULONG_PTR*/ hFileHandle,
     ref Guid guidVendor,
     UInt32 metadataFlags,
     out IntPtr /* IWICBitmapDecoder */ ppIDecode);
Example #37
0
        public static Stream waitForFileAccess(string filePath, FileAccess access, int timeoutMs,
            CancellationToken token)
        {
            IntPtr fHandle;
            int errorCode;
            DateTime start = DateTime.Now;

            uint desiredAccess = (uint)CreateFileAccess.GENERIC_READ;
            int fileShare = (int)CreateFileShare.FILE_SHARE_READ;

            if (access == FileAccess.Write || access == FileAccess.ReadWrite)
            {

                desiredAccess |= (int)CreateFileAccess.GENERIC_WRITE;
                fileShare = (int)CreateFileShare.NONE;
            }

            int creationDisposition = (int)CreateFileCreationDisposition.OPEN_EXISTING;
            int fileAttributes = (int)(CreateFileAttributes.NORMAL | CreateFileAttributes.FILE_FLAG_RANDOM_ACCESS);

            while (true)
            {

                fHandle = CreateFileW(filePath, desiredAccess, fileShare, IntPtr.Zero,
                    creationDisposition, fileAttributes, IntPtr.Zero);

                errorCode = Marshal.GetLastWin32Error();

                if (fHandle != IntPtr.Zero && fHandle.ToInt64() != -1L)
                {
                    Microsoft.Win32.SafeHandles.SafeFileHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(fHandle, true);

                    return new FileStream(handle, access);
                }

                if (errorCode != ERROR_SHARING_VIOLATION)
                {
                    Win32Exception e = new System.ComponentModel.Win32Exception(errorCode);

                    throw new IOException(e.Message, errorCode);
                }
                else if (timeoutMs >= 0 && (DateTime.Now - start).TotalMilliseconds > timeoutMs)
                {
                    throw new TimeoutException("Timed out waiting for file access: " + filePath);
                }
                else if (token != null && token.IsCancellationRequested == true) {

                    return(null);
                }

                Thread.Sleep(100);
            }
           
        }
        private static bool showConsole     = false; //Or false if you don't want to see the console

        static void Main(string[] args)
        {
            string[] requiredArgs = new string[] { "username", "password", "host", "port", "node", "vm", "viewer" };
            var      parsedArgs   = args.Select(s => s.Split('=')).ToDictionary(s => s[0], s => s[1]);

            if (parsedArgs.ContainsKey("debug"))
            {
                if (parsedArgs["debug"] == "on")
                {
                    showConsole = true;
                }
            }

            if (showConsole)
            {
                AllocConsole();
                IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
                Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
                FileStream           fileStream     = new FileStream(safeFileHandle, FileAccess.Write);
                System.Text.Encoding encoding       = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
                StreamWriter         standardOutput = new StreamWriter(fileStream, encoding);
                standardOutput.AutoFlush = true;
                Console.SetOut(standardOutput);
            }


            foreach (var requried in requiredArgs)
            {
                if (!parsedArgs.ContainsKey(requried))
                {
                    Console.WriteLine("missing argument : " + requried);
                    Console.ReadLine();
                    return;
                }
            }

            string Username     = parsedArgs["username"];
            string Password     = parsedArgs["password"];
            string Host         = parsedArgs["host"];
            int    Port         = Convert.ToInt32(parsedArgs["port"]);
            string Node         = parsedArgs["node"];
            string VmId         = parsedArgs["vm"];
            string RemoteViewer = parsedArgs["viewer"];

            ProxmoxAPI aAPI = new ProxmoxAPI();

            aAPI.Username = Username;
            aAPI.Password = Password;
            aAPI.Host     = Host;
            aAPI.Port     = Port;

            try
            {
                string Ticket = aAPI.RefreshTicket();
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed to get ticket : " + ex.Message);
                Console.ReadLine();
                return;
            }

            string SpiceCommand = "";

            try
            {
                SpiceCommand = aAPI.GetSpiceCommand(Node, VmId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed to get spice command : " + ex.Message);
                Console.ReadLine();
                return;
            }

            string FileName = "";

            try
            {
                FileName = Path.GetTempFileName();
                System.IO.File.WriteAllText(FileName, SpiceCommand);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed to get write temp file : " + ex.Message);
                Console.ReadLine();
                return;
            }

            try
            {
                Process.Start(RemoteViewer, FileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed to start remote viewer : " + ex.Message);
                Console.ReadLine();
                return;
            }
        }