예제 #1
0
    public Example_19()
    {
        try {

            FileStream fos = new FileStream("Example_19.pdf", FileMode.Create);
            BufferedStream bos = new BufferedStream(fos);

            PDF pdf = new PDF( bos );

            FileStream fis = new FileStream( "Example_03.pdf", FileMode.Open );

            // FileInputStream fis = new FileInputStream( "PDF32000_2008.pdf" );

            BufferedStream bis = new BufferedStream( fis );
            List< PDFobj > objects = pdf.read(bis);
            for ( int j = 0; j < objects.Count; j++ ) {
                PDFobj obj = ( PDFobj ) objects[j];
                for ( int i = 0; i < obj.dict.Count; i++ ) {
                    Console.WriteLine(obj.dict[i]);
                }
                Console.WriteLine();
            }
            bis.Close();

            pdf.Flush();
            bos.Close();
        }
        catch ( Exception e ) {
            Console.WriteLine(e.StackTrace);
        }
    }
    /**
       	 * Writes a file from the contents of a String
       	 * @param filename The name of the file.
       	 * @return The String to write to the file.
       	 */
    public static void writeFile(string filename, string contents)
    {
        FileStream fs = null;
        BufferedStream bs = null;
        StreamWriter sw = null;

        try
        {
            fs = new FileStream(filename, FileMode.Open);

            // Here BufferedInputStream is added for fast writing.
            bs = new BufferedStream(fs);
            sw = new StreamWriter(bs);
            sw.Write(contents);

            // dispose all the resources after using them.
            fs.Close();
            bs.Close();
            sw.Close();
        }

        catch (FileNotFoundException e)
        {
            System.Console.WriteLine(e.ToString());
        }

        catch (IOException e)
        {
            System.Console.WriteLine(e.ToString());
        }
    }
예제 #3
0
        public async Task ShouldNotFlushUnderlyingStreamIfReadOnly(bool underlyingCanSeek)
        {
            var underlying = new DelegateStream(
                canReadFunc: () => true,
                canWriteFunc: () => false,
                canSeekFunc: () => underlyingCanSeek,
                readFunc: (_, __, ___) => 123,
                writeFunc: (_, __, ___) =>
                {
                    throw new NotSupportedException();
                },
                seekFunc: (_, __) => 123L
            );

            var wrapper = new CallTrackingStream(underlying);

            var buffered = new BufferedStream(wrapper);
            buffered.ReadByte();

            buffered.Flush();
            Assert.Equal(0, wrapper.TimesCalled(nameof(wrapper.Flush)));

            await buffered.FlushAsync();
            Assert.Equal(0, wrapper.TimesCalled(nameof(wrapper.FlushAsync)));
        }
예제 #4
0
    public static void Main()
    {
        var bs = new BufferedStream(Console.OpenStandardInput());
        StreamReader reader = new StreamReader(bs);
        Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

        string[] ss = reader.ReadLine().Split();
        double t = double.Parse(ss[0]);

        List<int> w = reader.ReadLine().Split().Select(x => int.Parse(x)).OrderBy(x => x).ToList();
        int res = max_cuts + 47, left = int.Parse(ss[1]);
        foreach (int q in w)
        {
            for (int i = 1; i <= max_cuts; i++)
            {
                double big = q / (double)i;
                var cut = w.Select(x => new {Count = Math.Ceiling(x / big), Length = x});
                if (cut.Min(y => y.Length / y.Count) >= t * big)
                {
                    double cnt = cut.Sum(y => y.Count - 1);
                    if (cnt < res) res = (int)cnt;
                }
            }
            left--;
        }
        Console.WriteLine(res);
    }
예제 #5
0
        public void TestBuffering(long length, int internalBufferCount, int clientBufferCount)
        {
            var random = new Random();
            var remoteData = new byte[length];
            random.NextBytes(remoteData);
            var buffer = new byte[clientBufferCount];
            var clientData = new List<byte>();
            Func<long, byte[], int> reader = (remoteOffset, buff) =>
            {
                int toRead = Math.Min(buff.Length, (int)(length - remoteOffset));
                Buffer.BlockCopy(remoteData, (int) remoteOffset, buff, 0, toRead);
                return  toRead;
            };
            var bufferedStream = new BufferedStream(length, reader, internalBufferCount);
            while (true)
            {
                int read = bufferedStream.Read(buffer, 0, buffer.Length);
                clientData.AddRange(buffer.Take(read));
                if(read==0)
                    break;
                
            }

            Assert.Equal(remoteData, clientData);
        }
예제 #6
0
 protected string invokeGetRequest(string requestUrl, string contentType)
 {
     string completeUrl = requestUrl;
     string responseString;
     try
     {
         HttpWebRequest request1 = WebRequest.Create(completeUrl) as HttpWebRequest;
         request1.ContentType = contentType;
         request1.Method = @"GET";
         HttpWebResponse httpWebResponse = (HttpWebResponse)request1.GetResponse();
         using (BufferedStream buffer = new BufferedStream(httpWebResponse.GetResponseStream()))
         {
             using (StreamReader reader = new StreamReader(buffer))
             {
                 responseString = reader.ReadToEnd();
             }
         }
         //StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream());
         //string responseString = reader.ReadToEnd();
         return responseString;
     }
     catch (WebException ex)
     {
         //reading the custom messages sent by the server
         using (var reader = new StreamReader(ex.Response.GetResponseStream()))
         {
             return reader.ReadToEnd();
         }
     }
     catch (Exception ex)
     {
         return "Failed with exception message:" + ex.Message;
     }
 }
예제 #7
0
        public async Task ShouldAlwaysFlushUnderlyingStreamIfWritable(bool underlyingCanRead, bool underlyingCanSeek)
        {
            var underlying = new DelegateStream(
                canReadFunc: () => underlyingCanRead,
                canWriteFunc: () => true,
                canSeekFunc: () => underlyingCanSeek,
                readFunc: (_, __, ___) => 123,
                writeFunc: (_, __, ___) => { },
                seekFunc: (_, __) => 123L
            );

            var wrapper = new CallTrackingStream(underlying);

            var buffered = new BufferedStream(wrapper);
            
            buffered.Flush();
            Assert.Equal(1, wrapper.TimesCalled(nameof(wrapper.Flush)));

            await buffered.FlushAsync();
            Assert.Equal(1, wrapper.TimesCalled(nameof(wrapper.FlushAsync)));

            buffered.WriteByte(0);
            
            buffered.Flush();
            Assert.Equal(2, wrapper.TimesCalled(nameof(wrapper.Flush)));

            await buffered.FlushAsync();
            Assert.Equal(2, wrapper.TimesCalled(nameof(wrapper.FlushAsync)));
        }
