Seek() публичный Метод

public Seek ( long offset, SeekOrigin origin ) : long
offset long
origin SeekOrigin
Результат long
Пример #1
0
    /* add a jpeg frame to an AVI file */
    public void avi_add(u8[] buf, uint size)
    {
        uint osize = size;

        Console.WriteLine(DateTime.Now.Millisecond + " avi frame");
        db_head db = new db_head {
            db = "00dc".ToCharArray(), size = size
        };

        fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db));
        fd.Write(buf, 0, (int)size);
        if (size % 2 == 1)
        {
            size++;
            fd.Seek(1, SeekOrigin.Current);
        }
        nframes++;
        totalsize += size;

        if (((DateTime.Now - start).TotalSeconds * targetfps) > nframes)
        {
            avi_add(buf, osize);
            Console.WriteLine("Extra frame");
        }
    }
 /// <summary>
 /// 分块下载
 /// </summary>
 /// <param name="bufferedStream"></param>
 /// <param name="startPos"></param>
 /// <param name="endPos"></param>
 /// <param name="localFilePath"></param>
 /// <param name="bucketName"></param>
 /// <param name="fileKey"></param>
 private static void Download(BufferedStream bufferedStream, long startPos, long endPos, String localFilePath, String bucketName, String fileKey)
 {
     Stream contentStream = null;
     try
     {
         var getObjectRequest = new GetObjectRequest(bucketName, fileKey);
         getObjectRequest.SetRange(startPos, endPos);
         var ossObject = client.GetObject(getObjectRequest);
         byte[] buffer = new byte[1024 * 1024];
         var bytesRead = 0;
         bufferedStream.Seek(startPos, SeekOrigin.Begin);
         contentStream = ossObject.Content;
         while ((bytesRead = contentStream.Read(buffer, 0, buffer.Length)) > 0)
         {
             bufferedStream.Write(buffer, 0, bytesRead);
         }
     }
     finally
     {
         if (contentStream != null)
         {
             contentStream.Dispose();
         }
     }
 }
Пример #3
0
        public static HashData ComputeHashes(string fileName)
        {
            try
            {
                using (FileStream stream = File.OpenRead(fileName))
                {
                    using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
                    {
                        string md5, sha1, sha256;
                        byte[] checksum;

                        using (var md5Cng = new MD5Cng())
                        {
                            checksum = md5Cng.ComputeHash(bufferedStream);
                            md5 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        stream.Seek(0, SeekOrigin.Begin);
                        bufferedStream.Seek(0, SeekOrigin.Begin);

                        using (var sha1Cng = new SHA1Cng())
                        {
                            checksum = sha1Cng.ComputeHash(bufferedStream);
                            sha1 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        stream.Seek(0, SeekOrigin.Begin);
                        bufferedStream.Seek(0, SeekOrigin.Begin);

                        using (var sha256Cng = new SHA256Cng())
                        {
                            checksum = sha256Cng.ComputeHash(bufferedStream);
                            sha256 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        return new HashData(md5, sha1, sha256);
                    }
                }
            }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
            return null;
        }
Пример #4
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(2048, SeekOrigin.Begin);

        nframes   = 0;
        totalsize = 0;
    }
Пример #5
0
        /// <summary>
        /// Creates the report.
        /// </summary>
        public string CreateReportXAML(string serverUrl, ReportConfig config)
        {
            if (config.StaticXAMLReport != null)
                return config.StaticXAMLReport;

            // load the xslt template
            System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
            try {
                LoadTemplate(xslt, serverUrl, config.ReportGroup, config.ReportTemplate);
            }
            catch (System.Exception) {
                throw new ScrumFactory.Exceptions.ScrumFactoryException("Error_reading_report_template");
            }

            // creates a buffer stream to write the report context in XML
            System.IO.BufferedStream xmlBuffer = new System.IO.BufferedStream(new System.IO.MemoryStream());
            System.Xml.XmlWriterSettings writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.CheckCharacters = false;
            writerSettings.OmitXmlDeclaration = true;

            System.Xml.XmlWriter reportDataStream = System.Xml.XmlWriter.Create(xmlBuffer, writerSettings);

            // write XML start tag
            reportDataStream.WriteStartDocument();
            reportDataStream.WriteStartElement("ReportData");

            // create report context in XML
            CreateDefaultXMLContext(reportDataStream, writerSettings, serverUrl, config);

            // finish XML document
            reportDataStream.WriteEndDocument();
            reportDataStream.Flush();

            xmlBuffer.Seek(0, System.IO.SeekOrigin.Begin);
            // debug
            //System.IO.StreamReader s = new System.IO.StreamReader(xmlBuffer);
            //string ss = s.ReadToEnd();

            System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
            readerSettings.CheckCharacters = false;
            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(xmlBuffer, readerSettings);

            // creates a buffer stream to write the XAML flow document
            System.IO.StringWriter xamlBuffer = new System.IO.StringWriter();

            System.Xml.XmlWriter xamlWriter = System.Xml.XmlWriter.Create(xamlBuffer, writerSettings);

            // creates the flow document XMAL
            xslt.Transform(xmlReader, xamlWriter);

            // sets the flow document at the view
            return xamlBuffer.ToString();
        }
Пример #6
0
        public static void Main(string[] args)
        {
            string filename =
                //"compl.bit";
                //"01-Lovecraft_s Death.mp3";
                //"01-enochian_crescent-tatan.mp3";
                //"bad-info-crc.mp3";
                //"test-id3v1.mp3";
                //"test-id3v2.mp3";
                "test-lame.mp3";

            Stream mp3Stream =
                new BufferedStream(
                    new FileStream(
                        filename,
                        FileMode.Open,
                        FileAccess.Read));

            Mp3Validator validator = new Mp3Validator();
            validator.OnValidationFailure += ValidationFailureEventHandler;
            validator.Validate(mp3Stream);
            Console.WriteLine("Done");
            mp3Stream.Seek(0, SeekOrigin.Begin);

            Mp3StreamReader reader = new Mp3StreamReader(mp3Stream);
            foreach (IMp3StreamRegion region in reader)
            {
            }
            Console.WriteLine("Done");
            mp3Stream.Seek(0, SeekOrigin.Begin);

            while (-1 != mp3Stream.ReadByte())
            {
            }
            Console.WriteLine("Done");

            Console.ReadKey();
        }
Пример #7
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(224, SeekOrigin.Begin);

        nframes         = 0;
        totalsize       = 0;
        max_buff_size   = 0;
        lista_tams      = new List <u32>();
        start_timestamp = DateTime.Now.Ticks;
    }
Пример #8
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(8204, SeekOrigin.Begin);

        indexs.Clear();

        nframes   = 0;
        totalsize = 0;
        start     = DateTime.Now;
    }
Пример #9
0
    /* add a jpeg frame to an AVI file */
    public void avi_add(u8[] buf, uint size)
    {
        Console.WriteLine(DateTime.Now.Millisecond + "avi frame");
        db_head db = new db_head {
            db = "00dc".ToCharArray(), size = size
        };

        fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db));
        fd.Write(buf, 0, (int)size);
        if (size % 2 == 1)
        {
            size++;
            fd.Seek(1, SeekOrigin.Current);
        }
        nframes++;
        totalsize += size;
        lista_tams.Add(size);
        if (size > max_buff_size)
        {
            max_buff_size = size;
        }
    }
Пример #10
0
 /// <summary>
 /// Returns the current content of the stream as a <see cref="BufferedStream"/>
 /// </summary>
 /// <returns><see cref="BufferedStream"/> containing current <see cref="BitStream"/> data</returns>
 public BufferedStream CloneAsBufferedStream()
 {
     BufferedStream bs = new BufferedStream(stream);
     StreamWriter sw = new StreamWriter(bs);
     sw.Write(GetStreamData());
     bs.Seek(0, SeekOrigin.Begin);
     return bs;
 }
Пример #11
0
 /**
  * Reading bytes from stream
  *
  * @param count  bytes count
  * @param stream source stream
  * @return readed bytes
  * @throws IOException reading exception
  */
 public static void skipBytes(int count, /*InputStream*/ BufferedStream  stream)
 {
     try {
         stream.Seek(count, SeekOrigin.Current);
     } catch(IOException e) {
         System.Diagnostics.Debug.WriteLine(e.StackTrace);
         throw e;
     }
 }
Пример #12
0
		/// <summary>Put as binary, i.e. read and write raw bytes.</summary>
		/// <remarks>
		/// The stream is closed after the transfer is complete if
		/// <see cref="CloseStreamsAfterTransfer"/> is <c>true</c> (the default) and are left
		/// open otherwise.
		/// </remarks>
		/// <param name="srcStream">Input stream of data to put.</param>
		/// <param name="remoteFile">Name of remote file in current directory.</param>
		/// <param name="append"><c>true</c> if appending, <c>false</c> otherwise</param>
        /// <param name="alwaysCloseStreams"><c>true if a local file is being put</c></param>
        /// <returns>Number of bytes transferred.</returns>
        private long PutBinary(Stream srcStream, string remoteFile, bool append, bool alwaysCloseStreams)
        {    
            BufferedStream input = null;
            BufferedStream output = null;
            Exception storedEx = null;
            lastBytesTransferred = 0;
            try
            {
				input = new BufferedStream(srcStream);
                
                InitPut(remoteFile, append);
                
                // get an output stream
                output = new BufferedStream(GetOutputStream());
                
                // if resuming, we skip over the unwanted bytes
                if (resume && resumeMarker > 0)
                {
                    input.Seek(resumeMarker, SeekOrigin.Current);
                }
                else
                    resumeMarker = 0;

                byte[] buf = new byte[transferBufferSize];

                // read a chunk at a time and write to the data socket            
                long monitorCount = 0;
                int count = 0;
                DateTime start = DateTime.Now;
                if (throttler != null)
                {
                    throttler.Reset();
                }

                while ((count = input.Read(buf, 0, buf.Length)) > 0 && !cancelTransfer)
                {
                    output.Write(buf, 0, count);
                    lastBytesTransferred += count;
                    monitorCount += count;

                    if (throttler != null)
                    {
                        throttler.ThrottleTransfer(lastBytesTransferred);
                    }

                    if (BytesTransferred != null && !cancelTransfer && monitorCount >= monitorInterval)
                    {
                        BytesTransferred(this, new BytesTransferredEventArgs(remoteFile, lastBytesTransferred, resumeMarker));
                        monitorCount = 0;
                    }
                    start = SendServerWakeup(start);
                }
            }
            catch (Exception ex)
            {
                log.Error("Caught exception " + ex.Message);
                storedEx = ex;              
            }
            finally
            {
                resume = false;
                resumeMarker = 0;
                try
                {
                    if ((alwaysCloseStreams || closeStreamsAfterTransfer))
                    {
                        log.Debug("Closing source stream");
                        if (input != null)
                            input.Close();
                    }
                }
                catch (SystemException ex)
                {
                    log.Warn("Caught exception closing stream", ex);
                }
                
				try 
				{
					if (output!=null)
	                    output.Flush();
				}
				catch (SystemException ex)
				{
					log.Warn("Caught exception flushing output-stream", ex);
				}
                CloseDataSocket(output);
                
                // if we did get an exception bail out now
                if (storedEx != null) 
				{
                    log.Error("Caught exception", storedEx);
                    throw storedEx;
                }
                                
                // notify the final transfer size
                if (BytesTransferred != null && !cancelTransfer)
                    BytesTransferred(this, new BytesTransferredEventArgs(remoteFile, lastBytesTransferred, resumeMarker));            

                // log bytes transferred
                log.Debug("Transferred " + lastBytesTransferred + " bytes to remote host");
            }
            return lastBytesTransferred;
        }