예제 #8
0
 static void Main(string[] args)
 {
     using (FileStream fs = new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         using (BufferedStream bs = new BufferedStream(fs))
         {
             using (StreamReader _in = new StreamReader(bs))
             {
                 using (StreamWriter _out = new StreamWriter(output))
                 {
                     string line;
                     while ((line = _in.ReadLine()) != null)
                     {
                         if (wholeWordOnly)
                         {
                             _out.WriteLine(Regex.Replace(line, @"\bstart\b", "finish"));
                         }
                         else
                         {
                             _out.WriteLine(line.Replace("start", "finish"));
                         }
                     }
                 }
             }
         }
     }
 }
 public static void SetPositionToNegativeValue_Throws_ArgumentOutOfRangeException()
 {
     using (BufferedStream stream = new BufferedStream(new MemoryStream()))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.Position = -1);
     }
 }
		private void Connect()
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
			{
				SendTimeout = SendTimeout,
				ReceiveTimeout = ReceiveTimeout
			};
			try
			{
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

				if (!socket.Connected)
				{
					socket.Close();
					socket = null;
					return;
				}
				Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

				if (Password != null)
					SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

				db = 0;
				var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
				clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
				lastCommand = null;
				lastSocketException = null;
				LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

				if (isPreVersion1_26 == null)
				{
					isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
				}

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
			}
			catch (SocketException ex)
			{
                if (socket != null)
                    socket.Close();
                socket = null;

				HadExceptions = true;
				var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
				log.Error(throwEx.Message, ex);
				throw throwEx;
			}
		}
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strLoc = "Loc_000oo";
		String strValue = String.Empty;
		try
		{
			BinaryWriter sr2;
		    MemoryStream ms2;
			FileStream fs2;
			BufferedStream bs2;
			String filName = s_strTFAbbrev+"Test.tmp";
			if(File.Exists(filName))
				File.Delete(filName);			
			strLoc = "Loc_98hg7";
			ms2 = new MemoryStream();
			sr2 = new BinaryWriter(ms2);
			iCountTestcases++;
			if(sr2.BaseStream != ms2) {
				iCountErrors++;
				printerr( "Error_g57hb! Incorrect basestream");
			}
			sr2.Close();
			ms2 = new MemoryStream();
			bs2 = new BufferedStream(ms2);
			sr2 = new BinaryWriter(bs2);
			iCountTestcases++;
			if(sr2.BaseStream != bs2) {
				iCountErrors++;
				printerr( "Error_988hu! Incorrect basestream");
			}
			sr2.Close();
			fs2 = new FileStream(filName, FileMode.Create);
			sr2 = new BinaryWriter(fs2);
			iCountTestcases++;
			if(sr2.BaseStream != fs2) {
				iCountErrors++;
				printerr( "Error_29g87! Incorrect baseStream");
			}
			sr2.Close();
			if(File.Exists(filName))
				File.Delete(filName);
		} catch (Exception exc_general ) {
			++iCountErrors;
			Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
예제 #12
0
    public Example_01()
    {
        FileStream fos = new FileStream("Example_01.pdf", FileMode.Create);
        BufferedStream bos = new BufferedStream(fos);

        PDF pdf = new PDF(bos);
        pdf.setCompressor(Compressor.ORIGINAL_ZLIB);

        Page page = new Page(pdf, Letter.PORTRAIT);

        Box flag = new Box();
        flag.SetPosition(100.0, 100.0);
        flag.SetSize(190.0, 100.0);
        flag.SetColor(RGB.WHITE);
        flag.DrawOn(page);

        double sw = 7.69;   // stripe width
        Line stripe = new Line(0.0, sw/2, 190.0, sw/2);
        stripe.SetWidth(sw);
        stripe.SetColor(RGB.OLD_GLORY_RED);
        for (int row = 0; row < 7; row++) {
            stripe.PlaceIn(flag, 0.0, row * 2 * sw);
            stripe.DrawOn(page);
        }

        Box union = new Box();
        union.SetSize(76.0, 53.85);
        union.SetColor(RGB.OLD_GLORY_BLUE);
        union.SetFillShape(true);
        union.PlaceIn(flag, 0.0, 0.0);
        union.DrawOn(page);

        double h_si = 12.6; // horizontal star interval
        double v_si = 10.8; // vertical star interval
        Point star = new Point(h_si/2, v_si/2);
        star.SetShape(Point.STAR);
        star.SetRadius(3.0);
        star.SetColor(RGB.WHITE);
        star.SetFillShape(true);

        for (int row = 0; row < 6; row++) {
            for (int col = 0; col < 5; col++) {
                star.PlaceIn(union, row * h_si, col * v_si);
                star.DrawOn(page);
            }
        }
        star.SetPosition(h_si, v_si);
        for (int row = 0; row < 5; row++) {
            for (int col = 0; col < 4; col++) {
                star.PlaceIn(union, row * h_si, col * v_si);
                star.DrawOn(page);
            }
        }

        pdf.Flush();
        bos.Close();
    }
 private static void StartWavAnalyze(string strFileName,long nLength)
 {
     using (FileStream fs = new FileStream(strFileName,FileMode.Open,FileAccess.Read))
     using (BufferedStream bs = new BufferedStream(fs,nBufferSize))
     using (BinaryReader r = new BinaryReader(bs))
     {
         StartWavAnalyze(r,nLength);
     }
 }
예제 #14
0
    public Example_04()
    {
        String fileName = "data/happy-new-year.txt";

        FileStream fos = new FileStream("Example_04.pdf", FileMode.Create);
        BufferedStream bos = new BufferedStream(fos);

        PDF pdf = new PDF(bos);
        pdf.setCompressor(Compressor.ORIGINAL_ZLIB);

        Font f1 = new Font(
                pdf,
                "AdobeMingStd-Light",       // Chinese (Traditional) font
                CodePage.UNICODE);
        Font f2 = new Font(
                pdf,
                "AdobeSongStd-Light",       // Chinese (Simplified) font
                CodePage.UNICODE);
        Font f3 = new Font(
                pdf,
                "KozMinProVI-Regular",      // Japanese font
                CodePage.UNICODE);
        Font f4 = new Font(
                pdf,
                "AdobeMyungjoStd-Medium",   // Korean font
                CodePage.UNICODE);

        Page page = new Page(pdf, Letter.PORTRAIT);

        f1.SetSize(14);
        f2.SetSize(14);
        f3.SetSize(14);
        f4.SetSize(14);

        double x_pos = 100.0;
        double y_pos = 20.0;
        StreamReader reader = new StreamReader(
                new FileStream(fileName, FileMode.Open));
        TextLine text = new TextLine(f1);
        String line = null;
        while ((line = reader.ReadLine()) != null) {
            if (line.IndexOf("Simplified") != -1) {
                text.SetFont(f2);
            } else if (line.IndexOf("Japanese") != -1) {
                text.SetFont(f3);
            } else if (line.IndexOf("Korean") != -1) {
                text.SetFont(f4);
            }
            text.SetText(line);
            text.SetPosition(x_pos, y_pos += 24);
            text.DrawOn(page);
        }
        reader.Close();

        pdf.Flush();
        bos.Close();
    }
 public static void StreamThroughWaveFile(string sFileName,IReadWaveData objCallback)
 {
     using (FileStream fs = new FileStream(sFileName,FileMode.Open,FileAccess.Read))
     using (BufferedStream bs = new BufferedStream(fs, nBufferSize))
     using (BinaryReader r = new BinaryReader(bs))
     {
         StreamThroughWaveFile(r, objCallback);
     }
 }
예제 #16
0
    public static void Main()
    {
        var bs = new BufferedStream(Console.OpenStandardInput());
        StreamReader reader = new StreamReader(bs);

        string[] ss = reader.ReadLine().Split();
        int n = int.Parse(ss[0]), k = int.Parse(ss[1]);
        List<int> a = reader.ReadLine().Split().Select(x => int.Parse(x) - 1).ToList();

        var cycles = Enumerable.Range(0, n).Select(x => new List<List<int>>()).ToArray();
        bool[] seen = new bool[n];
        foreach (int i in Enumerable.Range(0, n))
            if (!seen[i])
        {
            List<int> cyc = new List<int> ();
            int u = i;
            do {
                cyc.Add(u);
                seen[u] = true;
                u = a[u];
            } while (u != i);
            cycles[cyc.Count].Add(cyc);
        }

        Dictionary<int, int> pow = factor(k).ToDictionary(x => x.Prime, x => x.Power);
        List<int> res = Enumerable.Repeat(-1, n).ToList();
        foreach (var group in cycles.Where(x => x.Count > 0))
        {
            int len = group.First().Count;
            int need = len == 1 ?
                gcd(k, group.Count) : // we want to avoid self-loops
                factor(len)
                .Where(f => pow.ContainsKey(f.Prime))
                .Select(f => pow[f.Prime])
                .Aggregate(1, (x, y) => x * y);//multiply everything

            if (group.Count % need == 0)
                for (int i = 0; i < group.Count; i += need)
                {
                    List<int> cyc = new List<int> ();
                    foreach (int l in Enumerable.Range(0, len))
                        foreach (int j in Enumerable.Range(0, need))
                            cyc.Add(group[i + j][l]);

                    int move = inverse(k / need % len, len);
                    foreach (int j in Enumerable.Range(0, cyc.Count))
                        res[cyc[j]] = cyc[(j + move) % cyc.Count];
                }
        }

        if (res.Any(x => x == -1))
            Console.WriteLine("Impossible");
        else
            Console.WriteLine(string.Join(" ", res.Select(x => x + 1)));
    }
예제 #17
0
    public List<string> GetAllData()
    {
        string line = "";
        string input_file = "./Saved Data/characters.xml";
        List<string> keyList = new List<string>();
        List<string> elemList = new List<string>();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] key = null;
        RijndaelManaged RMCrypto = new RijndaelManaged();
        string tagID;
        string tagIDend;
        int indexStart = 0;
        int indexEnd = 0;

        key = encoding.GetBytes(Data_Handler_Key.keyvalue);
        FileStream decrypted_file = new FileStream(input_file, FileMode.Open);
        CryptoStream cryptography_stream = new CryptoStream(decrypted_file, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
        using (MemoryStream msDecrypt = new MemoryStream())
        {
            using (BufferedStream readBuffer = new BufferedStream(cryptography_stream))
            using (StreamReader srDecrypt = new StreamReader(readBuffer))
            {
                    while ((line = srDecrypt.ReadLine()) != null)
                    {
                        elemList.Add(line);
                    }
            }
        }
        cryptography_stream.Close();
        decrypted_file.Close();
        tagID = "<id>" + Character_Info.id + "</id>";
        tagIDend = "<idend>" + Character_Info.id + "</idend>";
        int i = 0;
        foreach(var content in elemList)
        {
            if(content == tagID)
            {
                indexStart = i;
            }

            if(content == tagIDend)
            {
                indexEnd = i;
            }
            i++;
        }
        if (indexStart != indexEnd)
        {
            elemList.RemoveRange(indexStart, indexEnd - indexStart);
        }
        elemList.Remove("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        elemList.Remove("<savedcharacters>");
        elemList.Remove("</savedcharacters>");
        return elemList;
    }
예제 #18
0
    public static void Main()
    {
        string path = @"..\..\Files\Start.txt";
        string pathResult = @"..\..\Files\Result.txt";
        Console.WriteLine("Loading...");
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            int bufferSize = 10485760; //10MB  buffer size

            using (StreamWriter sw = new StreamWriter(path, true))
            {
                for (long i = 0; i < 5000000; i++) //if you want 100mb files make it 1 000 000
                {
                    sw.WriteLine("This is some text to test");
                    sw.WriteLine("Reading repeated 500 time");
                    sw.WriteLine(" TEST TEXT:");
                    sw.WriteLine("testTextstart with startstart start");

                }

            }

            using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (BufferedStream bs = new BufferedStream(fs, bufferSize))
                {
                    using (StreamWriter result = new StreamWriter(pathResult, false))
                    {
                        using (StreamReader sr = new StreamReader(bs))
                        {

                            while (!sr.EndOfStream)
                            {
                                string line = sr.ReadLine();
                                // result.WriteLine(line.Replace("start", "finish")); // ex. 07
                                result.WriteLine(Regex.Replace(line, @"\bstart\b", "finish")); //ex. 08
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Operation failed: \n {0}", e.ToString());
        }

        Console.WriteLine("Success -> check Files dir in project");
    }
예제 #19
0
    static void Main(string[] args)
    {
        // Check that an argument was specified when the
        // program was invoked.
        //if (args.Length == 0)
        //{
        //    Console.WriteLine("Error: The name of the host computer" +
        //        " must be specified when the program is invoked.");
        //    return;
        //}

          //  string remoteName = args[0];

        // Create the underlying socket and connect to the server.
        Console.WriteLine("OS {0} {1} processors count {2}\n", Environment.OSVersion, Environment.Is64BitOperatingSystem ? "x64" : "x32", Environment.ProcessorCount);
        Socket clientSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        clientSocket.Connect(new IPEndPoint(
            IPAddress.Parse("127.0.0.1"), 1800));

        Console.WriteLine("Client is connected.\n");

        // Create a NetworkStream that owns clientSocket and
        // then create a BufferedStream on top of the NetworkStream.
        // Both streams are disposed when execution exits the
        // using statement.
        using (Stream
            netStream = new NetworkStream(clientSocket, true),
            bufStream =
                  new BufferedStream(netStream, streamBufferSize))
        {
            // Check whether the underlying stream supports seeking.
            Console.WriteLine("NetworkStream {0} seeking.\n",
                bufStream.CanSeek ? "supports" : "does not support");

            // Send and receive data.
            if (bufStream.CanWrite)
            {
                SendData(netStream, bufStream);
            }
            if (bufStream.CanRead)
            {
                ReceiveData(netStream, bufStream);
            }

            // When bufStream is closed, netStream is in turn
            // closed, which in turn shuts down the connection
            // and closes clientSocket.
            Console.WriteLine("\nShutting down the connection.");
            bufStream.Close();
        }
        Console.ReadKey();
    }
예제 #20
0
        public void UnderlyingStreamThrowsExceptions()
        {
            var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream());

            Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status);

            Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status);

            stream.WriteByte(1);
            Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status);
        }
예제 #21
0
    public static void Main()
    {
        var bs = new BufferedStream(Console.OpenStandardInput());
        StreamReader reader = new StreamReader(bs);

        int n = int.Parse(reader.ReadLine());
        List<int> a = reader.ReadLine().Split().Select(x => int.Parse(x))
            .OrderByDescending(x => x).ToList();

        Console.WriteLine(Enumerable.Range(0, n - 1).Max(i => i + a[i] + 2));
    }
 public static void Write_Arguments()
 {
     using (BufferedStream stream = new BufferedStream(new MemoryStream()))
     {
         byte[] array = new byte[10];
         Assert.Throws<ArgumentNullException>("array", () => stream.Write(null, 1, 1));
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(array, -1, 1));
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(array, 1, -1));
         Assert.Throws<ArgumentException>(() => stream.Write(array, 9, 2));
     }
 }
 public static void SetLength_NegativeValue()
 {
     using (MemoryStream underlying = new MemoryStream())
     using (BufferedStream stream = new BufferedStream(underlying))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.SetLength(-1));
         stream.SetLength(1);
         Assert.Equal(1, underlying.Length);
         Assert.Equal(1, stream.Length);
     }
 }
    public static void StreamThroughWave(string strFileName, long length)
    {
        if (!File.Exists(strFileName))
            throw new Exception("File not found.");

        using (FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
        using (BufferedStream bs = new BufferedStream(fs, 32768))
        using (BinaryReader r = new BinaryReader(bs))
        {
            StreamThroughWave(r, length);
        }
    }
예제 #25
0
    /// <summary>
    /// Gets the chunk data.
    /// </summary>
    /// <returns>The chunk data.</returns>
    /// <param name="x">The x coordinate.</param>
    /// <param name="z">The z coordinate.</param>
    /// <param name="width">Width.</param>
    /// <param name="height">Height.</param>
    /// <param name="depth">Depth.</param>
    public CubicTerrainData GetChunkData(int x, int y, int z, int width, int height, int depth)
    {
        BufferedStream chunkDataStream = new BufferedStream (File.Open (this.chunkDataFile, FileMode.Open));
        CubicTerrainData terrainData = new CubicTerrainData (width, height, depth);

        // Get chunk starting position
        chunkDataStream.Position = this.chunkLookupTable [new ListIndex<int>(x,y,z)];

        terrainData.DeserializeChunk (chunkDataStream);
        chunkDataStream.Close ();

        return terrainData;
    }
예제 #26
0
    public static void Main()
    {
        Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
        var bs = new BufferedStream(Console.OpenStandardInput());
        StreamReader reader = new StreamReader(bs);
        double x = double.Parse(reader.ReadLine());

        List<int> res = Solve(x).ToList();
        if (res.Count == 0)
            Console.WriteLine("No solution");
        else
            foreach (int s in res)
                Console.WriteLine(s);
    }
예제 #27
0
 static string CalculateChecksum(Stream stream)
 {
     using (var bs = new BufferedStream(stream))
     using (var sha1 = new SHA1Managed())
     {
         var hash = sha1.ComputeHash(bs);
         var formatted = new StringBuilder(2*hash.Length);
         foreach (var b in hash)
         {
             formatted.AppendFormat("{0:X2}", b);
         }
         return formatted.ToString();
     }
 }
		private void Connect()
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
			{
				SendTimeout = SendTimeout
			};
			try
			{
                socket = GetSocketCanConnect();
                if (!socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    socket = null;
                    return;
                }

				Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

				if (Password != null)
					SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

				db = 0;
				var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
				clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
				lastCommand = null;
				lastSocketException = null;
				LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

				if (isPreVersion1_26 == null)
				{
					isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;

					//force version reload
					log.DebugFormat("redis-server Version: {0}", isPreVersion1_26);
				}
			}
			catch (SocketException ex)
			{
                if (socket != null)
                    socket.Close();
                socket = null;

				HadExceptions = true;
				var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
				log.Error(throwEx.Message, ex);
				throw throwEx;
			}
		}
 public static string CalculateChecksum(string filename)
 {
     using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     using (var bs = new BufferedStream(fs))
     using (var sha1 = new SHA1Managed())
     {
         var hash = sha1.ComputeHash(bs);
         var formatted = new StringBuilder(2 * hash.Length);
         foreach (var b in hash)
         {
             formatted.AppendFormat("{0:X2}", b);
         }
         return formatted.ToString();
     }
 }
예제 #30
0
    public static void Main()
    {
        var bs = new BufferedStream(Console.OpenStandardInput());
        StreamReader reader = new StreamReader(bs);

        string[] ss = reader.ReadLine().Split();
        int n = int.Parse(ss[0]), k = int.Parse(ss[1]);
        List<int> a = reader.ReadLine().Split().Select(x => int.Parse(x) - 1).ToList();

        var cycles = Enumerable.Range(0, n).Select(x => new List<List<int>>()).ToArray();
        bool[] seen = new bool[n];
        foreach (int i in Enumerable.Range(0, n)) if (!seen[i])
        {
            List<int> cyc = new List<int> ();
            int u = i;
            do {
                cyc.Add(u);
                seen[u] = true;
                u = a[u];
            } while (u != i);
            cycles[cyc.Count].Add(cyc);
        }

        List<int> res = Enumerable.Repeat(-1, n).ToList();
        foreach (var group in cycles) if (group.Count > 0)
        {
            int len = group.First().Count;
            int need = gcd(len, k);

            if (group.Count % need == 0)
                for (int i = 0; i < group.Count; i += need)
                {
                    List<int> cyc = new List<int> ();
                    foreach (int l in Enumerable.Range(0, len))
                        foreach (int j in Enumerable.Range(0, need))
                            cyc.Add(group[i + j][l]);

                    int move = inverse(k / need % len, len);
                    if (move != -1) foreach (int j in Enumerable.Range(0, cyc.Count))
                        res[cyc[j]] = cyc[(j + move) % cyc.Count];
                }
        }

        if (res.Any(x => x == -1))
            Console.WriteLine("Impossible");
        else
            Console.WriteLine(string.Join(" ", res.Select(x => x + 1)));
    }
예제 #31
0
 public PostscriptDSCTokenizer(string path)
 {
     _stream         = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     _bufferedStream = new BufferedStream(_stream);
 }
예제 #32
0
 private void WriteHmuxLength(BufferedStream stream, int length)
 {
     stream.WriteByte((byte)(length >> 8));
     stream.WriteByte((byte)length);
 }
예제 #33
0
        private bool TryMakeBrushesFromGeometryCache()
        {
            long begin = System.Environment.TickCount;

            try
            {
                Action <object> loadBrush = new Action <object>(LoadBrush);

                bool useIndex = false;
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                int count = -1;

                try
                {
                    if (System.IO.File.Exists(geometryCacheIndexPath))
                    {
                        FileStream indexFile = new FileStream(geometryCacheIndexPath, FileMode.Open);
                        System.IO.Compression.GZipStream indexZip = new System.IO.Compression.GZipStream(indexFile, System.IO.Compression.CompressionMode.Decompress);
                        BufferedStream indexStream = new BufferedStream(indexZip);

                        index = (long[])f.Deserialize(indexStream);
                        indexStream.Close();
                        useIndex = true;
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("index deserialization failed");
                }

                bool geometryCacheExists = File.Exists(geometryCachePath);
                if (geometryCacheExists == false)
                {
                    System.Diagnostics.Trace.TraceWarning("No geometry cache found");
                    return(false);
                }

                //  Load file to memory
                FileStream file = new FileStream(geometryCachePath, FileMode.Open);
                System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(file, System.IO.Compression.CompressionMode.Decompress);
                BufferedStream bufferedStream        = new BufferedStream(zip);
                cacheData = ReadFully(bufferedStream, 0);
                bufferedStream.Close();
                MemoryStream stream = new MemoryStream(cacheData);
                //stream.Write(cacheData, 0, cacheData.Length);
                //stream.Seek(0, SeekOrigin.Begin);

                count = (int)f.Deserialize(stream);
                if ((index != null) && (index.Length == count))
                {
                    stream.Close();
                    Debug.WriteLine("Valid index found, use multi threaded path for geometry cache loading");
                    threadInfo = new Dictionary <System.Threading.Thread, BrushLoadThreadInfo>();
                    for (int i = 0; i < count; ++i)
                    {
                        ThreadManager.Instance.AddTask(loadBrush, new BrushInfo(i));
                    }
                    ThreadManager.Instance.Execute();
                    cacheData  = null;
                    threadInfo = null;
                    // \todo add interface
                    RenderStack.Graphics.BufferGL.FinalizeDeserializations();
                }
                else
                {
                    //  No valid index found, single threaded path
                    Debug.WriteLine("No valid index found, single threaded path for geometry cache loading");
                    index    = new long[count];
                    useIndex = false;
                    //  Create MemoryStream so we can access Position
                    for (int i = 0; i < count; ++i)
                    {
                        if (useIndex)
                        {
                            stream.Seek(index[i], SeekOrigin.Begin);
                        }
                        else
                        {
                            index[i] = stream.Position;
                        }
                        //Message("BrushManager: " + i.ToString() + "/" + count.ToString() + " GeometryMesh Deserialize");
                        string       name = (string)f.Deserialize(stream);
                        GeometryMesh mesh = (GeometryMesh)f.Deserialize(stream);
                        Message("BrushManager: " + i.ToString() + "/" + count.ToString() + " MakeBrush " + name);
                        MakeBrush(name, mesh);
                    }
                    stream.Close();
                }

                UpdateGeometryCacheIndex();
                long end      = System.Environment.TickCount;
                long duration = end - begin;
                System.Diagnostics.Trace.WriteLine("Geometry cache load took " + duration.ToString() + " ticks");
                return(true);
            }
            catch (Exception)
            {
                System.Diagnostics.Trace.TraceWarning("There was a problem with geometrycache");
                return(false);
            }
        }
예제 #34
0
        private int ReadHmuxLength(BufferedStream stream)
        {
            int length = (stream.ReadByte() << 8) + stream.ReadByte();

            return(length);
        }
예제 #35
0
        private void DoHmux(HttpContext context)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            String sessionId;

            if (!_isStickySessions)
            {
                sessionId = null;
            }
            else
            {
                sessionId = GetRequestedSessionId(request);
            }

            TempBuffer tempBuf = TempBuffer.Allocate();

            byte[] buf = tempBuf.GetBuffer();

            try {
                Stream is_ = request.InputStream;
                int    len = is_.Read(buf, 0, buf.Length);
                bool   isComplete;

                if (len < 0)
                {
                    isComplete = true;
                }
                else if (len < buf.Length)
                {
                    int sublen = is_.Read(buf, len, 1);

                    if (sublen == 0) //.NET return 0 for Stream.EOF
                    {
                        isComplete = true;
                    }
                    else
                    {
                        len       += sublen;
                        isComplete = false;
                    }
                }
                else
                {
                    isComplete = false;
                }

                Server client = null;
                int    result = OK | EXIT;

                HmuxConnection channel = _loadBalancer.OpenServer(sessionId, null);

                // If everything fails, return an error
                if (channel == null)
                {
                    SendNotAvailable(response);

                    return;
                }

                client = channel.GetPool();

                BufferedStream rs = channel.GetSocketStream();
                BufferedStream ws = channel.GetSocketStream();
                result = FAIL | EXIT;
                long requestStartTime = Utils.CurrentTimeMillis();

                try {
                    result = HandleRequest(context, request, response, channel, rs, ws,
                                           buf, len, isComplete, isComplete);

                    if ((result & STATUS_MASK) == OK)
                    {
                        client.ClearBusy();

                        return;
                    }
                    else if ((result & STATUS_MASK) == BUSY)
                    {
                        client.Busy();
                    }
                    else
                    {
                        client.FailSocket();
                    }
                } catch (ClientDisconnectException) {
                    _log.Info("Client disconnect detected for '{0}'", channel.GetTraceId());

                    return;
                } catch (IOException e) {
                    client.FailSocket();
                    _log.Error("IOException '{0}': '{1}' {2}", channel.GetTraceId(), e.Message, e.StackTrace);
                } finally {
                    if ((result & EXIT_MASK) == QUIT)
                    {
                        channel.Free(requestStartTime);
                    }
                    else
                    {
                        channel.Close();
                    }
                }

                // server/2675
                if (isComplete && (result & STATUS_MASK) == BUSY ||
                    "GET".Equals(request.HttpMethod))
                {
                    channel = _loadBalancer.OpenServer(sessionId, client);

                    // If everything fails, return an error
                    if (channel == null)
                    {
                        _log.Info("load-balance failed" + (client != null ? (" for " + client.GetDebugId()) : ""));

                        SendNotAvailable(response);

                        return;
                    }

                    Server client2 = channel.GetPool();

                    if (_log.IsLoggable(EventLogEntryType.Information))
                    {
                        _log.Info("load-balance failing over"
                                  + (client != null ? (" from " + client.GetDebugId()) : "")
                                  + " to " + client2.GetDebugId());
                    }

                    rs = channel.GetSocketStream();
                    ws = channel.GetSocketStream();

                    result           = FAIL | EXIT;
                    requestStartTime = Utils.CurrentTimeMillis();

                    try {
                        result = HandleRequest(context, request, response, channel, rs, ws,
                                               buf, len, isComplete, false);

                        if ((result & STATUS_MASK) == OK)
                        {
                            client2.ClearBusy();

                            return;
                        }
                        else if ((result & STATUS_MASK) == BUSY)
                        {
                            client2.Busy();
                        }
                        else
                        {
                            client2.FailSocket();
                        }
                    } catch (IOException e) {
                        client2.FailSocket();

                        _log.Info("Failover to '{0}' did not succeed '{1}', {2} ", client2.GetDebugId(), e.Message, e.StackTrace);
                    } finally {
                        if ((result & EXIT_MASK) == QUIT)
                        {
                            channel.Free(requestStartTime);
                        }
                        else
                        {
                            channel.Close();
                        }
                    }
                }

                SendNotAvailable(response);
            } finally {
                TempBuffer.Free(tempBuf);
                tempBuf = null;
            }
        }
예제 #36
0
        private Tuple <INatsConnection, IList <IOp> > EstablishConnection(Host host, ConnectionInfo connectionInfo, CancellationToken cancellationToken)
        {
            Socket         socket      = null;
            BufferedStream writeStream = null;
            BufferedStream readStream  = null;

            try
            {
                socket = _socketFactory.Create(connectionInfo.SocketOptions);

                socket.Connect(
                    host,
                    connectionInfo.SocketOptions.ConnectTimeoutMs,
                    cancellationToken);

                readStream = new BufferedStream(socket.CreateReadStream(), socket.ReceiveBufferSize);

                var reader      = new NatsOpStreamReader(readStream);
                var consumedOps = new List <IOp>();

                IOp ReadOne()
                {
                    var op = reader.ReadOp().FirstOrDefault();

                    if (op != null)
                    {
                        consumedOps.Add(op);
                    }

                    return(op);
                }

                var serverInfo = VerifyConnection(host, connectionInfo, socket, ReadOne);

                writeStream = new BufferedStream(socket.CreateWriteStream(), socket.SendBufferSize);

                return(new Tuple <INatsConnection, IList <IOp> >(new NatsConnection(
                                                                     serverInfo,
                                                                     socket,
                                                                     writeStream,
                                                                     readStream,
                                                                     reader,
                                                                     cancellationToken), consumedOps));
            }
            catch
            {
                Swallow.Everything(
                    () =>
                {
                    readStream?.Dispose();
                    readStream = null;
                },
                    () =>
                {
                    writeStream?.Dispose();
                    writeStream = null;
                },
                    () =>
                {
                    if (socket == null)
                    {
                        return;
                    }

                    if (socket.Connected)
                    {
                        socket.Shutdown(SocketShutdown.Both);
                    }

                    socket.Dispose();
                    socket = null;
                });

                throw;
            }
        }
예제 #37
0
        private static PTable MergeTo2(IList <PTable> tables, long fileSize, int indexEntrySize, string outputFile,
                                       Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord,
                                       byte version, int cacheDepth)
        {
            Log.Trace("PTables merge started (specialized for <= 2 tables).");
            var watch = Stopwatch.StartNew();

            var  enumerators      = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList();
            long dumpedEntryCount = 0;

            using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
                                          DefaultSequentialBufferSize, FileOptions.SequentialScan))
            {
                f.SetLength(fileSize);
                f.Seek(0, SeekOrigin.Begin);

                using (var md5 = MD5.Create())
                    using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write))
                        using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize))
                        {
                            // WRITE HEADER
                            var headerBytes = new PTableHeader(version).AsByteArray();
                            cs.Write(headerBytes, 0, headerBytes.Length);

                            // WRITE INDEX ENTRIES
                            var        buffer     = new byte[indexEntrySize];
                            var        enum1      = enumerators[0];
                            var        enum2      = enumerators[1];
                            bool       available1 = enum1.MoveNext();
                            bool       available2 = enum2.MoveNext();
                            IndexEntry current;
                            while (available1 || available2)
                            {
                                var entry1 = new IndexEntry(enum1.Current.Stream, enum1.Current.Version, enum1.Current.Position);
                                var entry2 = new IndexEntry(enum2.Current.Stream, enum2.Current.Version, enum2.Current.Position);

                                if (available1 && (!available2 || entry1.CompareTo(entry2) > 0))
                                {
                                    current    = entry1;
                                    available1 = enum1.MoveNext();
                                }
                                else
                                {
                                    current    = entry2;
                                    available2 = enum2.MoveNext();
                                }

                                if (existsAt(current))
                                {
                                    AppendRecordTo(bs, buffer, version, current, indexEntrySize);
                                    dumpedEntryCount += 1;
                                }
                            }
                            bs.Flush();
                            cs.FlushFinalBlock();

                            f.SetLength(f.Position + MD5Size);

                            // WRITE MD5
                            var hash = md5.Hash;
                            f.Write(hash, 0, hash.Length);
                            f.FlushToDisk();
                        }
            }
            Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).",
                      watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount);
            return(new PTable(outputFile, Guid.NewGuid(), version, depth: cacheDepth));
        }