Пример #13
0
        /// <summary>
        /// Creates the report.
        /// </summary>
        public string CreateReportXAML(string serverUrl, ReportConfig config, bool toUseAsHtml = false)
        {
            if (config.StaticXAMLReport != null)
            {
                return(config.StaticXAMLReport);
            }

            // load the xslt template
            System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
            try {
                LoadTemplate(xslt, serverUrl, config.ReportGroup, config.ReportTemplate);
            }
            catch (System.Exception ex) {
                throw new ScrumFactory.Exceptions.ScrumFactoryException("Error_reading_report_template\n" + ex.Message);
            }

            // creates a buffer stream to write the report context in XML
            System.IO.BufferedStream     xmlBuffer      = new System.IO.BufferedStream(new System.IO.MemoryStream());
            System.Xml.XmlWriterSettings writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.CheckCharacters    = false;
            writerSettings.OmitXmlDeclaration = true;

            System.Xml.XmlWriter reportDataStream = System.Xml.XmlWriter.Create(xmlBuffer, writerSettings);

            // write XML start tag
            reportDataStream.WriteStartDocument();
            reportDataStream.WriteStartElement("ReportData");

            // create report context in XML
            CreateDefaultXMLContext(reportDataStream, writerSettings, serverUrl, config);

            // finish XML document
            reportDataStream.WriteEndDocument();
            reportDataStream.Flush();

            xmlBuffer.Seek(0, System.IO.SeekOrigin.Begin);
            // debug
            //System.IO.StreamReader s = new System.IO.StreamReader(xmlBuffer);
            //string ss = s.ReadToEnd();

            System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings();
            readerSettings.CheckCharacters = false;
            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(xmlBuffer, readerSettings);

            // creates a buffer stream to write the XAML flow document
            System.IO.StringWriter xamlBuffer = new System.IO.StringWriter();

            System.Xml.XmlWriter xamlWriter = System.Xml.XmlWriter.Create(xamlBuffer, writerSettings);

            // creates the flow document XMAL
            xslt.Transform(xmlReader, xamlWriter);

            // sets the flow document at the view
            var xaml = xamlBuffer.ToString();

            if (toUseAsHtml)
            {
                xaml = MDParser.ConvertToHTML(xaml);
            }
            else
            {
                xaml = MDParser.ConvertToXAML(xaml);
            }

            return(xaml);
        }
Пример #14
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(2048,SeekOrigin.Begin);

        nframes = 0;
        totalsize = 0;
    }
	public void Read ()
	{
		mem.Write (new byte [] {0, 1, 2, 3, 4, 5, 6, 7}, 0, 8);
		BufferedStream stream = new BufferedStream (mem);

		byte [] bytes = new byte [10];
		stream.Read (bytes, 0, 3);
		Assert.AreEqual (0, bytes [0], "test#01");
		Assert.AreEqual (0, bytes [1], "test#02");
		Assert.AreEqual (0, bytes [2], "test#03");

		stream.Seek (0, SeekOrigin.Begin);
		stream.Read (bytes, 0, 3);
		Assert.AreEqual (0, bytes [0], "test#04");
		Assert.AreEqual (1, bytes [1], "test#05");
		Assert.AreEqual (2, bytes [2], "test#06");
		Assert.AreEqual (0, bytes [0], "test#07");		

		stream.Read (bytes, 5, 3);
		Assert.AreEqual (3, bytes [5], "test#08");
		Assert.AreEqual (4, bytes [6], "test#09");
		Assert.AreEqual (5, bytes [7], "test#10");
		Assert.AreEqual (0, bytes [8], "test#11");		

		stream.Read (bytes, 0, 10);
		Assert.AreEqual (3, bytes [5], "test#12");
		Assert.AreEqual (4, bytes [6], "test#13");
		Assert.AreEqual (5, bytes [7], "test#14");
		Assert.AreEqual (0, bytes [9], "test#15");				
	}
Пример #16
0
        /// <summary>  
        /// Put as binary, i.e. read and write raw bytes
        /// </summary>
        /// <param name="srcStream">  input stream of data to put
        /// </param>
        /// <param name="remoteFile"> name of remote file we are writing to
        /// </param>
        /// <param name="append">     true if appending, false otherwise
        /// </param>
        private void PutBinary(Stream srcStream, string remoteFile, bool append)
        {
            BufferedStream input = null;
            BinaryWriter output = null;
            SystemException storedEx = null;
            long size = 0;
            try
            {
                input = new BufferedStream(srcStream);

                InitPut(remoteFile, append);

                // get an output stream
                output = new BinaryWriter(data.DataStream);

                // if resuming, we skip over the unwanted bytes
                if (resume)
                {
                    input.Seek(resumeMarker, SeekOrigin.Current);
                }

                byte[] buf = new byte[transferBufferSize];

                if (TransferStarted != null)
                    TransferStarted(this, new EventArgs());

                // read a chunk at a time and write to the data socket
                long monitorCount = 0;
                int count = 0;
                while ((count = input.Read(buf, 0, buf.Length)) > 0 && !cancelTransfer)
                {
                    output.Write(buf, 0, count);
                    size += count;
                    monitorCount += count;
                    if (BytesTransferred != null && monitorCount > monitorInterval)
                    {
                        BytesTransferred(this, new BytesTransferredEventArgs(size));
                        monitorCount = 0;
                    }
                }
            }
            catch (SystemException ex)
            {
                storedEx = ex;
            }
            finally
            {
                resume = false;
                try
                {
                    if (input != null)
                        input.Close();
                }
                catch (SystemException ex)
                {
                    log.Warn("Caught exception closing stream", ex);
                }

                try
                {
                    if (output != null)
                       output.Close();
                }
                catch (SystemException ex)
                {
                    log.Warn("Caught exception closing data socket", ex);
                }

                // if we did get an exception bail out now
                if (storedEx != null)
                    throw storedEx;

                // notify the final transfer size
                if (BytesTransferred != null)
                    BytesTransferred(this, new BytesTransferredEventArgs(size));
                if (TransferComplete != null)
                    TransferComplete(this, new EventArgs());

                // log bytes transferred
                log.Debug("Transferred " + size + " bytes to remote host");
            }
        }
Пример #17
0
        public void With_WebSocket_FailsWithDoubleMessageAwait()
        {
            var handshake = GenerateSimpleHandshake();
            using (var ms = new BufferedStream(new MemoryStream()))
            using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions))
            {
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                ws.ReadMessage();
                ws.ReadMessage();
            }
        }