예제 #38
0
        private async Task PerformPackageInstallation(IProgress <double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
        {
            // Target based on if it is an archive or single assembly
            //  zip archives are assumed to contain directory structures relative to our ProgramDataPath
            var extension = Path.GetExtension(package.targetFilename);
            var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
            var target    = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);

            // Download to temporary file so that, if interrupted, it won't destroy the existing installation
            var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
            {
                Url = package.sourceUrl,
                CancellationToken = cancellationToken,
                Progress          = progress
            }).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            // Validate with a checksum
            var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);

            if (packageChecksum != Guid.Empty) // support for legacy uploads for now
            {
                using (var crypto = new MD5CryptoServiceProvider())
                    using (var stream = new BufferedStream(File.OpenRead(tempFile), 100000))
                    {
                        var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
                        if (check != packageChecksum)
                        {
                            throw new ApplicationException(string.Format("Download validation failed for {0}.  Probably corrupted during transfer.", package.name));
                        }
                    }
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Success - move it to the real target
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(target));
                File.Copy(tempFile, target, true);
                //If it is an archive - write out a version file so we know what it is
                if (isArchive)
                {
                    File.WriteAllText(target + ".ver", package.versionStr);
                }
            }
            catch (IOException e)
            {
                _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
                throw;
            }

            try
            {
                File.Delete(tempFile);
            }
            catch (IOException e)
            {
                // Don't fail because of this
                _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
            }
        }
예제 #39
0
        private void mnuLoad_Click(object sender, EventArgs e)
        {
            clearLevel();
            cmdSave.Enabled  = false;
            cmdClear.Enabled = false;
            cmdReset.Enabled = false;

            lstLevels.Items.Clear();

            bool inLevel = false;

            if (dgOpenMapData.ShowDialog() == DialogResult.OK)
            {
                mnuSave.Enabled   = true;
                mnuSaveAs.Enabled = true;

                const string userRoot = "HKEY_CURRENT_USER";
                const string subkey   = "LodeRunner";
                const string keyName  = userRoot + "\\" + subkey;
                Registry.SetValue(keyName, "PathName", Path.GetDirectoryName(dgOpenMapData.FileName));

                //                String[] lines = System.IO.File.ReadAllLines(dgOpenMapData.FileName);

                using (FileStream fs = File.Open(dgOpenMapData.FileName, FileMode.Open))
                    using (BufferedStream bs = new BufferedStream(fs, System.Text.ASCIIEncoding.Unicode.GetByteCount("g")))
                        using (StreamReader sr = new StreamReader(bs)) {
                            LevelDefinition levelDefinition = null;
                            string          line;
                            while ((line = sr.ReadLine()) != null)
                            {
                                if (line.StartsWith("#define GAME_NUMBER"))
                                {
                                    gameNumber = line.Substring(@"#define GAME_NUMBER".Length + 1).Trim();
                                }
                                else if (line.StartsWith("#define NUMBER_OF_GAMES"))
                                {
                                    numberOfGames = line.Substring(@"#define NUMBER_OF_GAMES".Length + 1).Trim();
                                }
                                else if (line.StartsWith("#if GAME_NUMBER"))
                                {
                                    gameNumberId = Int16.Parse(line.Substring(line.IndexOf("==") + 3).Trim());
                                }
                                else if (line.StartsWith("  #define LEVEL_COUNT"))
                                {
                                    Int16 gamesPerLevel = Int16.Parse(line.Substring(@"  #define LEVEL_COUNT".Length + 1).Trim());
                                    gamesPerLevels.Add(gamesPerLevel);
                                    dgExport.Rows.Add(dgExport.Rows.Count, gamesPerLevel);
                                }
                                else if (line.StartsWith("const uint8_t PROGMEM"))
                                {
                                    levelDefinition           = new LevelDefinition();
                                    levelDefinition.LevelName = line.Substring(line.IndexOf("PROGMEM ") + 8, line.Length - line.IndexOf("PROGMEM ") - 14);
                                    inLevel = true;
                                }
                                else if (inLevel)
                                {
                                    if (line == "};")
                                    {
                                        inLevel = false;
                                        ListViewItem item = new ListViewItem();
                                        item.Text = levelDefinition.LevelName;
                                        item.Tag  = levelDefinition;
                                        lstLevels.Items.Add(item);
                                    }
                                    else
                                    {
                                        char[]   splitchar = { ',' };
                                        String[] strData   = line.Trim().Split(splitchar);

                                        int cursor = 0;


                                        // Player start pos ..

                                        CoordinateSet player = new CoordinateSet();
                                        player.X = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                        player.Y = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                        levelDefinition.Player = player;


                                        // Enemies

                                        int numberOfEnemies = Convert.ToInt32(strData[cursor++].Trim(), 16);

                                        for (int x = 0; x < numberOfEnemies; x++)
                                        {
                                            CoordinateSet enemy = new CoordinateSet();
                                            enemy.X = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            enemy.Y = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            levelDefinition.Enemies.Add(enemy);
                                        }


                                        // Level Ladders

                                        int numberOfLevelLadders = Convert.ToInt32(strData[cursor++].Trim(), 16);

                                        for (int x = 0; x < numberOfLevelLadders; x++)
                                        {
                                            CoordinateSet levelLadder = new CoordinateSet();
                                            levelLadder.X = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            levelLadder.Y = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            levelDefinition.Ladders.Add(levelLadder);
                                        }


                                        // Reentry points

                                        for (int x = 0; x < 4; x++)
                                        {
                                            CoordinateSet reentryPoint = new CoordinateSet();
                                            reentryPoint.X = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            reentryPoint.Y = Convert.ToInt32(strData[cursor++].Trim(), 16);
                                            levelDefinition.ReentryPoints.Add(reentryPoint);
                                        }

                                        // Encryption type ..

                                        levelDefinition.EncryptionType = (EncryptionType)Convert.ToInt32(strData[cursor++].Trim(), 16);
                                        int[] data = new int[strData.Length - cursor];

                                        for (int count = cursor; count <= strData.Length - 2; count++)
                                        {
                                            data[count - cursor] = Convert.ToInt32(strData[count].Trim(), 16);
                                        }

                                        loadLevel(levelDefinition, data);
                                    }
                                }
                            }
                        }
            }

            foreach (ListViewItem item in lstLevels.Items)
            {
                validate(item, (LevelDefinition)item.Tag);
            }


            MessageBox.Show("Level data loaded successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        static void Main(string[] args)
        {
            /*-----------------------------------------------------------------------
             * Title
             * --------------------------------------------------------------------*/
            string divider = new string('=', 100);

            Console.WriteLine(divider);
            Console.WriteLine("CLIENT");
            Console.WriteLine(divider);


            /*-----------------------------------------------------------------------
             * Vars
             * --------------------------------------------------------------------*/
            int       port = 43000;
            TcpClient client;
            byte      count = 0;


            /*-----------------------------------------------------------------------
             * Send 3 messages (last one to close server)
             * --------------------------------------------------------------------*/
            try
            {
                while (count < 3)
                {
                    // Pause for 1 second.
                    Thread.Sleep(1000);

                    // Create a new client
                    using (client = new TcpClient("localhost", port))
                    {
                        string msg = (count < 2) ? $"This is message {count + 1}" : "close";

                        // Create a new stream to send message
                        using (NetworkStream stream = client.GetStream())
                        {
                            using (BufferedStream writer = new BufferedStream(stream))
                            {
                                byte[] messageBytesToSend = Encoding.UTF8.GetBytes(msg);
                                writer.Write(messageBytesToSend, 0, messageBytesToSend.Length);
                                Console.WriteLine("Message sent...");
                            }
                        }
                    }

                    // Inc. counter
                    count++;
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to connect to server");
            }


            /*-----------------------------------------------------------------------
             * Finish up
             * --------------------------------------------------------------------*/
            Console.WriteLine("Client finished...");
            Console.ReadKey();
        }
예제 #41
0
 public HttpBufferedStream(Stream stream)
 {
     this.innerStream = new BufferedStream(stream);
 }
예제 #42
0
        public void whois_info(string domainname)
        {
            Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + m_jobId + " whois on : " + domainname);
            //            http://reports.internic.net/cgi/whois?whois_nic=xorcism.org&type=domain
            TcpClient      tcpWhois = null;
            NetworkStream  nsWhois;
            BufferedStream bfWhois = null;
            StreamWriter   swSend;
            StreamReader   srReceive;

            try
            {
                // The TcpClient should connect to the who-is server, on port 43 (default who-is)
                tcpWhois = new TcpClient("whois.internic.net", 43); //Hardcoded
                // Set up the network stream
                nsWhois = tcpWhois.GetStream();
                // Hook up the buffered stream to the network stream
                bfWhois = new BufferedStream(nsWhois);
            }
            catch (Exception ex)
            {
                Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + m_jobId + " WhoisError: Could not open a connection to the Who-Is server. " + ex.Message + " " + ex.InnerException);
            }

            // Send to the server the hostname that we want to get information on
            swSend = new StreamWriter(bfWhois);
            swSend.WriteLine(domainname);
            swSend.Flush();

            //TODO

            /*
             * try
             * {
             *  srReceive = new StreamReader(bfWhois);
             *  string strResponse;
             *  // Read the response line by line
             *  //TODO: Review Update
             *  while ((strResponse = srReceive.ReadLine()) != null)
             *  {
             *      //txtResponse.Text += strResponse + "\r\n";
             *      if (strResponse.Contains("Domain Name:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Domain Name";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.INFORMATION.Add(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Registrar:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Registrar";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.INFORMATION.Add(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Whois Server:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Whois Server";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.INFORMATION.Add(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Referral URL:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Referral URL";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Name Server:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Name Server";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Status:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Status";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Updated Date:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Updated Date";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Creation Date:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Creation Date";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *      if (strResponse.Contains("Expiration Date:"))
             *      {
             *          INFORMATION newInfo = new INFORMATION();
             *          newInfo.Title = "Expiration Date";
             *          newInfo.Result = strResponse;
             *          newInfo.JobID = m_jobId;
             *          m_model.AddToINFORMATION(newInfo);
             *          m_model.SaveChanges();
             *      }
             *  }
             * }
             * catch(Exception ex)
             * {
             *  Utils.Helper_Trace("XORCISM PROVIDER XINFO", "JobID:" + m_jobId + " WhoisError: Could not read data from the Who-Is server. " + ex.Message + " " + ex.InnerException);
             * }
             */

            // We're done with the connection
            tcpWhois.Close();
        }
        static void _Start(object nothing)
        {
            try
            {
                var deadline = DateTime.Now.AddSeconds(20);

                log.Info("_Start");

                while (DateTime.Now < deadline)
                {
                    try
                    {
                        TcpClient client = new TcpClient("127.0.0.1", OutputPort);
                        Console.WriteLine("Port open");
                        client.Close();
                        break;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Port closed");
                    }
                }

                using (TcpClient client = new TcpClient("127.0.0.1", OutputPort))
                {
                    client.ReceiveBufferSize = 1024 * 1024 * 5; // 5mb

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (var stream = new BufferedStream(client.GetStream(), 1024 * 1024 * 5))
                        {
                            DateTime lastdata = DateTime.Now;
                            while (client.Client.Connected)
                            {
                                int bytestoread = client.Available;

                                while (bytestoread > 0)
                                {
                                    //bytestoread -= readRTPData(stream, ms);
                                    bytestoread -= readJPGData(stream, ms);
                                    lastdata     = DateTime.Now;
                                }
                                // up to 100 fps or 50 with 10ms process time
                                System.Threading.Thread.Sleep(10);

                                if (lastdata.AddSeconds(5) < DateTime.Now)
                                {
                                    client.Client.Send(new byte[0]);
                                }
                            }
                            //cleanup on disconnect
                            FlightData.myhud.bgimage = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FlightData.myhud.bgimage = null;
                log.Error(ex);
            }
        }
예제 #44
0
 protected TextBuffer(Stream str)
 {
     this.delta        = 1;
     this.bufferedStrm = new BufferedStream(str);
 }
        static int Main(string[] args)
        {
            try
            {
                // Default number of lines is 1
                int numlines = 1;

                #region Command Line Parsing

                string filename = string.Empty;
                bool   redirected;
                bool   set_l     = false;
                bool   set_input = false;

                foreach (string arg in args)
                {
                    if (arg[0] == '/')
                    {
                        if (arg.Length > 3)
                        {
                            if (arg.ToUpper( )[1] == 'L')
                            {
                                if (arg[2] != ':')
                                {
                                    return(WriteError("Invalid argument: " + arg));
                                }
                                try
                                {
                                    if (set_l)
                                    {
                                        return(WriteError("Duplicate /L argument"));
                                    }
                                    else
                                    {
                                        numlines = Convert.ToInt32(arg.Substring(3));
                                        if (numlines < 1)
                                        {
                                            return(WriteError("Number of lines must be 1 or greater"));
                                        }
                                        set_l = true;
                                    }
                                }
                                catch (FormatException)
                                {
                                    return(WriteError("Invalid number of lines: " + arg));
                                }
                            }
                        }
                        else
                        {
                            if (arg == "/?")
                            {
                                return(WriteError( ));
                            }
                            else
                            {
                                return(WriteError("Invalid argument: " + arg));
                            }
                        }
                    }
                    else
                    {
                        if (set_input)
                        {
                            return(WriteError("Duplicate file argument"));
                        }
                        else
                        {
                            if (File.Exists(arg))
                            {
                                filename = arg;
                            }
                            else
                            {
                                return(WriteError("Invalid filename: " + arg));
                            }
                            set_input = true;
                        }
                    }
                }

                if (ConsoleEx.InputRedirected)
                {
                    if (set_input)
                    {
                        return(WriteError("Use either file name or redirection, not both"));
                    }
                    else
                    {
                        set_input  = true;
                        redirected = true;
                    }
                }
                else
                {
                    if (args.Length == 0)
                    {
                        return(WriteError( ));
                    }
                    redirected = false;
                }

                #endregion Command Line Parsing


                int      index  = 0;
                string[] output = new string[numlines];

                if (redirected)
                {
                    // Read standard input and store the lines in a list
                    while (Console.In.Peek( ) > -1)
                    {
                        output.SetValue(Console.In.ReadLine( ), index);
                        index = (index + 1) % numlines;
                    }
                }
                else
                {
                    // Read the file and store the lines in an array
                    Encoding enc = GetEncoding(filename);
                    using (FileStream fsi = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        using (BufferedStream bsi = new BufferedStream(fsi))
                            using (StreamReader sri = new StreamReader(bsi, enc))
                            {
                                while (sri.Peek( ) > -1)
                                {
                                    output.SetValue(sri.ReadLine( ), index);
                                    index = (index + 1) % numlines;
                                }
                            }
                }

                // Display the lines in the correct order
                for (int i = index; i < output.Length; i++)
                {
                    Console.WriteLine(output[i]);
                }
                if (index > 0)
                {
                    for (int i = 0; i < index; i++)
                    {
                        Console.WriteLine(output[i]);
                    }
                }
                return(0);
            }
            catch (Exception e)
            {
                return(WriteError(e.Message));
            }
        }
예제 #46
0
        // ReSharper restore UnusedMember.Local

        private bool Load(ILoadMonitor loader)
        {
            IProgressStatus status =
                new ProgressStatus(string.Format(Resources.BiblioSpecLibrary_Load_Loading__0__library,
                                                 Path.GetFileName(FilePath)));

            loader.UpdateProgress(status);

            long lenRead = 0;

            // AdlerChecksum checksum = new AdlerChecksum();

            try
            {
                // Use a buffered stream for initial read
                BufferedStream stream = new BufferedStream(CreateStream(loader), 32 * 1024);

                int    countHeader = (int)LibHeaders.count * 4;
                byte[] libHeader   = new byte[countHeader];
                if (stream.Read(libHeader, 0, countHeader) != countHeader)
                {
                    throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_library_header_File_may_be_corrupted);
                }
                lenRead += countHeader;
                // Check the first byte of the primary version number to determine
                // whether the format is little- or big-endian.  Little-endian will
                // have the version number in this byte, while big-endian will have zero.
                if (libHeader[(int)LibHeaders.version1 * 4] == 0)
                {
                    _bigEndian = true;
                }

                int numSpectra   = GetInt32(libHeader, (int)LibHeaders.num_spectra);
                var dictLibrary  = new Dictionary <LibKey, BiblioSpectrumInfo>(numSpectra);
                var setSequences = new HashSet <LibSeqKey>();

                string revStr = string.Format("{0}.{1}", // Not L10N
                                              GetInt32(libHeader, (int)LibHeaders.version1),
                                              GetInt32(libHeader, (int)LibHeaders.version2));
                Revision = float.Parse(revStr, CultureInfo.InvariantCulture);

                // checksum.MakeForBuff(libHeader, AdlerChecksum.ADLER_START);

                countHeader = (int)SpectrumHeaders.count * 4;
                byte[] specHeader   = new byte[1024];
                byte[] specSequence = new byte[1024];
                for (int i = 0; i < numSpectra; i++)
                {
                    int percent = i * 100 / numSpectra;
                    if (status.PercentComplete != percent)
                    {
                        // Check for cancellation after each integer change in percent loaded.
                        if (loader.IsCanceled)
                        {
                            loader.UpdateProgress(status.Cancel());
                            return(false);
                        }

                        // If not cancelled, update progress.
                        loader.UpdateProgress(status = status.ChangePercentComplete(percent));
                    }

                    // Read spectrum header
                    int bytesRead = stream.Read(specHeader, 0, countHeader);
                    if (bytesRead != countHeader)
                    {
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);
                    }

                    // If this is the first header, and the sequence length is zero,
                    // then this is a Linux format library.  Switch to linux format,
                    // and start over.
                    if (i == 0 && GetInt32(specHeader, (int)SpectrumHeaders.seq_len) == 0)
                    {
                        _linuxFormat = true;
                        stream.Seek(lenRead, SeekOrigin.Begin);

                        // Re-ead spectrum header
                        countHeader = (int)SpectrumHeadersLinux.count * 4;
                        bytesRead   = stream.Read(specHeader, 0, countHeader);
                        if (bytesRead != countHeader)
                        {
                            throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted);
                        }
                    }

                    lenRead += bytesRead;

                    // checksum.MakeForBuff(specHeader, checksum.ChecksumValue);

                    int charge = GetInt32(specHeader, (int)SpectrumHeaders.charge);
                    if (charge > TransitionGroup.MAX_PRECURSOR_CHARGE)
                    {
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted);
                    }

                    int numPeaks  = GetInt32(specHeader, (int)SpectrumHeaders.num_peaks);
                    int seqLength = GetInt32(specHeader, (_linuxFormat ?
                                                          (int)SpectrumHeadersLinux.seq_len : (int)SpectrumHeaders.seq_len));
                    int copies = GetInt32(specHeader, (_linuxFormat ?
                                                       (int)SpectrumHeadersLinux.copies : (int)SpectrumHeaders.copies));

                    // Read sequence information
                    int countSeq = (seqLength + 1) * 2;
                    if (stream.Read(specSequence, 0, countSeq) != countSeq)
                    {
                        throw new InvalidDataException(Resources.BiblioSpecLibrary_Load_Data_truncation_in_spectrum_sequence_File_may_be_corrupted);
                    }

                    lenRead += countSeq;

                    // checksum.MakeForBuff(specSequence, checksum.ChecksumValue);

                    // Store in dictionary
                    if (IsUnmodified(specSequence, seqLength + 1, seqLength))
                    {
                        // These libraries should not have duplicates, but just in case.
                        // CONSIDER: Emit error about redundancy?
                        // These legacy libraries assume [+57.0] modified Cysteine
                        LibKey key = new LibKey(GetCModified(specSequence, ref seqLength), 0, seqLength, charge);
                        if (!dictLibrary.ContainsKey(key))
                        {
                            dictLibrary.Add(key, new BiblioSpectrumInfo((short)copies, (short)numPeaks, lenRead));
                        }
                        setSequences.Add(new LibSeqKey(key));
                    }

                    // Read over peaks
                    int countPeaks = 2 * sizeof(Single) * numPeaks;
                    stream.Seek(countPeaks, SeekOrigin.Current);    // Skip spectrum
                    lenRead += countPeaks;

                    // checksum.MakeForBuff(specPeaks, checksum.ChecksumValue);
                }

                // Checksum = checksum.ChecksumValue;
                _dictLibrary  = dictLibrary;
                _setSequences = setSequences;
                loader.UpdateProgress(status.Complete());
                return(true);
            }
            catch (InvalidDataException x)
            {
                loader.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            catch (IOException x)
            {
                loader.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            catch (Exception x)
            {
                x = new Exception(string.Format(Resources.BiblioSpecLibrary_Load_Failed_loading_library__0__, FilePath), x);
                loader.UpdateProgress(status.ChangeErrorException(x));
                return(false);
            }
            finally
            {
                if (ReadStream != null)
                {
                    // Close the read stream to ensure we never leak it.
                    // This only costs on extra open, the first time the
                    // active document tries to read.
                    try { ReadStream.CloseStream(); }
                    catch (IOException) {}
                }
            }
        }
예제 #47
0
        public void Run()
        {
            IsRunning = true;
            while (IsRunning)
            {
                Logger.Log("Broadcaster {0} waiting for connection...", Id);
                TcpClient client = null;
                try
                {
                    client = Listener.AcceptTcpClient();

#if DEBUG == false
                    //timeouts affect debugging when stepping through code
                    client.ReceiveTimeout = 5000;
#endif
                }
                catch (Exception ex)
                {
                    Logger.Log("Broadcaster {0} could not accept TCP client: {1}", Id, ex.Message);
                    continue;
                }
                Logger.Log("Broadcaster {0} accepting client: {1}", Id, client.Client.RemoteEndPoint);

                BinaryReader reader = null;
                BinaryWriter writer = null;
                try
                {
                    BufferedStream stream = new BufferedStream(client.GetStream());
                    reader = new BinaryReader(stream);
                    writer = new BinaryWriter(stream);

                    //grab auth key
                    int    authKeyLength = IPAddress.NetworkToHostOrder(reader.ReadInt32());
                    byte[] authKeyBytes  = reader.ReadBytes(authKeyLength);
                    string authKey       = Encoding.UTF8.GetString(authKeyBytes);

                    if (Server.ActiveUsers.ContainsKey(authKey) == true)
                    {
                        while (true)
                        {
                            if (PendingMessages.Count > 0)
                            {
                                var    message   = PendingMessages.Dequeue();
                                byte[] userBytes = Encoding.UTF8.GetBytes(message.Key.Name);
                                writer.Write(IPAddress.HostToNetworkOrder(userBytes.Length));
                                writer.Write(userBytes);

                                byte[] messageBytes = Encoding.UTF8.GetBytes(message.Value);
                                writer.Write(IPAddress.HostToNetworkOrder(messageBytes.Length));
                                writer.Write(messageBytes);
                                stream.Flush();
                            }
                            else
                            {
                                Thread.Sleep(500);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log("Broadcaster {0} exception handling client {1}, {2}: ", Id, client.Client.RemoteEndPoint, ex.Message);
                }
                finally
                {
                    Logger.Log("Broadcaster {0} done handling client {1}", Id, client.Client.RemoteEndPoint);
                    reader.Close();
                    writer.Close();
                    if (client != null)
                    {
                        client.Close();
                    }
                }
            }
        }
        public async Task <HttpResponseMessage> DistributeDocument(string fileNameAndPath, string cloudDeploymentResourceUrl, string sourceDocumentId, string jwtToken)
        {
            string multiCloudMachineName = cloudDeploymentResourceUrl.TrimEnd('/') + "/api/v1/";
            string qvDocName             = Path.GetFileNameWithoutExtension(fileNameAndPath);
            var    l_FileStream          = new FileStream(fileNameAndPath, FileMode.Open, FileAccess.Read);
            var    stream  = new BufferedStream(l_FileStream, 8192);
            var    content = new StreamContent(stream, 65536);

            try
            {
                content.Headers.Add("Content-Type", "binary/octet-stream");
                using (HttpClient cloudClient = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, multiCloudMachineName + "apps/import?mode=autoreplace&appId=" + sourceDocumentId + "&fallbackName=" + qvDocName)
                    {
                        Content = content
                    };
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
                    HttpResponseMessage autoReplaceDocResponse = await cloudClient.SendAsync(request);

                    switch (autoReplaceDocResponse.StatusCode)
                    {
                    case HttpStatusCode.RequestEntityTooLarge:
                        PrintMessage("Failure - Could not upload document to engine, since engine reported that the app exceeds the maximum size. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        throw new HttpAppSizeException("App size exceeds max size");

                    case HttpStatusCode.GatewayTimeout:
                        PrintMessage("Failure - Could not upload document in engine, API gateway in QSEfe/Multicloud reported that it timed out when waiting for a response. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(autoReplaceDocResponse);
                        break;
                    }
                    if (!autoReplaceDocResponse.IsSuccessStatusCode)
                    {
                        PrintMessage("Failure - Could not upload document " + qvDocName + "to engine. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(autoReplaceDocResponse);
                    }

                    else
                    {
                        Console.WriteLine("Success - Document  " + qvDocName + " uploaded to engine");
                    }

                    var responseContent = await autoReplaceDocResponse.Content.ReadAsStringAsync() ?? "{}";

                    EngineDoc result = JsonConvert.DeserializeObject <EngineDoc>(responseContent);

                    HttpResponseMessage createItemResponse = await CreateItem(result, jwtToken, multiCloudMachineName, qvDocName);

                    return(createItemResponse);
                }
            }
            catch (HttpAppSizeException)
            {
                PrintMessage("App " + qvDocName + " exceeds max size", false);
            }
            catch (WorkflowException e)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, workflowException. Message =" + e.Message, false);
            }
            catch (TaskCanceledException e)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, Connection timeout. Message =" + e.Message, false);
            }
            catch (Exception ex)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, Other exception of unknown cause. Message =" + ex.Message, false);
            }
            finally
            {
                content.Dispose();
                stream.Dispose();
                l_FileStream.Dispose();
            }
            return(null);
        }
예제 #49
0
        public static PTable MergeTo(IList <PTable> tables, string outputFile, Func <string, ulong, ulong> upgradeHash, Func <IndexEntry, bool> existsAt, Func <IndexEntry, Tuple <string, bool> > readRecord, byte version, int cacheDepth = 16)
        {
            Ensure.NotNull(tables, "tables");
            Ensure.NotNullOrEmpty(outputFile, "outputFile");
            Ensure.Nonnegative(cacheDepth, "cacheDepth");

            var indexEntrySize = version == PTableVersions.Index32Bit ? PTable.IndexEntry32Size : IndexEntry64Size;

            var fileSize = GetFileSize(tables, indexEntrySize); // approximate file size

            if (tables.Count == 2)
            {
                return(MergeTo2(tables, fileSize, indexEntrySize, outputFile, upgradeHash, existsAt, readRecord, version, cacheDepth)); // special case
            }
            Log.Trace("PTables merge started.");
            var watch = Stopwatch.StartNew();

            var enumerators = tables.Select(table => new EnumerableTable(version, table, upgradeHash, existsAt, readRecord)).ToList();

            for (int i = 0; i < enumerators.Count; i++)
            {
                if (!enumerators[i].MoveNext())
                {
                    enumerators[i].Dispose();
                    enumerators.RemoveAt(i);
                    i--;
                }
            }

            long dumpedEntryCount = 0;

            using (var f = new FileStream(outputFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
                                          DefaultSequentialBufferSize, FileOptions.SequentialScan))
            {
                f.SetLength(fileSize);
                f.Seek(0, SeekOrigin.Begin);

                using (var md5 = MD5.Create())
                    using (var cs = new CryptoStream(f, md5, CryptoStreamMode.Write))
                        using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize))
                        {
                            // WRITE HEADER
                            var headerBytes = new PTableHeader(version).AsByteArray();
                            cs.Write(headerBytes, 0, headerBytes.Length);

                            var buffer = new byte[indexEntrySize];
                            // WRITE INDEX ENTRIES
                            while (enumerators.Count > 0)
                            {
                                var idx     = GetMaxOf(enumerators);
                                var current = enumerators[idx].Current;
                                if (existsAt(current))
                                {
                                    AppendRecordTo(bs, buffer, version, current, indexEntrySize);
                                    dumpedEntryCount += 1;
                                }
                                if (!enumerators[idx].MoveNext())
                                {
                                    enumerators[idx].Dispose();
                                    enumerators.RemoveAt(idx);
                                }
                            }
                            bs.Flush();
                            cs.FlushFinalBlock();

                            f.FlushToDisk();
                            f.SetLength(f.Position + MD5Size);

                            // WRITE MD5
                            var hash = md5.Hash;
                            f.Write(hash, 0, hash.Length);
                            f.FlushToDisk();
                        }
            }
            Log.Trace("PTables merge finished in {0} ([{1}] entries merged into {2}).",
                      watch.Elapsed, string.Join(", ", tables.Select(x => x.Count)), dumpedEntryCount);
            return(new PTable(outputFile, Guid.NewGuid(), depth: cacheDepth));
        }
예제 #50
0
파일: General.cs 프로젝트: arelee/ravendb
        public void CompleteTransaction(Guid txId, Action <DocumentInTransactionData> perDocumentModified)
        {
            Api.JetSetCurrentIndex(session, Transactions, "by_tx_id");
            Api.MakeKey(session, Transactions, txId, MakeKeyGrbit.NewKey);
            if (Api.TrySeek(session, Transactions, SeekGrbit.SeekEQ))
            {
                Api.JetDelete(session, Transactions);
            }

            Api.JetSetCurrentIndex(session, DocumentsModifiedByTransactions, "by_tx");
            Api.MakeKey(session, DocumentsModifiedByTransactions, txId, MakeKeyGrbit.NewKey);
            if (Api.TrySeek(session, DocumentsModifiedByTransactions, SeekGrbit.SeekEQ) == false)
            {
                return;
            }
            Api.MakeKey(session, DocumentsModifiedByTransactions, txId, MakeKeyGrbit.NewKey);
            Api.JetSetIndexRange(session, DocumentsModifiedByTransactions, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
            var bookmarksToDelete      = new List <byte[]>();
            var documentsInTransaction = new List <DocumentInTransactionData>();

            do
            {
                // esent index ranges are approximate, and we need to check them ourselves as well
                if (
                    Api.RetrieveColumnAsGuid(session, DocumentsModifiedByTransactions,
                                             tableColumnsCache.DocumentsModifiedByTransactionsColumns["locked_by_transaction"]) != txId)
                {
                    continue;
                }
                var metadata = Api.RetrieveColumn(session, DocumentsModifiedByTransactions,
                                                  tableColumnsCache.DocumentsModifiedByTransactionsColumns["metadata"]);
                var key = Api.RetrieveColumnAsString(session, DocumentsModifiedByTransactions,
                                                     tableColumnsCache.DocumentsModifiedByTransactionsColumns["key"],
                                                     Encoding.Unicode);

                RavenJObject dataAsJson;
                var          metadataAsJson = metadata.ToJObject();
                using (
                    Stream stream = new BufferedStream(new ColumnStream(session, DocumentsModifiedByTransactions,
                                                                        tableColumnsCache.DocumentsModifiedByTransactionsColumns["data"])))
                {
                    using (var data = documentCodecs
                                      .Aggregate(stream, (dataStream, codec) => codec.Decode(key, metadataAsJson, dataStream)))
                        dataAsJson = data.ToJObject();
                }


                documentsInTransaction.Add(new DocumentInTransactionData
                {
                    Data   = dataAsJson,
                    Delete =
                        Api.RetrieveColumnAsBoolean(session, DocumentsModifiedByTransactions,
                                                    tableColumnsCache.DocumentsModifiedByTransactionsColumns["delete_document"]).Value,
                    Etag = Api.RetrieveColumn(session, DocumentsModifiedByTransactions,
                                              tableColumnsCache.DocumentsModifiedByTransactionsColumns["etag"]).
                           TransfromToGuidWithProperSorting(),
                    Key      = key,
                    Metadata = metadata.ToJObject(),
                });
                bookmarksToDelete.Add(Api.GetBookmark(session, DocumentsModifiedByTransactions));
            } while (Api.TryMoveNext(session, DocumentsModifiedByTransactions));

            foreach (var bookmark in bookmarksToDelete)
            {
                Api.JetGotoBookmark(session, DocumentsModifiedByTransactions, bookmark, bookmark.Length);
                Api.JetDelete(session, DocumentsModifiedByTransactions);
            }
            foreach (var documentInTransactionData in documentsInTransaction)
            {
                perDocumentModified(documentInTransactionData);
            }
        }
예제 #51
0
        public static bool VerifySteamHash(string executablePath)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                //Get Steam_api.dll from (parent)filepath\Among Us_Data\Plugins\x86\steam_api.dll and steam_api64.dll
                var baseDllFolder = Path.Join(Directory.GetParent(executablePath).FullName, "/Among Us_Data/Plugins/x86/");
                if (!Directory.Exists(baseDllFolder))
                {
                    baseDllFolder = Path.Join(Directory.GetParent(executablePath).FullName, "/Among Us_Data/Plugins/x86_64/");
                }
                var steam_apiCert   = AuthenticodeTools.IsTrusted(Path.Join(baseDllFolder, "steam_api.dll"));
                var steam_api64Cert = AuthenticodeTools.IsTrusted(Path.Join(baseDllFolder, "steam_api64.dll"));
                //Settings.conInterface.WriteModuleTextColored("GameVerifier",Color.Yellow,$"steam_apiCert: {steam_apiCert}");
                //Settings.conInterface.WriteModuleTextColored("GameVerifier",Color.Yellow,$"steam_api64Cert: {steam_api64Cert}");
                return((steam_apiCert) && (steam_api64Cert));
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var baseDllFolder = Path.Join(Directory.GetParent(executablePath).FullName,
                                              "/Among Us_Data/Plugins/x86/");

                var steam_apiPath   = Path.Join(baseDllFolder, "steam_api.dll");
                var steam_api64Path = Path.Join(baseDllFolder, "steam_api64.dll");
                var steam_apiHash   = String.Empty;
                var steam_api64Hash = String.Empty;

                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    using (FileStream fs = new FileStream(steam_apiPath, FileMode.Open))
                    {
                        using (var bs = new BufferedStream(fs))
                        {
                            var           hash            = sha1.ComputeHash(bs);
                            StringBuilder steam_apihashSb = new StringBuilder(2 * hash.Length);
                            foreach (byte byt in hash)
                            {
                                steam_apihashSb.AppendFormat("{0:X2}", byt);
                            }

                            steam_apiHash = steam_apihashSb.ToString();
                        }
                    }

                    using (FileStream fs = new FileStream(steam_api64Path, FileMode.Open))
                    {
                        using (var bs = new BufferedStream(fs))
                        {
                            var           hash = sha1.ComputeHash(bs);
                            StringBuilder steam_api64hashSb = new StringBuilder(2 * hash.Length);
                            foreach (byte byt in hash)
                            {
                                steam_api64hashSb.AppendFormat("{0:X2}", byt);
                            }

                            steam_api64Hash = steam_api64hashSb.ToString();
                        }
                    }
                }

                return(String.Equals(steamapi32_orig_hash.ToUpper(), steam_apiHash) &&
                       String.Equals(steamapi64_orig_hash.ToUpper(), steam_api64Hash));
            }

            throw new PlatformNotSupportedException();
        }