Пример #18
0
        /// <summary>
        /// We need to make sure that the url that we are trying to treat as a file
        /// lies below the document root of the http server so that people can't grab
        /// random files off your computer while this is running.
        /// </summary>
        public void writeURL()
        {
            try {
                // first check if the request is actually authenticated

                IPEndPoint AC_endpoint = (IPEndPoint)s.RemoteEndPoint;

                if (!HTTPAuthProcessor.AllowedToAccessThisServer(AC_endpoint.Address))
                {
                    // now give the user a 403 and break...
                    writeForbidden();
                    ns.Flush();
                    return;
                }

                querystring = "";
                url = original_url;
                ConsoleOutputLogger.WriteLine("internal HTTP: " + HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()) + " - " + url);
                if (url.StartsWith("/vcr/"))
                {
                    #region VCR request
                    // remove the /vcr/ stuff
                    url = url.Remove(0,5);

                    // set this to true when implementing and reaching a new method
                    bool method_found = false;

                    // check which function is called
                        #region AddSearchterm
                        if (url.ToUpper().StartsWith("ADDSEARCHTERM"))
                        {
                            method_found = true;
                            url = url.Remove(0, 14);

                            // let's check for the category

                            // TODO: better Querystring Handling!!!!

                            string[] splitted = url.Split('&');

                            string categoryname = "";
                            string newsearchterm = "";

                            string[] splitted2 = splitted[0].Split('=');
                            string[] splitted3 = splitted[1].Split('=');

                            if (splitted2[0].ToUpper() == "CATEGORY")
                            {
                                categoryname = splitted2[1];
                            }
                            if (splitted3[0].ToUpper() == "NEW_TERM")
                            {
                                newsearchterm = splitted3[1];
                            }

                            if ((newsearchterm != "") & (categoryname != ""))
                            {
                                string Output;

                                if (HTTPServer.vcr_scheduler.Category_Processor.AddSearchTerm(HttpUtility.UrlDecode(categoryname, Encoding.UTF7), HttpUtility.UrlDecode(newsearchterm, Encoding.UTF7)))
                                {
                                    // check if there's already a category with that name
                                    Output = ForwardToPage("Searchterm " + HttpUtility.UrlDecode(newsearchterm, Encoding.UTF7) + " successfully added to the category " + HttpUtility.UrlDecode(categoryname, Encoding.UTF7), "/editcategory_step3.html?category="+categoryname);
                                }
                                else
                                {
                                    Output = ForwardToPage("Error: Searchterm not added...", "/editcategory_step3.html?category=" + categoryname);
                                }
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();
                            }
                            // if not..well forget about it
                        }
                        #endregion

                        #region DelSearchterm
                        if (url.ToUpper().StartsWith("DELSEARCHTERM"))
                        {
                            method_found = true;
                            url = url.Remove(0, 14);

                            // let's check for the category

                            // TODO: better Querystring Handling!!!!

                            string[] splitted = url.Split('&');

                            string categoryname = "";
                            string searchterm = "";

                            string[] splitted2 = splitted[0].Split('=');
                            string[] splitted3 = splitted[1].Split('=');

                            if (splitted2[0].ToUpper() == "CATEGORY")
                            {
                                categoryname = splitted2[1];
                            }
                            if (splitted3[0].ToUpper() == "TERM")
                            {
                                searchterm = splitted3[1];
                            }

                            if ((searchterm != "") & (categoryname != ""))
                            {
                                string Output;

                                if (HTTPServer.vcr_scheduler.Category_Processor.DelSearchTerm(HttpUtility.UrlDecode(categoryname, Encoding.UTF7), HttpUtility.UrlDecode(searchterm, Encoding.UTF7)))
                                {
                                    // check if there's already a category with that name
                                    Output = ForwardToPage("Searchterm " + HttpUtility.UrlDecode(searchterm, Encoding.UTF7) + " successfully deleted from category " + HttpUtility.UrlDecode(categoryname, Encoding.UTF7), "/editcategory_step4.html?category=" + categoryname);
                                }
                                else
                                {
                                    Output = ForwardToPage("Error: Searchterm not deleted...", "/editcategory_step4.html?category=" + categoryname);
                                }
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();
                            }
                            // if not..well forget about it
                        }
                        #endregion

                        #region AddCategory
                        if (url.ToUpper().StartsWith("ADDCATEGORY"))
                        {
                            method_found = true;
                            url = url.Remove(0, 12);

                            string[] splitted = url.Split('=');
                            if (splitted[0].ToUpper() == "CATEGORYNAME")
                            {
                                string Output;
                                // check if there's already a category with that name

                                // it's UTF7 in this case because it comes directly from the browser...
                                if (HTTPServer.vcr_scheduler.Category_Processor.AddCategory(HttpUtility.UrlDecode(splitted[1], Encoding.UTF7)))
                                {
                                    Output = ForwardToPage("Category " + HttpUtility.UrlDecode(splitted[1], Encoding.UTF7) + " successfully added..", "/addcategory.html");
                                }
                                else
                                {
                                    // failed
                                    Output = ForwardToPage("Error: Category not added...", "/addcategory.html");
                                }
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();
                            }
                        }
                        #endregion

                        #region DelCategory
                        // rewritten addrecording/deleterecording...
                        if (url.ToUpper().StartsWith("DELCATEGORY"))
                        {
                            method_found = true;
                            url = url.Remove(0, 12);

                            string[] splitted = url.Split('=');
                            if (splitted[0].ToUpper() == "DELCATEGORY")
                            {
                                string Output;
                                // it's UTF7 in this case because it comes directly from the browser...
                                if (HTTPServer.vcr_scheduler.Category_Processor.DelCategory(HttpUtility.UrlDecode(splitted[1], Encoding.UTF7)))
                                {
                                    Output = ForwardToPage("Category " + HttpUtility.UrlDecode(splitted[1], Encoding.UTF7) + " successfully deleted..", "/delcategory.html");
                                }
                                else
                                {
                                    // failed
                                    Output = ForwardToPage("Error: Category not found...", "/delcategory.html");
                                }
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();
                            }
                        }
                        #endregion

                        #region ManageRecording
                        // rewritten addrecording/deleterecording...
                        if (url.ToUpper().StartsWith("MANAGERECORDING"))
                        {
                            url = url.Remove(0, 16);

                            string[] parameterlist = url.Split('&');

                            // what type of function are we calling now?

                            // fix the encoding; UTF8 that is
                            for (int i = 0; i < parameterlist.Length; i++)
                            {
                                string[] split_parameter = HttpUtility.UrlDecode(parameterlist[i], Encoding.UTF8).Split('=');
                                if (split_parameter[0].ToUpper() == "TYPE")
                                {
                                    if (split_parameter[1].ToUpper() == "DEL")
                                    {
                                        url = "DELETERECORDING/" + url;
                                        break;
                                    }
                                    if (split_parameter[1].ToUpper() == "ADD")
                                    {
                                        url = "ADDRECORDING/" + url;
                                        break;
                                    }

                                }
                            }
                        }
                        #endregion

                        #region AddRecording
                        if (url.ToUpper().StartsWith("ADDRECORDING"))
                        {
                            #region CheckAuthentification
                            if (!HTTPAuthProcessor.AllowedToCreateRecordings(AC_endpoint.Address))
                            {
                                // now give the user a 403 and break...
                                writeForbidden();
                                ns.Flush();
                                return;
                            }
                            #endregion

                            method_found = true;
                            url = url.Remove(0, 13);

                            string[] parameterlist = url.Split('&');

                            // fix the encoding; UTF8 that is
                            for (int i = 0; i < parameterlist.Length; i++)
                            {
                                parameterlist[i] = HttpUtility.UrlDecode(parameterlist[i], Encoding.UTF8);
                            }

                            // instantiate new Recording
                            Recording newTimer = new Recording();

                            #region data'n'stuff
                            int s_date = 0, s_month = 0, s_year = 0, s_hour = 0, s_minute = 0, e_date = 0, e_month = 0, e_year = 0, e_hour = 0, e_minute = 0;
                            #endregion

                            // TODO: add some try..catch thingies..
                            foreach (string Parameter in parameterlist)
                            {
                                try
                                {
                                    string[] split_parameter = Parameter.Split('=');

                                    // Zwischenergebniss: s_date=1&s_month=8&s_year=2006&s_hour=12&s_minute=12&e_date=1
                                    // &e_month=8&e_year=2006&e_hour=12&e_minute=12&name=1asdfasdfasf&ch=25

                                    switch (split_parameter[0].ToUpper())
                                    {
                                        case "S_DATE":
                                            s_date = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "S_MONTH":
                                            s_month = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "S_YEAR":
                                            s_year = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "S_HOUR":
                                            s_hour = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "S_MINUTE":
                                            s_minute = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "E_DATE":
                                            e_date = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "E_MONTH":
                                            e_month = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "E_YEAR":
                                            e_year = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "E_HOUR":
                                            e_hour = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "E_MINUTE":
                                            e_minute = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "NAME":
                                            newTimer.Recording_Name = HttpUtility.UrlDecode(split_parameter[1], Encoding.UTF8); // UTF-8 Decoding..
                                            break;
                                        case "CH":
                                            newTimer.Channel = HttpUtility.UrlDecode(split_parameter[1], Encoding.UTF8);// UTF-8 Decoding..
                                            break;
                                        case "REPEAT":
                                            if (split_parameter[1].ToUpper() == "DAILY")
                                                newTimer.isDaily = true;
                                            if (split_parameter[1].ToUpper() == "WEEKLY")
                                                newTimer.isWeekly = true;
                                            if (split_parameter[1].ToUpper() == "MONTHLY")
                                                newTimer.isMonthly = true;
                                            break;
                                        case "MO":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[0] = true;
                                            break;
                                        case "TU":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[1] = true;
                                            break;
                                        case "WE":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[2] = true;
                                            break;
                                        case "TH":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[3] = true;
                                            break;
                                        case "FR":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[4] = true;
                                            break;
                                        case "SA":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[5] = true;
                                            break;
                                        case "SU":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.Week[6] = true;
                                            break;
                                        case "HOLD":
                                            newTimer.HoldingTime = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        case "IA":
                                            if (split_parameter[1].ToUpper() == "ON")
                                                newTimer.isAutomaticEPGRecording = true;
                                            break;
                                        case "AK":
                                            newTimer.AutomaticEPGRecordingKeywords.Add(HttpUtility.UrlDecode(split_parameter[1], Encoding.UTF8));
                                            break;
                                        case "ARL":
                                            newTimer.AutomaticRecordingLength = Convert.ToInt32(split_parameter[1]);
                                            break;
                                        default:
                                            // alles andere interessiert uns nicht
                                            break;
                                    }
                                }
                                catch (Exception e)
                                {
                                    ConsoleOutputLogger.WriteLine("AddRecording: "+e.Message);
                                }
                            }
                            // TODO: add more checks for name+channel

                            // we're trying to map the given name to a number...
                            int ChannelNumber = ChannelAndStationMapper.Name2Number(newTimer.Channel);

                            if (ChannelNumber != -1)
                            {
                                ConsoleOutputLogger.WriteLine("Apparently the channel " + newTimer.Channel + " has the number " + Convert.ToString(ChannelNumber));
                                // we found something...
                                newTimer.Channel = Convert.ToString(ChannelNumber);
                            }

                            // try to map the IP to an username
                            newTimer.createdby = HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString());

                            ConsoleOutputLogger.WriteLine("Apparently the username is " + newTimer.createdby);

                            // check if HoldingTime isn't already set...
                            if (newTimer.HoldingTime == 0)
                            {
                                newTimer.HoldingTime = HTTPAuthProcessor.GetAccordingHoldingTime(AC_endpoint.Address.ToString());
                            }

                            ConsoleOutputLogger.WriteLine("Apparently this users HoldingTime is " + newTimer.HoldingTime);

                            // TODO: check if there are enough information given to actually create that timer
                            try
                            {
                                if ((s_year + s_month + s_date != 0))
                                {
                                    newTimer.StartsAt = new DateTime(s_year, s_month, s_date, s_hour, s_minute, 0);
                                    newTimer.EndsAt = new DateTime(e_year, e_month, e_date, e_hour, e_minute, 0);
                                }
                                else
                                {
                                    if (s_hour+s_minute+e_minute+e_hour != 0)
                                    {
                                        newTimer.StartsAt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, s_hour, s_minute, 0);
                                        newTimer.EndsAt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, e_hour, e_minute, 0);
                                    }
                                    else
                                    {
                                        newTimer.StartsAt = new DateTime();
                                        newTimer.EndsAt = new DateTime();
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                ConsoleOutputLogger.WriteLine("AddRecording: " + e.Message);
                            }
                            //newTimer.Recording_Filename = newTimer.Recording_ID.ToString();

                            // TODO: check for other timers that could possibly concur...
                            lock (HTTPServer.vcr_scheduler.Recordings.SyncRoot)
                            {
                                HTTPServer.vcr_scheduler.Recordings.Add(newTimer.Recording_ID, newTimer);
                            }

                            // tell the client that everything went fine...
                            string Output = ForwardToIndexHTML("New Timer created...");
                            byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                            int left = new UnicodeEncoding().GetByteCount(Output);
                            writeSuccess(left);
                            ns.Write(buffer, 0, left);
                            ns.Flush();

                            // Save the new Configuration...
                            HTTPServer.Configuration.SaveSettings();
                        }
                        #endregion

                        #region DeleteRecording
                        if (url.ToUpper().StartsWith("DELETERECORDING"))
                        {
                            // TODO: implement correct manage-recording version...
                            method_found = true;
                            // remove the /vcr/deleterecording? stuff
                            url = url.Remove(0, 16);

                            string[] splitted = url.Split('=');
                            if (splitted[0].ToUpper() == "ID")
                            {
                                Guid delete_entry_id = Guid.NewGuid();
                                string recording_name = "";
                                string recording_username = "";

                                lock (HTTPServer.vcr_scheduler.Recordings.SyncRoot)
                                {
                                    foreach (Recording recording_entry in HTTPServer.vcr_scheduler.Recordings.Values)
                                    {
                                        string original = recording_entry.Recording_ID.ToString();

                                        if (original == (splitted[1]))
                                        {
                                            recording_name = recording_entry.Recording_Name;
                                            delete_entry_id = recording_entry.Recording_ID;
                                            recording_username = recording_entry.createdby;
                                        }
                                    }
                                }
                                #region CheckAuthentification
                                if (!HTTPAuthProcessor.AllowedToDeleteRecordings(AC_endpoint.Address,recording_username))
                                {
                                    // now give the user a 403 and break...
                                    writeForbidden();
                                    ns.Flush();
                                    return;
                                }
                                #endregion

                                bool deleted = true;
                                try
                                {
                                    lock (HTTPServer.vcr_scheduler.Recordings.SyncRoot)
                                    {
                                        HTTPServer.vcr_scheduler.Recordings.Remove(delete_entry_id);
                                    }
                                }
                                catch (Exception)
                                {
                                    // failed
                                    deleted = false;
                                }
                                // tell the client that everything went fine...
                                string Output;
                                if (deleted)
                                    Output = ForwardToPage("Recording: " + recording_name + " successfully deleted...","/index.html");
                                else
                                    Output = ForwardToPage("Error: Recording not deleted...","/index.html");
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();

                                // Save the new Configuration...
                                HTTPServer.Configuration.SaveSettings();
                            }
                            else
                            {
                                string[] parameterlist = url.Split('&');

                                // fix the encoding; UTF8 that is
                                for (int i = 0; i < parameterlist.Length; i++)
                                {
                                    parameterlist[i] = HttpUtility.UrlDecode(parameterlist[i], Encoding.UTF8);
                                }

                                // instantiate new Recording
                                Recording newTimer = new Recording();

                                #region data'n'stuff
                                int s_date = 0, s_month = 0, s_year = 0, s_hour = 0, s_minute = 0, e_date = 0, e_month = 0, e_year = 0, e_hour = 0, e_minute = 0;
                                #endregion

                                // find some information to identify the recording and delete it...
                                try
                                {
                                    foreach (string Parameter in parameterlist)
                                    {
                                        string[] split_parameter = Parameter.Split('=');

                                        // Zwischenergebniss: s_date=1&s_month=8&s_year=2006&s_hour=12&s_minute=12&e_date=1
                                        // &e_month=8&e_year=2006&e_hour=12&e_minute=12&name=1asdfasdfasf&ch=25

                                        switch (split_parameter[0].ToUpper())
                                        {
                                            case "S_DATE":
                                                s_date = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "S_MONTH":
                                                s_month = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "S_YEAR":
                                                s_year = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "S_HOUR":
                                                s_hour = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "S_MINUTE":
                                                s_minute = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "E_DATE":
                                                e_date = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "E_MONTH":
                                                e_month = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "E_YEAR":
                                                e_year = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "E_HOUR":
                                                e_hour = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "E_MINUTE":
                                                e_minute = Convert.ToInt32(split_parameter[1]);
                                                break;
                                            case "NAME":
                                                newTimer.Recording_Name = HttpUtility.UrlDecode(split_parameter[1], Encoding.UTF8); // UTF-8 Decoding..
                                                break;
                                            case "CH":
                                                newTimer.Channel = HttpUtility.UrlDecode(split_parameter[1], Encoding.UTF8);// UTF-8 Decoding..
                                                break;
                                            default:
                                                // alles andere interessiert uns nicht
                                                break;
                                        }
                                    }

                                    // we're trying to map the given name to a number...
                                    int ChannelNumber = ChannelAndStationMapper.Name2Number(newTimer.Channel);

                                    if (ChannelNumber != -1)
                                    {
                                        // we found something...
                                        newTimer.Channel = Convert.ToString(ChannelNumber);
                                    }

                                    try
                                    {
                                        newTimer.StartsAt = new DateTime(s_year, s_month, s_date, s_hour, s_minute, 0);
                                        newTimer.EndsAt = new DateTime(e_year, e_month, e_date, e_hour, e_minute, 0);
                                    }
                                    catch (Exception e)
                                    {
                                        ConsoleOutputLogger.WriteLine("Deleterecording: " + e.Message);
                                    }
                                    Guid tobedeletedID = Guid.NewGuid();
                                    bool foundanID = false;
                                    string recording_username = "";

                                    // now we search for a corresponding recording ...
                                    lock (HTTPServer.vcr_scheduler.Recordings.SyncRoot)
                                    {
                                        foreach (Recording timer in HTTPServer.vcr_scheduler.Recordings.Values)
                                        {
                                            if (timer.Channel == newTimer.Channel)
                                            {
                                                if (timer.StartsAt == newTimer.StartsAt)
                                                {
                                                    if (timer.EndsAt == newTimer.EndsAt)
                                                    {
                                                        // found it...now save the key
                                                        tobedeletedID = timer.Recording_ID;
                                                        foundanID = true;
                                                        recording_username = timer.createdby;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (foundanID)
                                        {
                                            #region CheckAuthentification
                                            if (!HTTPAuthProcessor.AllowedToDeleteRecordings(AC_endpoint.Address, recording_username))
                                            {
                                                // now give the user a 403 and break...
                                                writeForbidden();
                                                ns.Flush();
                                                return;
                                            }
                                            #endregion

                                            ConsoleOutputLogger.WriteLine("Found Recording ... deleting");
                                            HTTPServer.vcr_scheduler.Recordings.Remove(tobedeletedID);
                                        }
                                    }
                                    // tell the client that everything went fine...
                                    string Output;
                                    if (foundanID)
                                        Output = ForwardToPage("Recording successfully deleted...","/index.html");
                                    else
                                        Output = ForwardToPage("Error: Recording not deleted...","index.html");
                                    byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                    int left = new UnicodeEncoding().GetByteCount(Output);
                                    writeSuccess(left);
                                    ns.Write(buffer, 0, left);
                                    ns.Flush();
                                }
                                catch (Exception e)
                                {
                                    ConsoleOutputLogger.WriteLine("Deleterecording(Findrecording): " + e.Message);
                                    writeFailure();
                                }
                            }
                        }
                        #endregion

                        #region RemoveRecordingFile
                        if (url.ToUpper().StartsWith("REMOVERECORDINGFILE"))
                        {
                            method_found = true;
                            // remove the deleterecording? stuff
                            url = url.Remove(0, 20);

                            string[] splitted = url.Split('=');
                            if (splitted[0].ToUpper() == "ID")
                            {
                                Guid delete_entry_id = Guid.NewGuid();
                                //String delete_entry_filename = "";

                                Recording tobedeletedrecording = null;

                                lock (HTTPServer.vcr_scheduler.doneRecordings.SyncRoot)
                                {
                                    foreach (Recording recording_entry in HTTPServer.vcr_scheduler.doneRecordings.Values)
                                    {
                                        string original = recording_entry.Recording_ID.ToString();

                                        if (original == splitted[1])
                                        {
                                            tobedeletedrecording = recording_entry;
                                        }
                                    }
                                }
                                bool deleted = true;

                                #region CheckAuthentification
                                if (!HTTPAuthProcessor.AllowedToDeleteRecordings(AC_endpoint.Address, tobedeletedrecording.createdby))
                                {
                                    // now give the user a 403 and break...
                                    writeForbidden();
                                    ns.Flush();
                                    return;
                                }
                                #endregion

                                try
                                {
                                    lock (HTTPServer.vcr_scheduler.doneRecordings.SyncRoot)
                                    {
                                        // remove file
                                        File.Delete(tobedeletedrecording.Recording_Filename);

                                        // remove entry in Hashtable
                                        HTTPServer.vcr_scheduler.doneRecordings.Remove(tobedeletedrecording.Recording_ID);
                                    }
                                }
                                catch (Exception)
                                {
                                    // failed
                                    deleted = false;
                                }
                                // tell the client that everything went fine...
                                string Output;
                                if (deleted)
                                    Output = ForwardToPage("Recording: " + tobedeletedrecording.Recording_Name + " successfully deleted...","/recordings.html");
                                else
                                    Output = ForwardToPage("Error: Recording not deleted...", "/recordings.html");
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();

                                // Remove the playlist file for the XBMC player
                                if (deleted)
                                {
                                    try
                                    {
                                        File.Delete(XBMCPlaylistFilesHelper.generatePlaylistFilename(tobedeletedrecording));
                                        File.Delete(XBMCPlaylistFilesHelper.generateThumbnailFilename(tobedeletedrecording));
                                    }
                                    catch
                                    {
                                        ConsoleOutputLogger.WriteLine("HTTP Server Exception: Could not delete the playlistfile for " + tobedeletedrecording.Recording_Name);
                                    }
                                }

                                // Save the new Configuration...
                                HTTPServer.Configuration.SaveSettings();
                            }
                            else
                                writeFailure();

                        }
                        #endregion

                        #region Reset PlayPosition
                        if (url.ToUpper().StartsWith("RESETRECORDING"))
                        {
                            method_found = true;
                            // remove the deleterecording? stuff
                            url = url.Remove(0, 15);

                            string[] splitted = url.Split('=');
                            if (splitted[0].ToUpper() == "ID")
                            {
                                Guid delete_entry_id = Guid.NewGuid();

                                lock (HTTPServer.vcr_scheduler.doneRecordings.SyncRoot)
                                {
                                    foreach (Recording recording_entry in HTTPServer.vcr_scheduler.doneRecordings.Values)
                                    {
                                        string original = recording_entry.Recording_ID.ToString();

                                        if (original == splitted[1])
                                        {
                                            recording_entry.SetLastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()),0);
                                        }
                                    }
                                }
                                string Output;
                                Output = ForwardToPage("Recording PlayPosition was reset...", "/recordings.html");
                                byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                                int left = new UnicodeEncoding().GetByteCount(Output);
                                writeSuccess(left);
                                ns.Write(buffer, 0, left);
                                ns.Flush();

                                // Save the new Configuration...
                                HTTPServer.Configuration.SaveSettings();
                            }
                            else
                                writeFailure();

                        }
                        #endregion

                    if (!method_found)
                    {
                        // nothing to do...
                        writeError(404, "No Method found");
                    }
                    #endregion
                }
                else
                if (url.StartsWith("/rss/"))
                {
                    #region XML RSS feed requests
                    // remove the /rss/ stuff
                    url = url.Remove(0, 5);

                    #region Recordings Listing RSS
                    if (url.ToUpper().StartsWith("RECORDED.XML"))
                    {
                        url = url.Remove(0, 12);

                        System.IO.MemoryStream XMLStream = new System.IO.MemoryStream();

                        RSS.RSSChannel oRSSChannel =  new RSS.RSSChannel("Recorded Listings",HTTPServer.Settings.HTTP_URL, "Displays all the recordings currently available for watching");
                        oRSSChannel.PubDate = System.DateTime.Now.ToString();

                        RSS.RSSImage oRSSImage = new RSS.RSSImage(HTTPServer.Settings.HTTP_URL + "/images/RSS_Logo_YAPS.png", HTTPServer.Settings.HTTP_URL, "YAPS VCR");

                        RSS.RSSRoot oRSSRoot = new RSS.RSSRoot(oRSSChannel,oRSSImage, XMLStream);

                        RSS.RSSItem oRSSItem = null;

                        // now go for a walk with all the Recordings...

                        #region Sort the Recordings Listing
                        List<Recording> sortedDoneRecordingList;
                        lock (HTTPServer.vcr_scheduler.doneRecordings.SyncRoot)
                        {
                            // TODO: add ascending/descending setting + reimplement the sorting algorithm
                            sortedDoneRecordingList = Sorter.SortRecordingTable(HTTPServer.vcr_scheduler.doneRecordings, false);
                        }
                        #endregion

                        // TODO: maybe we can do this without foreach...faster; but because this is not critical function of YAPS...well low priority
                        foreach (Recording recording in sortedDoneRecordingList)
                        {
                            oRSSItem = new RSS.RSSItem(recording.Recording_Name, HTTPServer.Settings.HTTP_URL + "/" + recording.Recording_ID.ToString());
                            oRSSItem.PubDate = recording.StartsAt.ToString();
                            oRSSItem.Comment = recording.Comment;

                            // generate Category List for this recording
                            oRSSItem.Categories = HTTPServer.vcr_scheduler.Category_Processor.RenderCategoryLine(HTTPServer.vcr_scheduler.Category_Processor.AutomaticCategoriesForRecording(recording), ',');

                            oRSSRoot.Items.Add(oRSSItem);
                        }

                        RSS.RSSUtilities.PublishRSS(oRSSRoot);

                        XMLStream.Seek(0, SeekOrigin.Begin);

                        byte[] byteArray = new byte[XMLStream.Length];
                        int xmlcount = XMLStream.Read(byteArray, 0, Convert.ToInt32(XMLStream.Length));

                        writeSuccess(xmlcount,"text/xml");
                        ns.Write(byteArray, 0, xmlcount);
                        ns.Flush();

                        XMLStream.Close();
                    }
                    #endregion

                    #endregion
                }
                else
                if (url.StartsWith("/dvb/"))
                {
                    #region Streaming Request

                    #region CheckAuthentification
                    if (!HTTPAuthProcessor.AllowedToAccessLiveStream(AC_endpoint.Address))
                    {
                        // now give the user a 403 and break...
                        writeForbidden();
                        ns.Flush();
                        return;
                    }
                    #endregion

                    // check if there is a MulticastProcessor Object for this channel
                    VCRandStreaming HReq = new VCRandStreaming(false,null,HTTPServer);

                    #region CheckAuthentification
                    if (!HTTPAuthProcessor.AllowedToAccessLiveStream(AC_endpoint.Address))
                    {
                        // now give the user a 403 and break...
                        writeForbidden();
                        ns.Flush();
                        return;
                    }
                    #endregion

                    try
                    {
                        HReq.HandleStreaming(url, this);
                        while (!HReq.done)
                        {
                            Thread.Sleep(100);
                        }
                        HTTPServer.Settings.NumberOfPlayedLiveTV++;
                    }
                    catch (Exception e)
                    {
                        ConsoleOutputLogger.WriteLine("Streaming error: " + e.Message);
                        try
                        {
                            writeFailure();
                        }
                        catch (Exception)
                        {
                            ConsoleOutputLogger.WriteLine("Streaming error: client disconnected");
                        }
                    }
                    #endregion
                }
                else
                if (url.StartsWith("/xml/"))
                {
                    #region Tuxbox Request
                    #region CheckAuthentification
                    if (!HTTPAuthProcessor.AllowedToAccessTuxbox(AC_endpoint.Address))
                    {
                        // now give the user a 403 and break...
                        writeForbidden();
                        ns.Flush();
                        return;
                    }
                    #endregion

                    url = url.Remove(0,5);

                    // set this to true when implementing and reaching a new method
                    bool method_found = false;

                    // check which function is called

                    #region boxstatus
                    if (url.ToUpper().StartsWith("BOXSTATUS"))
                    {
                        method_found = true;
                        /*
                         * <status>
                         * <current_time>Sat Jul 23 23:03:17 2005</current_time>
                         *  <standby>OFF</standby>
                         *  <recording>OFF</recording>
                         *  <mode>0</mode>
                         *  <ip>192.168.0.10</ip>
                         * </status>
                         *
                         * */
                        StringBuilder boxstatus = new StringBuilder();

                        // of course it would be possible to do this through serializers but it would be
                        // much more hassle than this:

                        boxstatus.AppendLine("<status>");
                        boxstatus.AppendLine("<current_time>"+DateTime.Now.ToString()+"</current_time>");
                        boxstatus.AppendLine("<standby>OFF</standby>");
                        boxstatus.AppendLine("<recording>OFF</recording>");
                        boxstatus.AppendLine("<mode>0</mode>");
                        boxstatus.AppendLine("<ip>"+HTTPServer.ipaddress.ToString()+"</ip>");
                        boxstatus.AppendLine("</status>");

                        byte[] buffer = new UTF8Encoding().GetBytes(boxstatus.ToString());

                        writeSuccess(buffer.Length, "text/xml");

                        ns.Write(buffer, 0, buffer.Length);
                        ns.Flush();

                    }
                    #endregion

                    #region services
                    if (url.ToUpper().StartsWith("SERVICES"))
                    {
                        method_found = true;

                        System.IO.MemoryStream XMLStream = new System.IO.MemoryStream();
                        // TODO: add check if EPGProcessor is even instantiated

                        try
                        {
                            List<tuxbox.bouquet> bouquets = new List<YAPS.tuxbox.bouquet>();

                            // add Currently Running events to the list...
                            tuxbox.bouquet currentlyrunningbouquet = TuxboxProcessor.addCurrentlyRunningBouquet(HTTPServer.EPGProcessor);
                            bouquets.Add(currentlyrunningbouquet);

                            XmlRootAttribute xRoot = new XmlRootAttribute();
                            xRoot.ElementName = "bouquets";
                            xRoot.IsNullable = true;

                            System.Xml.Serialization.XmlSerializer xmls = new XmlSerializer(bouquets.GetType(),xRoot);
                            xmls.Serialize(XMLStream, bouquets);

                            XMLStream.Seek(0, SeekOrigin.Begin);

                            byte[] byteArray = new byte[XMLStream.Length];
                            int xmlcount = XMLStream.Read(byteArray, 0, Convert.ToInt32(XMLStream.Length));

                            writeSuccess(xmlcount, "text/xml");
                            ns.Write(byteArray, 0, xmlcount);
                            ns.Flush();

                        }
                        finally
                        {
                            XMLStream.Close();
                        }
                    }
                    #endregion

                    #region streaminfo
                    // Currently broken (!)
                    if (url.ToUpper().StartsWith("STREAMINFO2"))
                    {
                        method_found = true;

                        if (TuxboxProcessor.ZapToChannel != "")
                        {
                            // get the currently running event information for this channel...

                            //EPG_Event_Entry currentlyrunningevent = TuxboxProcessor.getCurrentlyRunningEventOnChannel(TuxboxProcessor.ZapToChannel);

                            /*
                             * 480
                             * 576
                             * 997500
                             * 4:3
                             * 25
                             * joint stereo
                             * */

                            // first of all get the info what's currently running on the ZapedToChannel
                            StringBuilder streaminfo = new StringBuilder();

                            // TODO: add correct aspect ratio, resolution, bitrate

                            streaminfo.AppendLine("768\n"); // vertical resolution
                            streaminfo.AppendLine("576\n"); // horizontal resolution
                            streaminfo.AppendLine("997500\n"); // bitrate
                            streaminfo.AppendLine("4:3\n"); // aspect ratio
                            streaminfo.AppendLine("25\n"); // frames per second
                            streaminfo.AppendLine("joint stereo\n"); // audio information

                            byte[] buffer = new UTF8Encoding().GetBytes(streaminfo.ToString());

                            writeSuccess(buffer.Length, "text/html");

                            ns.Write(buffer, 0, buffer.Length);
                            ns.Flush();
                        }
                        else
                        {
                            ConsoleOutputLogger.WriteLine("No ZappedTo Channel found. Please first do a /cgi-bin/ZapTo?Path=");
                            writeFailure();
                        }
                    }
                    #endregion

                    #region currentservicedata
                    if (url.ToUpper().StartsWith("CURRENTSERVICEDATA"))
                    {
                        method_found = true;

                        if (TuxboxProcessor.ZapToChannel != "")
                        {
                            // get the currently running event information for this channel...
                            EPG_Event_Entry currentlyrunningevent = TuxboxProcessor.getCurrentlyRunningEventOnChannel(TuxboxProcessor.ZapToChannel,HTTPServer.EPGProcessor);

                            System.IO.MemoryStream XMLStream = new System.IO.MemoryStream();
                            // TODO: add check if EPGProcessor is even instantiated
                            if (currentlyrunningevent != null)
                            {
                                try
                                {
                                    YAPS.tuxbox.currentservicedata CurrentServiceData_ = new YAPS.tuxbox.currentservicedata();

                                    XmlRootAttribute xRoot = new XmlRootAttribute();
                                    xRoot.ElementName = "currentservicedata";
                                    xRoot.IsNullable = true;

                                    // TODO: this is default... implement later
                                    YAPS.tuxbox.channel channel = new YAPS.tuxbox.channel();
                                    channel.Name = "Stereo";
                                    channel.pid = "0x01";
                                    channel.selected = 1;

                                    CurrentServiceData_.audio_channels.Add(channel);

                                    CurrentServiceData_.current_event.date = currentlyrunningevent.StartTime.ToShortDateString();
                                    CurrentServiceData_.current_event.description = currentlyrunningevent.ShortDescription.Name;
                                    CurrentServiceData_.current_event.details = currentlyrunningevent.ShortDescription.Text;

                                    TimeSpan event_duration = currentlyrunningevent.EndTime - currentlyrunningevent.StartTime;

                                    CurrentServiceData_.current_event.duration = event_duration.Minutes.ToString();
                                    CurrentServiceData_.current_event.start = currentlyrunningevent.StartTime.Ticks.ToString();
                                    CurrentServiceData_.current_event.time = currentlyrunningevent.StartTime.ToShortTimeString();

                                    CurrentServiceData_.next_event = CurrentServiceData_.current_event;
                                    CurrentServiceData_.service.name = TuxboxProcessor.ZapToChannel;
                                    CurrentServiceData_.service.reference = TuxboxProcessor.ZapToChannel;

                                    System.Xml.Serialization.XmlSerializer xmls = new XmlSerializer(CurrentServiceData_.GetType(), xRoot);
                                    xmls.Serialize(XMLStream, CurrentServiceData_);

                                    XMLStream.Seek(0, SeekOrigin.Begin);

                                    byte[] byteArray = new byte[XMLStream.Length];
                                    int xmlcount = XMLStream.Read(byteArray, 0, Convert.ToInt32(XMLStream.Length));

                                    writeSuccess(xmlcount, "text/xml");
                                    ns.Write(byteArray, 0, xmlcount);
                                    ns.Flush();

                                }
                                finally
                                {
                                    XMLStream.Close();
                                }
                            }
                            else
                            {
                                ConsoleOutputLogger.WriteLine("There are no CurrentlyRunningEvents we know off. Check EPG!");
                                writeFailure();
                            }
                        }
                        else
                        {
                            ConsoleOutputLogger.WriteLine("No ZappedTo Channel found. Please first do a /cgi-bin/ZapTo?Path=");
                            writeFailure();
                        }
                    }
                    #endregion

                    #region boxinfo
                    if (url.ToUpper().StartsWith("BOXINFO"))
                    {
                        method_found = true;

                        System.IO.MemoryStream XMLStream = new System.IO.MemoryStream();
                        // TODO: add check if EPGProcessor is even instantiated

                        try
                        {
                            XmlRootAttribute xRoot = new XmlRootAttribute();
                            xRoot.ElementName = "boxinfo";
                            xRoot.IsNullable = true;

                            YAPS.tuxbox.boxinfo boxinfo = new YAPS.tuxbox.boxinfo();

                            boxinfo.disk = "none";
                            boxinfo.firmware = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                            boxinfo.fpfirmware = "n/a";
                            boxinfo.image.version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                            boxinfo.image.catalog = "http://www.technology-ninja.com";
                            boxinfo.image.comment = "Yet Another Proxy Server: UDP Multicast to TCP Unicast Proxy";
                            boxinfo.image.url = "http://www.technology-ninja.com";
                            boxinfo.manufacturer = "(C) 2006-2007 Daniel Kirstenpfad and the YAPS Team";
                            boxinfo.model = "YAPS";
                            boxinfo.processor = "n/a";
                            boxinfo.usbstick = "none";
                            boxinfo.webinterface = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

                            System.Xml.Serialization.XmlSerializer xmls = new XmlSerializer(boxinfo.GetType(), xRoot);
                            xmls.Serialize(XMLStream, boxinfo);

                            XMLStream.Seek(0, SeekOrigin.Begin);

                            byte[] byteArray = new byte[XMLStream.Length];
                            int xmlcount = XMLStream.Read(byteArray, 0, Convert.ToInt32(XMLStream.Length));

                            writeSuccess(xmlcount, "text/xml");
                            ns.Write(byteArray, 0, xmlcount);
                            ns.Flush();
                        }
                        finally
                        {
                            XMLStream.Close();
                        }
                    }
                    #endregion

                    if (!method_found)
                    {
                        ConsoleOutputLogger.WriteLine("Tuxbox stuff is coming soon");
                        writeFailure();
                    }
                    #endregion
                }
                else
                if (url.StartsWith("/cgi-bin/"))
                {
                    bool method_found = false;

                    // remove the start
                    url = url.Remove(0, 9);

                    #region Tuxbox Requests
                    #region CheckAuthentification
                    if (!HTTPAuthProcessor.AllowedToAccessTuxbox(AC_endpoint.Address))
                    {
                        // now give the user a 403 and break...
                        writeForbidden();
                        ns.Flush();
                        return;
                    }
                    #endregion

                    #region zapTo
                    if (url.ToUpper().StartsWith("ZAPTO?PATH="))
                    {
                        method_found = true;

                        url = url.Remove(0, 11);

                        if (ChannelAndStationMapper.Name2Number(url) != -1)
                        {
                            TuxboxProcessor.ZapToChannel = url;

                            String Output = "ok";
                            byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                            int left = new UnicodeEncoding().GetByteCount(Output);
                            writeSuccess(left);
                            ns.Write(buffer, 0, left);
                            ns.Flush();
                        }
                        else
                        {
                            ConsoleOutputLogger.WriteLine("Station not found, cannot zap to this channel: "+url);

                            String Output = "error";
                            byte[] buffer = new UnicodeEncoding().GetBytes(Output);
                            int left = new UnicodeEncoding().GetByteCount(Output);
                            writeSuccess(left);
                            ns.Write(buffer, 0, left);
                            ns.Flush();
                        }
                    }
                    #endregion

                    #endregion

                    if (!method_found)
                    {
                        ConsoleOutputLogger.WriteLine("Tuxbox stuff is coming soon");
                        writeFailure();
                    }

                }
                else
                {
                    #region File request (everything else...)

                    #region default page
                    if (url == "/")
                    {
                        url = "/index.html";
                    }
                    #endregion

                    // check if we have some querystring parameters
                    if (url.Contains("?"))
                    {
                        // yes, remove everything after the ? from the url but save it to querystring
                        querystring = url.Substring(url.IndexOf('?') + 1);
                        url = url.Remove(url.IndexOf('?'));
                    }

                    // Replace the forward slashes with back-slashes to make a file name
                    string filename = url.Replace('/', Path.DirectorySeparatorChar); //you have different path separators in unix and windows

                    #region Update the Playcount (eventually)
                    Recording currentlyPlaying = null;
                    // HACK: eventually this breaks when the recording path becomes configurable...take care of that!
                    try
                    {
                        // Strip first character (which should be the DirectorySeparator)
                        string doneRecordingFilename = filename.Remove(0, 1);

                        lock (HTTPServer.vcr_scheduler.doneRecordings)
                        {
                            // TODO: maybe we can do this without foreach...faster; but because this is not critical function of YAPS...well low priority
                            foreach (Recording recording in HTTPServer.vcr_scheduler.doneRecordings.Values)
                                if (recording.Recording_ID.ToString() == doneRecordingFilename)
                                {
                                    #region CheckAuthentification
                                    if (!HTTPAuthProcessor.AllowedToAccessRecordings(AC_endpoint.Address))
                                    {
                                        // now give the user a 403 and break...
                                        writeForbidden();
                                        ns.Flush();
                                        return;
                                    }
                                    // check if this recording is the Recording of another user
                                    //if (HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()).ToUpper() != recording.Username.ToUpper())
                                    //{
                                    //    if (HTTPAuthProcessor.AllowedToAccessOthersRecordings(AC_endpoint.Address))
                                    //    {
                                    //        // now give the user a 403 and break...
                                    //        writeForbidden();
                                    //        ns.Flush();
                                    //        return;
                                    //    }
                                    //}
                                    #endregion

                                    currentlyPlaying = recording;
                                    recording.PlayCount++;
                                    HTTPServer.Settings.NumberOfPlayedRecordings++;
                                    recording.LastTimePlayed = DateTime.Now;
                                    ConsoleOutputLogger.WriteLine("Increasing Playcount for Recording " + recording.Recording_Name);
                                    HTTPServer.Configuration.SaveSettings();
                                }
                        }
                    }
                    catch (Exception e)
                    {
                        ConsoleOutputLogger.WriteLine("HTTP.UpdatePlayCount: " + e.Message);
                    }
                    #endregion
                    try
                    {
                        // Construct a filename from the doc root and the filename
                        FileInfo file = new FileInfo(docRootFile + filename);
                        // Make sure they aren't trying in funny business by checking that the
                        // resulting canonical name of the file has the doc root as a subset.
                        filename = file.FullName;
                        if (!filename.StartsWith(docRootFile.FullName))
                        {
                            writeForbidden();
                        }
                        else
                        {
                            FileStream fs = null;
                            BufferedStream bs = null;
                            long bytesSent = 0;
                            bool resumed = false;

                            try
                            {
                                if (filename.EndsWith(".log"))
                                {
                                    // now give the user a 403 and break...
                                    writeForbidden();
                                    ns.Flush();
                                }
                                else
                                    if (filename.EndsWith(".html") | (filename.EndsWith(".htm")))
                                    {
                                        ConsoleOutputLogger.WriteLine("[DEBUG] 1");
                                        String Output = HTTPServer.Template_Processor.ProcessHTMLTemplate(filename, querystring, HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()));
                                        ConsoleOutputLogger.WriteLine("[DEBUG] 2");
                                        //int left = new UnicodeEncoding().GetByteCount(Output);
                                        int left = new UTF8Encoding().GetByteCount(Output);

                                        writeSuccess(left, "text/html");

                                        byte[] buffer = new UTF8Encoding().GetBytes(Output);
                                        //HttpServerUtility ut = new HttpServerUtility();

                                        //ut.HtmlEncode(new UTF8Encoding().G

                                        //byte[] buffer = new UnicodeEncoding().GetBytes(Output);

                                        ns.Write(buffer, 0, left);

                                        ns.Flush();
                                    }
                                    else
                                    {
                                        // Open the file for binary transfer
                                        fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                                        long left = file.Length;
                                        bool isThisARecordingRecording = false;

                                        // TODO: make the resuming behaviour for streamed recordings configurable!!
                                        if (currentlyPlaying != null)
                                        {
                                            //if (currentlyPlaying.LastStoppedPosition != 0) resumed = true;
                                            left = file.Length - currentlyPlaying.LastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()));
                                            bytesSent = currentlyPlaying.LastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()));
                                            writeSuccess(left, "video/mpeg2");
                                            isThisARecordingRecording = true;
                                        }
                                        else
                                        {
                                            // TODO: it'll be nice to handle jpeg/... well known file extensions as different mime types in the future...

                                            #region different mime-type-handling
                                            switch (getFileExtension(filename))
                                            {
                                                case ".css":
                                                    writeSuccess(left, "text/css");
                                                    break;
                                                case ".gif":
                                                    writeSuccess(left, "image/gif");
                                                    break;
                                                case ".png":
                                                    writeSuccess(left, "image/png");
                                                    break;
                                                case ".jpg":
                                                    writeSuccess(left, "image/jpeg");
                                                    break;
                                                case ".jpeg":
                                                    writeSuccess(left, "image/jpeg");
                                                    break;
                                                default:
                                                    // Write the content length and the success header to the stream; it's binary...so treat it as binary
                                                    writeSuccess(left, "application/octet-stream");
                                                    break;
                                            }
                                        }
                                            #endregion

                                        // Copy the contents of the file to the stream, ensure that we never write
                                        // more than the content length we specified.  Just in case the file somehow
                                        // changes out from under us, although I don't know if that is possible.
                                        bs = new BufferedStream(fs);
                                        left = file.Length;

                                        if (currentlyPlaying != null)
                                            bs.Seek(currentlyPlaying.LastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString())), SeekOrigin.Begin);

                                        // for performance reasons...
                                        String tUsername = HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString());
                                        int read;
                                        while (left > 0 && (read = bs.Read(bytes, 0, (int)Math.Min(left, bytes.Length))) != 0)
                                        {
                                            ns.Write(bytes, 0, read);
                                            bytesSent = bytesSent + read;
                                            left -= read;

                                            // check filesize; maybe when we're viewing while recording the filesize may change from time to time...
                                            left = file.Length;

                                            // set the already watched Size...
                                            if (isThisARecordingRecording) currentlyPlaying.SetLastStopPosition(tUsername,bytesSent);
                                        }
                                        ns.Flush();
                                        bs.Close();
                                        fs.Close();

                                        // this happens when we're all done...
                                        if (currentlyPlaying != null)
                                        {
                                            currentlyPlaying.SetLastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()), 0);

                                            // generate Thumbnail
                                            RecordingsThumbnail.CreateRecordingsThumbnail(currentlyPlaying, XBMCPlaylistFilesHelper.generateThumbnailFilename(currentlyPlaying));

                                            HTTPServer.Configuration.SaveSettings();
                                        }
                                    }
                            }
                            catch (Exception e)
                            {
                                ConsoleOutputLogger.WriteLine("writeURL: " + e.Message);
                                try
                                {
                                    writeFailure();
                                }
                                catch (Exception)
                                {
                                    ConsoleOutputLogger.WriteLine("writeURL.Result: connection lost to client");
                                }
                                if (bs != null) bs.Close();
                                if (bs != null) fs.Close();

                                // TODO: make the behaviour configurable: What happens when the streaming did end...and the User restarts..
                                if (!resumed)
                                {
                                    if (currentlyPlaying != null)
                                    {
                                        //currentlyPlaying.SetLastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()), bytesSent);

                                        // generate Thumbnail
                                        RecordingsThumbnail.CreateRecordingsThumbnail(currentlyPlaying, XBMCPlaylistFilesHelper.generateThumbnailFilename(currentlyPlaying));

                                        // Save it
                                        HTTPServer.Configuration.SaveSettings();
                                    }
                                }
                                else
                                {
                                    HTTPServer.Settings.NumberOfPlayedRecordings++;
                                    currentlyPlaying.SetLastStopPosition(HTTPAuthProcessor.IPtoUsername(AC_endpoint.Address.ToString()), 0);
                                    HTTPServer.Configuration.SaveSettings();
                                }

                            }

                        }
                    }
                    catch (Exception e)
                    {
                        ConsoleOutputLogger.WriteLine("HTTPProcessor.writeURL(): " + e.Message);
                        writeFailure();
                    }
                    #endregion
                }
            } catch(Exception e)
            {
                ConsoleOutputLogger.WriteLine("Unhandled http: " + e.Message);
                writeFailure();
            }
        }
	public void Seek ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [] {0, 1, 2, 3, 4, 5}, 0, 6);
		
		Assert.AreEqual (6, stream.Position, "test#01");
		
		stream.Seek (-5, SeekOrigin.End);		
		Assert.AreEqual (1, stream.Position, "test#02");
		
		stream.Seek (3, SeekOrigin.Current);
		Assert.AreEqual (4, stream.Position, "test#03");
		
		stream.Seek (300, SeekOrigin.Current);		
		Assert.AreEqual (304, stream.Position, "test#04");		
	}
	public void Seek_ClosedMemoryStream ()
	{
		MemoryStream ms = new MemoryStream ();
		BufferedStream stream = new BufferedStream (ms);
		ms.Close ();
		stream.Seek (0, SeekOrigin.Begin);
	}
        /// <summary>
        /// Diff working file with last commit
        /// </summary>
        /// <param name="fileName">Expect relative path</param>
        /// <returns></returns>
        public string DiffFile(string fileName)
        {
            try
            {
                if (!this.HasGitRepository) return "";

                HistogramDiff hd = new HistogramDiff();
                hd.SetFallbackAlgorithm(null);

                var fullName = GetFullPath(fileName);

                RawText b = new RawText(File.Exists(GetFullPath(fileName)) ?
                                        File.ReadAllBytes(fullName) : new byte[0]);
                RawText a = new RawText(GetFileContent(fileName) ?? new byte[0]);

                var list = hd.Diff(RawTextComparator.DEFAULT, a, b);

                using (Stream mstream = new MemoryStream(),
                              stream = new BufferedStream(mstream))
                {
                    DiffFormatter df = new DiffFormatter(stream);
                    df.Format(list, a, b);
                    df.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    var ret = new StreamReader(stream).ReadToEnd();

                    return ret;
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("Refresh: {0}\r\n{1}", this.initFolder, ex.ToString());

                return "";
            }
        }
Пример #22
0
        DataHash DigestFile( MD5 provider, string filepath, Regex findDateTime)
        {
            var rv = new DataHash() {
                Result = DataHashResult.FileNotFound,
                InputName = filepath,
            };

            if (!FileUtils.Exists(filepath)) return rv;
            provider.Initialize();
            var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (var bs = new BufferedStream(fs))
            {
                Logging.Emit("digest {0}", filepath);
                rv.Hash = new SoapHexBinary(provider.ComputeHash(bs)).ToString();
                rv.Result = DataHashResult.Ok;
                
                if (findDateTime != null) {
                    // check include cache for this file
                    
                    if (includeCache.ContainsEntry(rv.Hash, F_NotDateTime)) 
                    {
                        return rv;
                    }
                    if (includeCache.ContainsEntry(rv.Hash, F_HasDateTime)) 
                    {
                        rv.Result = DataHashResult.ContainsTimeOrDate;
                        return rv;
                    }

                    bs.Seek(0, SeekOrigin.Begin);
                    using (var ts = new StreamReader(bs))
                    {
                        string line = null;
                        do
                        {
                            line = ts.ReadLine();
                            if (line == null) 
                            {
                                includeCache.WaitOne();
                                try
                                {
                                    includeCache.AddTextFileContent(rv.Hash, F_NotDateTime, "");
                                }
                                finally
                                {
                                    includeCache.ReleaseMutex();
                                }
                                break;
                            }

                            if (findDateTime.IsMatch(line))
                            {
                                rv.Result = DataHashResult.ContainsTimeOrDate;

                                includeCache.WaitOne();
                                try
                                {
                                    includeCache.AddTextFileContent(rv.Hash, F_HasDateTime, "");
                                }
                                finally
                                {
                                    includeCache.ReleaseMutex();
                                }
                                
                                break;
                            }

                        } while (true);
                    }
                }
            }
            rv.Result = DataHashResult.Ok;
            
            return rv;
        }
Пример #23
0
 private long PutBinary(Stream srcStream, string remoteFile, bool append, bool alwaysCloseStreams)
 {
     BufferedStream stream = null;
     BufferedStream stream2 = null;
     Exception t = null;
     long bytesSoFar = 0L;
     try
     {
         stream = new BufferedStream(srcStream);
         this.InitPut(remoteFile, append);
         stream2 = new BufferedStream(this.GetOutputStream());
         if (this.resume)
         {
             stream.Seek(this.resumeMarker, SeekOrigin.Current);
         }
         else
         {
             this.resumeMarker = 0L;
         }
         byte[] buffer = new byte[this.transferBufferSize];
         long num2 = 0L;
         int count = 0;
         DateTime now = DateTime.Now;
         if (this.throttler != null)
         {
             this.throttler.Reset();
         }
         while (((count = stream.Read(buffer, 0, buffer.Length)) > 0) && !this.cancelTransfer)
         {
             stream2.Write(buffer, 0, count);
             bytesSoFar += count;
             num2 += count;
             if (this.throttler != null)
             {
                 this.throttler.ThrottleTransfer(bytesSoFar);
             }
             if (((this.BytesTransferred != null) && !this.cancelTransfer) && (num2 >= this.monitorInterval))
             {
                 this.BytesTransferred(this, new BytesTransferredEventArgs(remoteFile, bytesSoFar, this.resumeMarker));
                 num2 = 0L;
             }
             now = this.SendServerWakeup(now);
         }
     }
     catch (Exception exception2)
     {
         t = exception2;
     }
     finally
     {
         this.resume = false;
         try
         {
             if (alwaysCloseStreams || this.closeStreamsAfterTransfer)
             {
                 this.log.Debug("Closing source stream");
                 if (stream != null)
                 {
                     stream.Close();
                 }
             }
         }
         catch (SystemException exception3)
         {
             this.log.Warn("Caught exception closing stream", exception3);
         }
         try
         {
             if (stream2 != null)
             {
                 stream2.Flush();
             }
         }
         catch (SystemException exception4)
         {
             this.log.Warn("Caught exception flushing output-stream", exception4);
         }
         this.CloseDataSocket(stream2);
         if (t != null)
         {
             this.log.Error("Caught exception", t);
             throw t;
         }
         if ((this.BytesTransferred != null) && !this.cancelTransfer)
         {
             this.BytesTransferred(this, new BytesTransferredEventArgs(remoteFile, bytesSoFar, this.resumeMarker));
         }
         this.log.Debug("Transferred " + bytesSoFar + " bytes to remote host");
     }
     return bytesSoFar;
 }
Пример #24
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(224, SeekOrigin.Begin);
        
        nframes = 0;
        totalsize = 0;
        max_buff_size = 0;
        lista_tams = new List<u32>();
        start_timestamp = DateTime.Now.Ticks;

    }
Пример #25
0
        // ReSharper restore UnusedMember.Local
        private bool Load(ILoadMonitor loader)
        {
            ProgressStatus 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) {}
                }
            }
        }
Пример #26
0
    /* finish writing the AVI file - filling in the header */
    public void avi_end(int width, int height, int fps)
    {
        this.width  = width;
        this.height = height;
        lock (locker)
        {
            targetfps = fps;
        }

        riff_head rh = new riff_head {
            riff = "RIFF".ToCharArray(), size = 0, avistr = "AVI ".ToCharArray()
        };
        list_head lh1 = new list_head {
            list = "LIST".ToCharArray(), size = 0, type = "hdrl".ToCharArray()
        };
        avi_head  ah  = new avi_head();
        list_head lh2 = new list_head {
            list = "LIST".ToCharArray(), size = 0, type = "strl".ToCharArray()
        };
        stream_head sh   = new stream_head();
        frame_head  fh   = new frame_head();
        list_head   junk = new list_head()
        {
            list = "JUNK".ToCharArray(), size = 0
        };
        list_head lh3 = new list_head {
            list = "LIST".ToCharArray(), size = 0, type = "movi".ToCharArray()
        };

        //bzero(&ah, sizeof(ah));
        strcpy(ref ah.avih, "avih");
        ah.time       = (u32)(1e6 / fps);
        ah.numstreams = 1;
        //ah.scale = (u32)(1e6 / fps);
        //ah.rate = (u32)fps;
        //ah.length = (u32)(nframes);
        ah.nframes           = (u32)(nframes);
        ah.width             = (u32)width;
        ah.height            = (u32)height;
        ah.flags             = 0x10;
        ah.suggested_bufsize = 0;
        ah.maxbytespersec    = (u32)(3 * width * height * fps);

        //bzero(&sh, sizeof(sh));
        strcpy(ref sh.strh, "strh");
        strcpy(ref sh.vids, "vids");
        strcpy(ref sh.codec, "MJPG");
        sh.scale             = (u32)1;
        sh.rate              = (u32)fps;
        sh.length            = (u32)(nframes);
        sh.suggested_bufsize = (u32)(3 * width * height * fps);
        unchecked
        {
            sh.quality = (uint)-1;
        }
        sh.r = (short)width;
        sh.b = (short)height;

        //bzero(&fh, sizeof(fh));
        strcpy(ref fh.strf, "strf");
        fh.width    = width;
        fh.height   = height;
        fh.planes   = 1;
        fh.bitcount = 24;
        strcpy(ref fh.codec, "MJPG");
        fh.unpackedsize = (u32)(3 * width * height);

        uint indexlength = (uint)(indexs.Count * 16) + 8; // header as well

        rh.size = (u32)(Marshal.SizeOf(lh1) + Marshal.SizeOf(ah) + Marshal.SizeOf(lh2) + Marshal.SizeOf(sh) +
                        Marshal.SizeOf(fh) + Marshal.SizeOf(lh3) + //); // 212
                        nframes * Marshal.SizeOf((new db_head())) +
                        totalsize + indexlength + 7980);           // needs junk length + list movi header
        lh1.size = (u32)(4 + Marshal.SizeOf(ah) + Marshal.SizeOf(lh2) + Marshal.SizeOf(sh) + Marshal.SizeOf(fh));
        ah.size  = (u32)(Marshal.SizeOf(ah) - 8);
        lh2.size = (u32)(4 + Marshal.SizeOf(sh) + Marshal.SizeOf(fh));
        sh.size  = (u32)(Marshal.SizeOf(sh) - 8);
        fh.size  = (u32)(Marshal.SizeOf(fh) - 8);
        fh.size2 = fh.size;
        lh3.size = (u32)(4 +
                         nframes * Marshal.SizeOf((new db_head())) +
                         totalsize);
        junk.size = 8204 - lh1.size - 12 - 12 - 12 - 4; // junk head, list head, rif head , 4
        long pos = fd.Position;

        fd.Seek(0, SeekOrigin.Begin);

        fd.Write(StructureToByteArray(rh), 0, Marshal.SizeOf(rh));
        fd.Write(StructureToByteArray(lh1), 0, Marshal.SizeOf(lh1));
        fd.Write(StructureToByteArray(ah), 0, Marshal.SizeOf(ah));
        fd.Write(StructureToByteArray(lh2), 0, Marshal.SizeOf(lh2));
        fd.Write(StructureToByteArray(sh), 0, Marshal.SizeOf(sh));
        fd.Write(StructureToByteArray(fh), 0, Marshal.SizeOf(fh));
        fd.Write(StructureToByteArray(junk), 0, Marshal.SizeOf(junk));
        fd.Seek(8192, SeekOrigin.Begin);
        fd.Write(StructureToByteArray(lh3), 0, Marshal.SizeOf(lh3));

        fd.Seek(pos, SeekOrigin.Begin);
    }
 public static void SeekOnUnseekableStream_Throws_NotSupportedException()
 {
     using (WrappedMemoryStream underlying = new WrappedMemoryStream(true, true, false))
     using (BufferedStream stream = new BufferedStream(underlying))
     {
         Assert.Throws<NotSupportedException>(() => stream.Seek(0, new SeekOrigin()));
     }
 }
	public void ReadByte ()
	{
		mem.Write (new byte [] {0, 1, 2, 3, 4, 5, 6, 7}, 0, 8);
		BufferedStream stream = new BufferedStream (mem);

		Assert.AreEqual (-1, stream.ReadByte (), "test#01");
		Assert.AreEqual (-1, stream.ReadByte (), "test#02");
		Assert.AreEqual (-1, stream.ReadByte (), "test#03");

		stream.Seek (0, SeekOrigin.Begin);
		Assert.AreEqual (0, stream.ReadByte (), "test#04");
		Assert.AreEqual (1, stream.ReadByte (), "test#05");
		Assert.AreEqual (2, stream.ReadByte (), "test#06");
		Assert.AreEqual (3, stream.ReadByte (), "test#07");		
	}
        private void patchList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selection = (this.patchList.SelectedItem) as Change;
            if (selection != null)
            {
                txtFileName.Text = "Diff: " + selection.Name;
                var dispatcher = Dispatcher.CurrentDispatcher;
                Action act = () =>
                {
                    HistogramDiff hd = new HistogramDiff();
                    hd.SetFallbackAlgorithm(null);

                    RawText a = string.IsNullOrWhiteSpace(commitId1) ? new RawText(new byte[0]) :
                        new RawText(tracker.RepositoryGraph.GetFileContent(commitId1, selection.Name) ?? new byte[0]);
                    RawText b = string.IsNullOrWhiteSpace(commitId2) ? new RawText(new byte[0]) :
                        new RawText(tracker.RepositoryGraph.GetFileContent(commitId2, selection.Name) ?? new byte[0]);

                    var list = hd.Diff(RawTextComparator.DEFAULT, a, b);

                    var tmpFileName = Path.ChangeExtension(Path.GetTempFileName(), ".diff");

                    //using (Stream stream = new FileStream(tmpFileName, FileMode.CreateNew))
                    //{
                    //    DiffFormatter df = new DiffFormatter(stream);
                    //    df.Format(list, a, b);
                    //    df.Flush();
                    //}

                    using (Stream mstream = new MemoryStream(),
                          stream = new BufferedStream(mstream))
                    {
                        DiffFormatter df = new DiffFormatter(stream);
                        df.Format(list, a, b);
                        df.Flush();
                        stream.Seek(0, SeekOrigin.Begin);
                        var ret = new StreamReader(stream).ReadToEnd();
                        ret = ret.Replace("\r", "").Replace("\n", "\r\n");
                        File.WriteAllText(tmpFileName, ret);
                    }

                    ShowFile(tmpFileName);
                };

                dispatcher.BeginInvoke(act, DispatcherPriority.ApplicationIdle);
            }
        }
	public void SeekException ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Seek (-1, SeekOrigin.Begin);
	}