예제 #52
0
        /**
         * Creates a CertPath of the specified type.
         * This constructor is protected because most users should use
         * a CertificateFactory to create CertPaths.
         *
         * @param type the standard name of the type of Certificatesin this path
         **/
        public PkixCertPath(
            Stream inStream,
            String encoding)
//			: base("X.509")
        {
            try
            {
                if (encoding.ToUpper().Equals("PkiPath".ToUpper()))
                {
                    Asn1InputStream derInStream = new Asn1InputStream(inStream);
                    Asn1Object      derObject   = derInStream.ReadObject();
                    if (!(derObject is Asn1Sequence))
                    {
                        throw new CertificateException(
                                  "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
                    }
                    IEnumerator     e = ((Asn1Sequence)derObject).GetEnumerator();
                    Stream          certInStream;
                    MemoryStream    outStream;
                    DerOutputStream derOutStream;
                    certificates = new ArrayList();

                    while (e.MoveNext())
                    {
                        outStream    = new MemoryStream();
                        derOutStream = new DerOutputStream(outStream);

                        derOutStream.WriteObject((Asn1Encodable)e.Current);
                        derOutStream.Close();

                        certInStream = new MemoryStream(outStream.ToArray(), false);
                        certificates.Insert(0, new X509CertificateParser().ReadCertificate(certInStream));
                    }
                }
                else if (encoding.ToUpper().Equals("PKCS7") ||
                         encoding.ToUpper().Equals("PEM"))
                {
                    inStream     = new BufferedStream(inStream);
                    certificates = new ArrayList();

                    X509CertificateParser certParser = new X509CertificateParser();
                    X509Certificate       cert       = null;

                    while ((cert = certParser.ReadCertificate(inStream)) != null)
                    {
                        certificates.Add(cert);
                    }
                }
                else
                {
                    throw new CertificateException("unsupported encoding: " + encoding);
                }
            }
            catch (IOException ex)
            {
                throw new CertificateException(
                          "IOException throw while decoding CertPath:\n"
                          + ex.ToString());
            }

            this.certificates = SortCerts(certificates);
        }
예제 #53
0
        private int HandleRequest(HttpContext context,
                                  HttpRequest request,
                                  HttpResponse response,
                                  HmuxConnection hmuxChannel,
                                  BufferedStream rs,
                                  BufferedStream ws,
                                  byte[] buf, int length, bool isComplete,
                                  bool allowBusy)
        {
            Trace.TraceInformation("Handle request: length: {0}, complete: {1}, allowBusy {2}", length, isComplete, allowBusy);
            String traceId = hmuxChannel.GetTraceId();

            StringBuilder cb = new StringBuilder();

            bool isDebugFiner = true;

            String uri = request.Path;

            uri = Uri.EscapeUriString(uri);

            Trace.TraceInformation("Hmux[{0}] >>U:uri {1}->{2}", traceId, request.RawUrl, uri);
            WriteRequestString(ws, HmuxConnection.HMUX_URI, uri, traceId);

            String rawUri   = request.RawUrl;
            int    queryIdx = rawUri.IndexOf('?');

            if (queryIdx > -1 && queryIdx + 1 < rawUri.Length)
            {
                String query = rawUri.Substring(queryIdx + 1);
                Trace.TraceInformation("Hmux[{0}] >>U:query {1}", traceId, query);
                WriteRequestString(ws, HmuxConnection.CSE_QUERY_STRING, query, traceId);
            }

            Trace.TraceInformation("Hmux[{0}] >>m:method {1}", traceId, request.HttpMethod);
            WriteRequestString(ws, HmuxConnection.HMUX_METHOD, request.HttpMethod, traceId);

            Trace.TraceInformation("Hmux[{0}] >>u:server type {1}", traceId, "IIS");
            WriteRequestString(ws, HmuxConnection.CSE_SERVER_TYPE, "IIS", traceId);

            NameValueCollection serverVariables = request.ServerVariables;

            String serverPort = serverVariables.Get("SERVER_PORT");
            String serverName = serverVariables.Get("SERVER_NAME") + ':' + serverPort;

            Trace.TraceInformation("Hmux[{0}] >>v:server name {1}", traceId, serverName);
            WriteRequestString(ws, HmuxConnection.HMUX_SERVER_NAME, serverName, traceId);

            Trace.TraceInformation("Hmux[{0}] >>g:server port {1}", traceId, serverPort);
            WriteRequestString(ws, HmuxConnection.CSE_SERVER_PORT, serverPort, traceId);

            String remoteAddr = serverVariables.Get("REMOTE_ADDR");

            Trace.TraceInformation("Hmux[{0}] >>i:remote address {1}", traceId, remoteAddr);
            WriteRequestString(ws, HmuxConnection.CSE_REMOTE_ADDR, remoteAddr, traceId);

            String remoteHost = serverVariables.Get("REMOTE_HOST");

            if (remoteHost == null)
            {
                remoteHost = remoteAddr;
            }

            Trace.TraceInformation("Hmux[{0}] >>h:remote host {1}", traceId, remoteHost);
            WriteRequestString(ws, HmuxConnection.CSE_REMOTE_HOST, remoteHost, traceId);

            String protocol = serverVariables.Get("HTTP_VERSION");

            Trace.TraceInformation("Hmux[{0}] >>c:protocol {1}", traceId, protocol);
            WriteRequestString(ws, HmuxConnection.CSE_PROTOCOL, protocol, traceId);

            HttpClientCertificate clientCertificate = request.ClientCertificate;

            if (request.IsSecureConnection)
            {
                Trace.TraceInformation("Hmux[{0}] >>r:secure", traceId);
                WriteRequestString(ws, HmuxConnection.CSE_IS_SECURE, "", traceId);

                WriteRequestHeader(ws, "HTTPS", "on", traceId);
                WriteRequestHeader(ws, "SSL_SECRETKEYSIZE", clientCertificate.KeySize.ToString(), traceId);
            }

            if (clientCertificate.IsPresent)
            {
                Trace.TraceInformation("Hmux[{0}] >>r:certificate ({1})", traceId, clientCertificate.Certificate.Length);
                ws.WriteByte(HmuxConnection.CSE_CLIENT_CERT);
                WriteHmuxLength(ws, clientCertificate.Certificate.Length);
                ws.Write(clientCertificate.Certificate, 0, clientCertificate.Certificate.Length);
            }

            if (request.IsAuthenticated)
            {
                /*
                 * String remoteUser = request.LogonUserIdentity.Name;
                 */
                String remoteUser = HttpContext.Current.User.Identity.Name;
                WriteRequestString(ws, HmuxConnection.CSE_REMOTE_USER, remoteUser, traceId);
            }

            NameValueCollection headers = request.Headers;

            foreach (String key in headers.AllKeys)
            {
                if ("Connection".Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                String[] values = headers.GetValues(key);
                foreach (String value in values)
                {
                    WriteRequestHeader(ws, key, value, traceId);
                }
            }

            if (_isDebug)
            {
                WriteRequestHeader(ws, "X-Resin-Debug", traceId, traceId);
            }

            Stream requestStream  = request.InputStream;
            Stream responseStream = null;

            bool hasHeader = true;
            bool hasStatus = false;


            if (length > 0)
            {
                Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length);
                WriteRequestData(ws, HmuxConnection.HMUX_DATA, buf, length, traceId);
            }

            int len;

            int code;

            while (!isComplete && (len = requestStream.Read(buf, 0, buf.Length)) > 0)
            {
                Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length);
                WriteRequestData(ws, HmuxConnection.HMUX_DATA, buf, len, traceId);

                Trace.TraceInformation("Hmux[{0}] >>Y: (yield)", traceId);
                ws.WriteByte(HmuxConnection.HMUX_YIELD);
                ws.Flush();

                while (true)
                {
                    code = rs.ReadByte();

                    if (code < 0)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<w: end of file", traceId);

                        if (hasStatus)
                        {
                            return(OK | EXIT);
                        }
                        else
                        {
                            // Trace.TraceInformation("Hmux[{0}] <<w: unexpected end of file", traceId);

                            return(FAIL | EXIT);
                        }
                    }
                    else if (code == HmuxConnection.HMUX_QUIT)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId);

                        if (hasStatus)
                        {
                            return(OK | QUIT);
                        }
                        else
                        {
                            Trace.TraceInformation("Hmux[{0}] <<Q: unexpected quit file", traceId);

                            return(FAIL | QUIT);
                        }
                    }
                    else if (code == HmuxConnection.HMUX_EXIT)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId);

                        if (hasStatus)
                        {
                            return(OK | EXIT);
                        }
                        else
                        {
                            Trace.TraceInformation("Hmux[{0}] <<X: unexpected exit", traceId);

                            return(FAIL | EXIT);
                        }
                    }
                    else if (code == HmuxConnection.HMUX_YIELD)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId);

                        continue;
                    }

                    int sublen = ReadHmuxLength(rs);

                    if (code == HmuxConnection.HMUX_ACK)
                    {
                        if (isDebugFiner)
                        {
                            Trace.TraceInformation("Hmux[{0}] <<A: (ack) ({1})", traceId, sublen);
                        }

                        break;
                    }
                    else if (code == HmuxConnection.HMUX_CHANNEL)
                    {
                        int channel = sublen;
                        Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel);
                    }
                    else if (code == HmuxConnection.HMUX_STATUS && hasHeader)
                    {
                        String status = ReadHmuxString(rs, sublen);
                        Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status);
                        int statusCode = 0;
                        for (int i = 0; i < 3; i++)
                        {
                            statusCode = 10 * statusCode + status[i] - '0';
                        }

                        if (statusCode != 200)
                        {
                            response.StatusCode = statusCode;
                        }

                        hasStatus = true;
                    }
                    else if (code == HmuxConnection.HMUX_HEADER && hasHeader)
                    {
                        String name = ReadHmuxString(rs, sublen);
                        rs.ReadByte();
                        sublen = ReadHmuxLength(rs);
                        String value = ReadHmuxString(rs, sublen);

                        Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value);

                        RelayResponseHeader(response, name, value);
                    }
                    else if (code == HmuxConnection.HMUX_DATA)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen);

                        if (responseStream == null)
                        {
                            responseStream = response.OutputStream;
                        }

                        RelayResponseData(rs, responseStream, sublen);
                    }
                    else if (code == HmuxConnection.HMUX_META_HEADER)
                    {
                        String name = ReadHmuxString(rs, sublen);
                        rs.ReadByte();
                        sublen = ReadHmuxLength(rs);
                        String value = ReadHmuxString(rs, sublen);

                        Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value);

                        if ("cpu-load".Equals(name))
                        {
                            double loadAvg = 0.001 * long.Parse(value);

                            hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg);
                        }
                    }
                    else
                    {
                        Skip(rs, sublen);
                    }
                }
            }

            ws.WriteByte(HmuxConnection.HMUX_QUIT);
            ws.Flush();

            code = rs.ReadByte();

            // #2369 - A slow modem can cause the app-tier and web-tier times
            // to get out of sync, with the app-tier thinking it's completed
            // (and starts the keepalive timeout) 30s before the web-tier reads
            // its data.
            // As a temporary measure, we start the idle time at the first data
            // read (later we might mark the time it takes to read an app-tier
            // packet.  If it's short, e.g. 250ms, don't update the time.)
            hmuxChannel.SetIdleStartTime(Utils.CurrentTimeMillis());

            bool isBusy = false;

            for (; code >= 0; code = rs.ReadByte())
            {
                if (code == HmuxConnection.HMUX_QUIT)
                {
                    if (isDebugFiner)
                    {
                        Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId);
                    }

                    return(isBusy ? BUSY | QUIT : OK | QUIT);
                }
                else if (code == HmuxConnection.HMUX_EXIT)
                {
                    Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId);

                    return((isBusy || !hasStatus) ? BUSY | EXIT : OK | EXIT);
                }
                else if (code == HmuxConnection.HMUX_YIELD)
                {
                    Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId);

                    continue;
                }

                int sublen = (rs.ReadByte() << 8) + rs.ReadByte();

                if (code == HmuxConnection.HMUX_DATA)
                {
                    if (responseStream == null)
                    {
                        responseStream = response.OutputStream;
                    }

                    Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen);

                    if (!isBusy)
                    {
                        RelayResponseData(rs, responseStream, sublen);
                    }
                    else
                    {
                        Skip(rs, sublen);
                    }
                }
                else if (code == HmuxConnection.HMUX_STATUS && hasHeader)
                {
                    hasStatus = true;
                    String status = ReadHmuxString(rs, sublen);
                    Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status);

                    int statusCode = 0;
                    for (int i = 0; i < 3; i++)
                    {
                        statusCode = 10 * statusCode + status[i] - '0';
                    }

                    if (statusCode == 503 && allowBusy)
                    {
                        isBusy = true;
                    }
                    else if (statusCode != 200)
                    {
                        response.StatusCode = statusCode;
                    }
                }
                else if (code == HmuxConnection.HMUX_HEADER && hasHeader)
                {
                    String name = ReadHmuxString(rs, sublen);
                    rs.ReadByte();
                    sublen = ReadHmuxLength(rs);
                    String value = ReadHmuxString(rs, sublen);

                    Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value);

                    if (!isBusy)
                    {
                        RelayResponseHeader(response, name, value);
                    }
                }
                else if (code == HmuxConnection.HMUX_META_HEADER)
                {
                    String name = ReadHmuxString(rs, sublen);
                    rs.ReadByte();
                    sublen = ReadHmuxLength(rs);
                    String value = ReadHmuxString(rs, sublen);

                    Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value);

                    if ("cpu-load".Equals(name))
                    {
                        double loadAvg = 0.001 * long.Parse(value);

                        hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg);
                    }
                }
                else if (code == HmuxConnection.HMUX_CHANNEL)
                {
                    int channel = sublen;
                    Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel);
                }
                else if (code == HmuxConnection.CSE_SEND_HEADER)
                {
                    Trace.TraceInformation("Hmux[{0}] <<G: send headers", traceId);
                    Skip(rs, sublen);
                }
                else if (code == 0)
                {
                    Trace.TraceInformation("Hmux[{0}] <<0: unknown code (0)", traceId);

                    return(FAIL | EXIT);
                }
                else
                {
                    Trace.TraceInformation("Hmux[{0}] <<?: unknown code ({1})", traceId, code);
                    Skip(rs, sublen);
                }
            }
            Trace.TraceInformation("Hmux[{0}] end of file", traceId);

            // server/269q
            if (hasStatus)
            {
                return(isBusy ? BUSY | EXIT : OK | EXIT);
            }
            else
            {
                // Trace.TraceInformation("Hmux[{0}] unexpected end of file", traceId, code);
                return(FAIL | EXIT);
            }
        }