Пример #31
0
    /* start writing an AVI file */
    public void avi_start(string filename)
    {
        avi_close();

        fd = new BufferedStream(File.Open(filename, FileMode.Create));

        fd.Seek(8204,SeekOrigin.Begin);

        indexs.Clear();

        nframes = 0;
        totalsize = 0;
        start = DateTime.Now;
    }
	public void Seek_ClosedBufferedStream ()
	{
		BufferedStream stream = new BufferedStream (new MemoryStream ());
		stream.Close ();
		stream.Seek (0, SeekOrigin.Begin);
	}
Пример #33
0
        /// <summary>ファイルを元にWeatherDataTableを構成する</summary>
        /// <param name="filePath">読み取りファイルのパス</param>
        /// <param name="success">読み取り成功の真偽</param>
        /// <returns>構成されたPWeatherDataオブジェクト</returns>
        public static WeatherDataTable ToPWeatherData(string filePath, out bool success)
        {
            success = false;

            //読み出しファイルの存在確認
            if (!File.Exists(filePath)) return null;

            WeatherDataTable wdTable = new WeatherDataTable();
            Stream strm = File.OpenRead(filePath);
            BufferedStream bStrm = new BufferedStream(strm);

            //地点番号-名称特定
            LocationInformation lInfo;
            byte[] buffer = new byte[3];
            bStrm.Read(buffer, 0, 3);
            string ln = Encoding.GetEncoding(932).GetString(buffer);
            int lNumber;
            if (int.TryParse(ln, out lNumber))
            {
                if (!GetLocationInformation(lNumber, out lInfo))
                {
                    return null;
                }
            }
            else return null;

            //地点情報を設定
            wdTable.Location = lInfo;

            //年月日データまでシーク
            bStrm.Seek(14, SeekOrigin.Begin);

            //1時間データ読み込み処理
            buffer = new byte[14];
            while (true)
            {
                getHourlyData(ref wdTable, bStrm);
                //次の日にちまでシーク
                bStrm.Seek(184, SeekOrigin.Current);
                //年月日データまでシーク
                if (bStrm.Read(buffer, 0, 14) == 0) break;
            }

            success = true;
            return wdTable;
        }
Пример #34
0
        private void Initialize()
        {
            _recordFileRead = new FileStream(_Path + _FileName + _recExt, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            _recordFileWriteOrg = new FileStream(_Path + _FileName + _recExt, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            _recordFileWrite = new BufferedStream(_recordFileWriteOrg);

            _bitmapFileRead = new FileStream(_Path + _FileName + _bmpExt, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            _bitmapFileWriteOrg = new FileStream(_Path + _FileName + _bmpExt, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            _bitmapFileWrite = new BufferedStream(_bitmapFileWriteOrg);

            _bitmapFileWrite.Seek(0L, SeekOrigin.End);
            _lastBitmapOffset = _bitmapFileWrite.Length;
            _lastRecordNumber = (int)(_recordFileRead.Length / 8);
            _shutdownDone = false;
        }
Пример #35
0
        /// <summary>地点情報読み込み処理</summary>
        /// <param name="pwData">PWeatherDataオブジェクト</param>
        /// <param name="bStrm">読み取りStream</param>
        private static void getHourlyData(ref WeatherDataTable pwData, BufferedStream bStrm)
        {
            LocationInformation locationInfo = pwData.Location;
            byte[] buffer;
            //年月日情報
            buffer = new byte[8];
            //最終行の場合は終了
            bStrm.Read(buffer, 0, 8);
            string dTime = System.Text.Encoding.GetEncoding(932).GetString(buffer);
            int year = int.Parse(dTime.Substring(0, 4));
            int month = int.Parse(dTime.Substring(4, 2));
            int day = int.Parse(dTime.Substring(6, 2));
            DateTime cTime = new DateTime(year, month, day, 1, 0, 0);

            //1時間データまでシーク
            bStrm.Seek(2, SeekOrigin.Current);

            //24時間データを取得
            buffer = new byte[56];
            WeatherData wd = new WeatherData();
            wd.Source = WeatherData.DataSource.CalculatedValue;
            bool sunRise = false;
            bool hasDR = false;
            for (int i = 0; i < 24; i++)
            {
                WeatherRecord wr = new WeatherRecord();
                wr.DataDTime = cTime;

                //データ取得
                bStrm.Read(buffer, 0, 56);
                string data = System.Text.Encoding.GetEncoding(932).GetString(buffer);

                //気圧[Pa]
                double atm = wd.Value = double.Parse(data.Substring(0, 5)) * 0.01d;
                WeatherData.DataSource atmSource = getDataSource(data.Substring(5, 1));
                wd.Source = atmSource;
                wr.SetData(WeatherRecord.RecordType.AtmosphericPressure, wd);

                //乾球温度[C]
                double dbt = wd.Value = double.Parse(data.Substring(12, 4)) * 0.1;
                WeatherData.DataSource dbtSource = getDataSource(data.Substring(16, 1));
                wd.Source = dbtSource;
                wr.SetData(WeatherRecord.RecordType.DryBulbTemperature, wd);

                //相対湿度[%]
                double rhd = wd.Value = double.Parse(data.Substring(21, 3));
                WeatherData.DataSource rhdSource = getDataSource(data.Substring(24, 1));
                wd.Source = rhdSource;
                wr.SetData(WeatherRecord.RecordType.RelativeHumidity, wd);

                //風向[degree]
                wd.Value = getWindowDirection(int.Parse(data.Substring(25, 2)));
                wd.Source = getDataSource(data.Substring(27, 1));
                wr.SetData(WeatherRecord.RecordType.WindDirection, wd);

                //風速[m/s]
                wd.Value = double.Parse(data.Substring(28, 3)) * 0.1;
                wd.Source = getDataSource(data.Substring(31, 1));
                wr.SetData(WeatherRecord.RecordType.WindSpeed, wd);

                //雲量10分比[-]
                wd.Value = double.Parse(data.Substring(32, 2)) * 0.1;
                wd.Source = getDataSource(data.Substring(34, 1));
                wr.SetData(WeatherRecord.RecordType.TotalSkyCover, wd);

                //天気記号
                wd.Value = double.Parse(data.Substring(35, 2));
                wd.Source = getDataSource(data.Substring(37, 1));
                wr.SetData(WeatherRecord.RecordType.WeatherCode, wd);

                //露点温度[C]
                wd.Value = double.Parse(data.Substring(38, 4)) * 0.1;
                wd.Source = getDataSource(data.Substring(42, 1));
                wr.SetData(WeatherRecord.RecordType.DewPointTemperature, wd);

                //全天日射量[W/m2]
                double ghRad = double.Parse(data.Substring(47, 3)) * 277.7777778 * 0.01;
                wd.Value = ghRad;
                WeatherData.DataSource ghRadSource = getDataSource(data.Substring(50, 1));
                wd.Source = ghRadSource;
                wr.SetData(WeatherRecord.RecordType.GlobalHorizontalRadiation, wd);

                //降水量[mm]
                wd.Value = double.Parse(data.Substring(51, 4)) * 0.1;
                wd.Source = getDataSource(data.Substring(55, 1));
                wr.SetData(WeatherRecord.RecordType.PrecipitationLevel, wd);

                //推定可能なデータを計算して埋める********************************************************
                //絶対湿度[kg/kg(DA)]
                if (dbtSource != WeatherData.DataSource.MissingValue && rhdSource != WeatherData.DataSource.MissingValue)
                {
                    wd.Value = MoistAir.GetAirStateFromDBRH(dbt, rhd, MoistAir.Property.HumidityRatio, atm);
                    wd.Source = WeatherData.DataSource.CalculatedValue;
                    wr.SetData(WeatherRecord.RecordType.HumidityRatio, wd);
                }

                //直散分離
                //太陽の存在確認
                bool sr = (0 < Sun.GetSunAltitude(locationInfo.Latitude, locationInfo.Longitude, 135d, cTime));

                //直散分離
                double dsRad, dhRad;
                //日出・日没調整
                if (!sunRise && sr) Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime, out dsRad, out dhRad);
                else if (sunRise && !sr) Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime.AddHours(-1), out dsRad, out dhRad);
                else Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime.AddHours(-0.5), out dsRad, out dhRad);
                sunRise = sr;

                //24h「観測しない」が続いた場合は欠測扱い
                hasDR = (ghRadSource != WeatherData.DataSource.MissingValue || hasDR);
                if (i != 23 || hasDR)
                {
                    //直達日射量[W/m2]
                    wd.Value = dsRad;
                    wd.Source = WeatherData.DataSource.PredictedValue;
                    wr.SetData(WeatherRecord.RecordType.DirectNormalRadiation, wd);
                    //天空日射量[W/m2]
                    wd.Value = dhRad;
                    wd.Source = WeatherData.DataSource.PredictedValue;
                    wr.SetData(WeatherRecord.RecordType.DiffuseHorizontalRadiation, wd);
                }

                //空白データを欠測データとして埋める******************************************************
                wr.FillMissingData();

                //1時間進める
                cTime = cTime.AddHours(1);

                //気象レコード追加
                pwData.AddWeatherRecord(wr);
            }
        }
Пример #36
0
        /*
        Map File Format
        
        The first 65536 bytes of the map file is the graphical portion of the map.
        The next 65536 bytes appears to be the map that is used for path finding.
        
        The next 4 bytes is the number of markers on the map.
        
        The markers than follow here. If there are no markers than nothing
        is beyond the marker count bytes.
        
        
        Marker Format
        
        The first byte appears to be the x position
        The second byte appears to be the map tile it is in on the x axis
        Two blank bytes
        
        The next byte appears to the y position
        The next byte appears to be the map tile it is in on the y axis
        Two blank bytes
        
        The next 4 bytes are the image id of the image
        
        The next 2 bytes are the size of the string that fallows
        The string of text for the marker
        */


        /// <summary>
        /// Merges tibia maps together. The input files are only read from.
        /// </summary>
        /// <param name="serverType">The type of server (Real or OT)</param>
        /// <param name="outputDirectory">The directory where the merged maps will go.</param>
        /// <param name="inputDirectories">A list of directories that contain the tibia maps to be merged together.</param>
        /// <returns>
        /// Returns true if successful. If it returns false the files in the output
        /// directory may be corrupted and incorrect.
        /// </returns>
        public static bool Merge(Constants.ServerType serverType, string outputDirectory, params string[] inputDirectories)
        {
            if (inputDirectories.Length < 1)
                return false;

            string mask = null;

            if (serverType == Pokemon.Constants.ServerType.Real)
                mask = "1??1????.map";
            else
                mask = "0??0????.map";

            string[] files = Directory.GetFiles(inputDirectories[0], mask);

            try
            {
                foreach (string file in files)
                {
                    File.Copy(file, outputDirectory + "/" + Path.GetFileName(file), true);
                }
            }
            catch
            {
                return false;
            }

            for (int i = 1; i < inputDirectories.Length; ++i)
            {
                files = Directory.GetFiles(inputDirectories[i]);

                foreach (string file in files)
                {
                    if (!File.Exists(outputDirectory + "/" + Path.GetFileName(file)))
                    {
                        try
                        {
                            File.Copy(file, outputDirectory + "/" + Path.GetFileName(file));
                        }
                        catch
                        {
                            return false;
                        }
                    }
                    else
                    {
                        FileStream sourcefile = null;
                        FileStream inputfile = null;
                        BufferedStream sourcebuffered = null;
                        BufferedStream inputbuffered = null;

                        try
                        {
                            //Setup the streams and buffers
                            sourcefile = new FileStream(outputDirectory + "/" + Path.GetFileName(file), FileMode.Open);
                            inputfile = new FileStream(file, FileMode.Open);
                            sourcebuffered = new BufferedStream(sourcefile);
                            inputbuffered = new BufferedStream(inputfile);


                            //Read and write the graphical data
                            byte[] source = new byte[65536];
                            sourcebuffered.Read(source, 0, 65536);

                            byte[] input = new byte[65536];
                            inputbuffered.Read(input, 0, 65536);

                            Compare(source, input, 0, 65536);

                            sourcebuffered.Seek(0, SeekOrigin.Begin);
                            sourcebuffered.Write(source, 0, 65536);


                            //Read and write the pathfinding data
                            sourcebuffered.Seek(65536, SeekOrigin.Begin);
                            inputbuffered.Seek(65536, SeekOrigin.Begin);

                            sourcebuffered.Read(source, 0, 65536);
                            inputbuffered.Read(input, 0, 65536);

                            Compare(source, input, 0xfa, 65536);

                            sourcebuffered.Seek(65536, SeekOrigin.Begin);
                            sourcebuffered.Write(source, 0, 65536);


                            //Read and write the marker data
                            sourcebuffered.Seek(131072, SeekOrigin.Begin);
                            byte[] sourcemarkercountbytes = new byte[4];
                            sourcebuffered.Read(sourcemarkercountbytes, 0, 4);
                            int sourcemarkercount = BitConverter.ToInt32(sourcemarkercountbytes, 0);

                            inputbuffered.Seek(131072, SeekOrigin.Begin);
                            byte[] inputmarkercountbytes = new byte[4];
                            inputbuffered.Read(inputmarkercountbytes, 0, 4);
                            int inputmarkercount = BitConverter.ToInt32(inputmarkercountbytes, 0);

                            List<Marker> sourcemarkers = new List<Marker>();

                            for (int r = 0; r < sourcemarkercount; ++r)
                            {
                                byte[] data = new byte[12];
                                sourcebuffered.Read(data, 0, 12);

                                byte[] stringlength = new byte[2];
                                sourcebuffered.Read(stringlength, 0, 2);
                                int len = BitConverter.ToUInt16(stringlength, 0);

                                byte[] str = new byte[len];
                                sourcebuffered.Read(str, 0, len);
                                sourcebuffered.Seek(len, SeekOrigin.Current);

                                Marker marker = new Marker(data, stringlength, str);
                                sourcemarkers.Add(marker);
                            }

                            for (int r = 0; r < inputmarkercount; ++r)
                            {
                                byte[] data = new byte[12];
                                inputbuffered.Read(data, 0, 12);

                                byte[] stringlength = new byte[2];
                                inputbuffered.Read(stringlength, 0, 2);
                                int len = BitConverter.ToUInt16(stringlength, 0);

                                byte[] str = new byte[len];
                                inputbuffered.Read(str, 0, len);
                                inputbuffered.Seek(len, SeekOrigin.Current);

                                Marker marker = new Marker(data, stringlength, str);

                                //Make sure we arn't copying a marker that already exists
                                if (!sourcemarkers.Contains(marker))
                                {
                                    sourcemarkercount++;

                                    byte[] write = marker.GetBytes();
                                    sourcebuffered.SetLength(sourcebuffered.Length + write.Length);
                                    sourcebuffered.Seek(-write.Length, SeekOrigin.End);
                                    sourcebuffered.Write(write, 0, write.Length);
                                }
                            }

                            sourcebuffered.Seek(131072, SeekOrigin.Begin);
                            sourcemarkercountbytes = BitConverter.GetBytes(sourcemarkercount);
                            sourcebuffered.Write(sourcemarkercountbytes, 0, 4);
                        }
                        catch
                        {
                            return false;
                        }
                        finally
                        {
                            if (sourcebuffered != null)
                                sourcebuffered.Close();

                            if (inputbuffered != null)
                                inputbuffered.Close();

                            if (sourcefile != null)
                                sourcefile.Close();

                            if (inputfile != null)
                                inputfile.Close();
                        }
                    }
                }
            }

            return true;
        }
Пример #37
0
        /// <summary>
        /// 提取Response中的Body
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static byte[] getResponseBody(HttpWebResponse response)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                return null;
            Stream responseStream = response.GetResponseStream();

            byte[] bResponseBody = null;

            //chunked编码
            if (response.ContentLength == -1)
            {
                int bufferLength = 1024;
                byte[] buffer = new byte[bufferLength];
                BufferedStream bufferStream = new BufferedStream(new MemoryStream());

                int len = responseStream.Read(buffer, 0, bufferLength);
                while (len > 0)
                {
                    bufferStream.Write(buffer, 0, len);
                    len = responseStream.Read(buffer, 0, bufferLength);
                }
                bResponseBody = new byte[bufferStream.Length];
                bufferStream.Seek(0, SeekOrigin.Begin);
                bufferStream.Read(bResponseBody, 0, bResponseBody.Length);
                bufferStream.Close();
            }
            else
            {
                bResponseBody = new byte[response.ContentLength];
                BinaryReader r = new BinaryReader(responseStream);
                bResponseBody = r.ReadBytes((int)response.ContentLength);
            }
            return bResponseBody;
        }