예제 #54
0
 public DuplexBufferedStream(Stream stream, int bufferSize)
 {
     _readStream  = new BufferedStream(stream, bufferSize);
     _writeStream = new BufferedStream(stream, bufferSize);
     _bufferSize  = bufferSize;
 }
예제 #55
0
 private void WriteRequestData(BufferedStream stream, int code, byte[] data, int length, String traceId)
 {
     stream.WriteByte(HmuxConnection.HMUX_DATA);
     WriteHmuxLength(stream, length);
     stream.Write(data, 0, length);
 }
예제 #56
0
        public override void Action(TcpClient socket, string content, string[] Route)
        {
            if (Header.ContainsKey("Host"))
            {
                FFmpeg.Http = Http = "http://" + Header["Host"] + "/";
            }

            if (Route[1].ToLower() == "webapi")
            {
                #region 版本V2
                if (Route[2].ToLower() == "iscs.wcs.vms" || string.IsNullOrEmpty(Route[2].ToLower()))
                {
                    MergeResult NvrVideo  = new MergeResult();
                    MergeResult CifsVideo = new MergeResult();
                    bool        resgobal  = false;
                    bool        reslocal  = false;
                    #region 合并
                    if (Route[3].ToLower() == "mergevideo")
                    {
                        List <object> para  = JsonConvert.DeserializeObject <List <object> >(content);
                        ReuestInfo    param = JsonConvert.DeserializeObject <ReuestInfo>(para[0].ToString());

                        if (param == null)
                        {
                            param = new ReuestInfo();
                        }
                        else
                        {
                            param.Hash = HashCode.GetHash(content);
                            resgobal   = Strap.RequestGobal(param.Channels, param.PackageUkid + "_" + param.Hash);
                            NvrVideo   = FFmpeg.MergeVideo(param.PackageUkid + "_" + param.Hash + "_gobal");

                            reslocal  = Strap.RequestLocal(long.Parse(param.PackageUkid));
                            CifsVideo = FFmpeg.MergeVideo(param.PackageUkid.ToString() + "_local");
                        }
                        NvrVideo.PackageUkid  = long.Parse(param.PackageUkid);
                        CifsVideo.PackageUkid = long.Parse(param.PackageUkid);
                        string id     = Guid.NewGuid().ToString().Replace("-", "");
                        string result = new ReturnResult().Json(NvrVideo, CifsVideo, id);
                        SendCode(socket, result);
                    }
                    #endregion
                    #region 设置OSD
                    else if (Route[3].ToLower() == "osd")
                    {
                        // HttpRespone.RequestForm(content);
                        List <object> param = JsonConvert.DeserializeObject <List <object> >(content);
                        _log.Error(param[0] + "." + param[1] + "." + param[2]);
                        if (Strap.Device != null)
                        {
                            bool result = Strap.Device.IPCOSD(param[0].ToString(), param[1].ToString(), param[2].ToString());
                            if (result)
                            {
                                SendJson(socket, "{\"result\":\"ok\"}");
                            }
                            else
                            {
                                _log.Error(Strap.Device.ErrorMsg);
                                SendJson(socket, "{\"result\":\"fail\",\"msg\":\"" + Strap.Device.ErrorMsg + "\"}");
                            }
                        }
                        else
                        {
                            SendJson(socket, "{\"result\":\"ok\"}");
                        }
                    }
                    #endregion
                    #region 保存图片
                    else if (Route[3].ToLower() == "saveimage")
                    {
                        // HttpRespone.RequestForm(content);
                        string name = DateTime.Now.Ticks + ".jpg";
                        if (!Directory.Exists(FFmpeg.FileSavePath))
                        {
                            Directory.CreateDirectory(FFmpeg.FileSavePath);
                        }
                        string        filename = FFmpeg.FileSavePath + name;
                        List <object> param    = JsonConvert.DeserializeObject <List <object> >(content);
                        bool          re       = Strap.Device.SaveImage(param[0].ToString(), param[1].ToString(), filename);
                        _log.Debug(filename);
                        if (re)
                        {
                            SendJson(socket, "{\"result\":\"ok\",\"url\":\"http://" + _url + "/jpg/" + name + "\"}");
                        }
                        else
                        {
                            SendJson(socket, "{\"result\":\"fail\",\"msg\":\"" + Strap.Device.ErrorMsg + "\"}");
                        }
                    }
                    #endregion
                    #region 获取摄像头
                    else if (Route[3].ToLower() == "camera")
                    {
                        SendJson(socket, JsonConvert.SerializeObject(NVRInfos));
                    }
                    #endregion
                    #region  开始录像
                    else if (Route[3].ToLower() == "savevideo")
                    {
                        List <object> param = JsonConvert.DeserializeObject <List <object> >(content);
                        _log.Error(param[0] + "." + param[1] + "." + param[2]);
                        int id = Strap.Device.SaveVideo(param[0].ToString(), param[1].ToString(), long.Parse(param[2].ToString()));
                        if (id != 0)
                        {
                            SendJson(socket, "{\"result\":\"ok\",\"msg\":" + id + "}");
                        }
                        else
                        {
                            SendJson(socket, "{\"result\":\"fail\",\"msg\":" + Strap.Device.ErrorMsg + "}");
                        }
                    }
                    #endregion
                    #region 停止录像
                    else if (Route[3].ToLower() == "stopvideo")
                    {
                        List <object> param  = JsonConvert.DeserializeObject <List <object> >(content);
                        bool          result = Strap.Device.StopVideo(int.Parse(param[0].ToString()));

                        if (result)
                        {
                            SendJson(socket, "{\"result\":\"ok\"}");
                        }
                        else
                        {
                            SendJson(socket, "{\"result\":\"ok\",\"msg\":\"" + Strap.Device.ErrorMsg + "\"}");
                        }
                    }
                    #endregion
                }
                #endregion
            }
            else if (Route[1].ToLower() == "video")
            {
                string localfile = VirtualDirectory + "video\\" + Route[2].ToLower();
                if (File.Exists(localfile))
                {
                    FileStream     fs  = new FileStream(localfile, FileMode.Open, FileAccess.Read);
                    BufferedStream bs2 = new BufferedStream(fs);

                    HttpRespone.SendHeader(_httpversion, "application/octet-stream", bs2.Length, " 200 OK", ref socket);
                    byte[] bytes = new byte[4096];
                    int    read;
                    while ((read = bs2.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        HttpRespone.SendToBrowser(bytes, ref socket);
                    }
                    bs2.Close();
                }
                else
                {
                    HttpRespone.SendError(_httpversion, "文件存在", ref socket);
                }
            }
            else if (Route[1].ToLower() == "jpg")
            {
                string localfile = VirtualDirectory + "video\\" + Route[2].ToLower();
                if (File.Exists(localfile))
                {
                    FileStream     fs  = new FileStream(localfile, FileMode.Open, FileAccess.Read);
                    BufferedStream bs2 = new BufferedStream(fs);

                    HttpRespone.SendHeader(_httpversion, "image/jpeg", bs2.Length, " 200 OK", ref socket);
                    byte[] bytes = new byte[4096];
                    int    read;
                    while ((read = bs2.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        HttpRespone.SendToBrowser(bytes, ref socket);
                    }
                    bs2.Close();
                }
                else
                {
                    HttpRespone.SendError(_httpversion, "文件存在", ref socket);
                }
            }
            else
            {
                SendCode(socket, HtmlTemp.Html(new HttpCode().AppCode(Strap.Device.NVRInfos), 1));
            }
        }
        public async Task <string> SendGetRequest(string url)
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            System.Net.ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;  //  set the TLS Protocol

            // Create the web request
            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;

            //  request.ServicePoint.Expect100Continue = false;
            // Set type to POST
            request.Method    = "GET";
            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;
            request.ServicePoint.UseNagleAlgorithm = false;
            // Сообщаем серверу, что умеем работать с zip
            request.Headers.Add("Accept-Encoding", "gzip");

            try
            {
                string result = null;
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                {
                    Stream buffer = null;
                    if (response.ContentEncoding != "gzip")
                    {
                        buffer = new BufferedStream(response.GetResponseStream());
                    }
                    else
                    {
                        buffer = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
                    }

                    using (StreamReader reader = new StreamReader(buffer))
                        result = await reader.ReadToEndAsync();

                    buffer.Dispose();
                }

                return(result);
            }
            catch (WebException wex)
            {
                string errorMessage = String.Format("Status Code: {0}; Message: {1}", wex.Status.ToString(), wex.Message);
                if (wex.Response != null)
                {
                    using (var sr = new StreamReader(wex.Response.GetResponseStream()))
                    {
                        Stream buffer = null;
                        if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).ContentEncoding != "gzip")
                        {
                            buffer = new BufferedStream(wex.Response.GetResponseStream());
                        }
                        else
                        {
                            buffer = new GZipStream(wex.Response.GetResponseStream(), CompressionMode.Decompress);
                        }

                        using (StreamReader reader = new StreamReader(buffer))
                            errorMessage = await reader.ReadToEndAsync();

                        buffer.Dispose();
                    }
                }
                throw new Exception("Provider failed to process request: " + errorMessage);
            }
        }
예제 #58
0
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content,
                SecureRandom random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
                string digestName            = Helper.GetDigestAlgName(digestOID);

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);

                byte[] hash;
                if (outer._digests.Contains(digestOID))
                {
                    hash = (byte[])outer._digests[digestOID];
                }
                else
                {
                    IDigest dig = Helper.GetDigestInstance(digestName);
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(dig));
                    }
                    hash = DigestUtilities.DoFinal(dig);
                    outer._digests.Add(digestOID, hash.Clone());
                }

                IStreamCalculator calculator = sigCalc.CreateCalculator();

#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE
                Stream sigStr = calculator.Stream;
#else
                Stream sigStr = new BufferedStream(calculator.Stream);
#endif

                Asn1Set signedAttr = null;
                if (sAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                    Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new Asn1.Cms.AttributeTable(tmpSigned);
                        }
                    }

                    // TODO Validate proposed signed attributes

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    new DerOutputStream(sigStr).WriteObject(signedAttr);
                }
                else if (content != null)
                {
                    // TODO Use raw signature of the hash value instead
                    content.Write(sigStr);
                }

                Platform.Dispose(sigStr);
                byte[] sigBytes = ((IBlockResult)calculator.GetResult()).Collect();

                Asn1Set unsignedAttr = null;
                if (unsAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
                    Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

                    // TODO Validate proposed unsigned attributes

                    unsignedAttr = outer.GetAttributeSet(unsigned);
                }

                // TODO[RSAPSS] Need the ability to specify non-default parameters
                Asn1Encodable       sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
                AlgorithmIdentifier encAlgId          = Helper.GetEncAlgorithmIdentifier(
                    new DerObjectIdentifier(encOID), sigX509Parameters);

                return(new SignerInfo(signerIdentifier, digAlgId,
                                      signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr));
            }
예제 #59
0
 public MessagesStreamReader(Stream stream)
 {
     this.stream = new BufferedStream(stream);
     this.reader = new BinaryReader(this.stream);
 }
        private void DoGenerate(MmdModel model, MmdMotion motion, string savePath, float frameStepLength,
                                float timeAfterMotionFinish, float physicsStepLength)
        {
            try
            {
                _status = GenerateStatus.Preparing;
                if (physicsStepLength > frameStepLength)
                {
                    physicsStepLength = frameStepLength;
                }
                var poser          = new Poser(model);
                var motionPlayer   = new MotionPlayer(motion, poser);
                var physicsReactor = new BulletPyhsicsReactor();

                var totalTimeLength = motion.Length / 30.0 + timeAfterMotionFinish;
                var totalStepCount  = (int)(totalTimeLength / frameStepLength) + 1;
                var playPos         = 0.0;
                var maxSubSteps     = (int)(frameStepLength / physicsStepLength) + 1;

                using (var fileStream = new FileStream(savePath, FileMode.Create))
                {
                    using (var bufferedStream = new BufferedStream(fileStream))
                    {
                        using (var binaryWriter = new BinaryWriter(bufferedStream))
                        {
                            WriteHeader(binaryWriter, model, totalStepCount + 1, frameStepLength);
                            _status           = GenerateStatus.CalculatingFrames;
                            _totalFrames      = totalStepCount + 1;
                            _calculatedFrames = 0;
                            physicsReactor.AddPoser(poser);
                            motionPlayer.SeekFrame(0);
                            poser.PrePhysicsPosing();
                            physicsReactor.Reset();
                            poser.PostPhysicsPosing();
                            WritePose(binaryWriter, poser);
                            _calculatedFrames = 1;
                            for (var i = 0; i < totalStepCount; ++i)
                            {
                                playPos += frameStepLength;
                                motionPlayer.SeekTime(playPos);
                                poser.PrePhysicsPosing();
                                physicsReactor.React(frameStepLength, maxSubSteps, physicsStepLength);
                                poser.PostPhysicsPosing();
                                WritePose(binaryWriter, poser);
                                _calculatedFrames = i + 2;
                                if (_canceled)
                                {
                                    _status = GenerateStatus.Canceled;
                                    return;
                                }
                            }
                        }
                    }
                }
                _status = GenerateStatus.Finished;
            }
            catch (Exception e)
            {
                _status = GenerateStatus.Failed;
                Debug.LogException(e);
            }
            finally
            {
                if (_status != GenerateStatus.Finished)
                {
                    try
                    {
                        File.Delete(savePath);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
            }
        }