Seek() public method

public Seek ( long offset, SeekOrigin loc ) : long
offset long
loc SeekOrigin
return long
Beispiel #1
1
        public void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            var paras       = camera.GetParameters();
            var imageformat = paras.PreviewFormat;

            if (imageformat == Android.Graphics.ImageFormatType.Nv21)
            {
                Android.Graphics.YuvImage img = new Android.Graphics.YuvImage(data,
                                                                              imageformat, paras.PreviewSize.Width, paras.PreviewSize.Height, null);

                if (time <= DateTime.Now)
                {
                    using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
                    {
                        bool didIt = img.CompressToJpeg(new Rect(0, 0, paras.PreviewSize.Width, paras.PreviewSize.Height), 75, outStream);
                        outStream.Seek(0, System.IO.SeekOrigin.Begin);
                        //     Bitmap newBM = BitmapFactory.DecodeStream(outStream);

                        NetProcess.SendRoomMessage(outStream.ToArray());
                        time = DateTime.Now.AddMilliseconds(300);
                    }
                }
            }
        }
        public override async Task Invoke(IOwinContext context)
        {
            using (var buffer = new MemoryStream())
            {
                var responseStream = context.Response.Body;

                context.Response.Body = buffer;

                await _next.Invoke(context);

                Console.WriteLine("[{0}] {1} {2}", Thread.CurrentThread.ManagedThreadId, context.Response.StatusCode, (HttpStatusCode)context.Response.StatusCode);

                foreach (var header in context.Response.Headers)
                {
                    Console.WriteLine("\t{0} {1}", header.Key, string.Join(", ", header.Value));
                }

                buffer.Seek(0, SeekOrigin.Begin);

                await buffer.CopyToAsync(responseStream);

                if (LogBody(context.Response.ContentType))
                {
                    buffer.Seek(0, SeekOrigin.Begin);

                    using (var reader = new StreamReader(buffer, true))
                    {
                        var body = await reader.ReadToEndAsync();

                        Console.WriteLine(body);
                        Console.WriteLine();
                    }
                }
            }
        }
Beispiel #3
0
 internal static object DeserializeWithMd5CheckSum(MemoryStream ms, Func<Stream, object> body)
 {
     // Check MD5 checksum.
     ms.Seek (0, SeekOrigin.Begin);
     byte[] expectedMd5 = new byte[16];
     ms.Read (expectedMd5, 0, expectedMd5.Length);
     ms.Seek (0, SeekOrigin.Begin);
     WriteBytes (ms, sixteenZeroes);
     using (var md5 = MD5.Create()) {
         ms.Seek (0, SeekOrigin.Begin);
         var actualMd5 = md5.ComputeHash (ms);
         if (!expectedMd5.SequenceEqual (actualMd5)) {
             throw new BrokenDataException ();
         }
     }
     ms.Seek (0, SeekOrigin.Begin);
     WriteBytes (ms, expectedMd5);
     // Check endianess.
     if (ms.ReadByte () != Utils.Endianess ()) {
         throw new EndianessMismatchException ();
     }
     // Check version.
     if (ReadInt (ms) > Shovel.Api.Version) {
         throw new VersionNotSupportedException ();
     }
     return body (ms);
 }
        public void With_WebSocket_CanReadSmallFrame()
        {
            var handshake = GenerateSimpleHandshake();
            using (var ms = 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.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                var reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEnd();
                    Assert.AreEqual("Hi", s);
                }

                ms.Seek(0, SeekOrigin.Begin);
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEndAsync().Result;
                    Assert.AreEqual("Hi", s);
                }
            }
        }
Beispiel #5
0
        public void AddFile(DeduplicatorState state, FileInfo sourceFile, string destinationPath)
        {
            if (state.DestinationToFileHash.ContainsKey(destinationPath))
            {
                // File has already been added.
                return;
            }

            // Read the source file.
            var memory = new MemoryStream();
            using (var stream = new BufferedStream(new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.None), 1200000))
            {
                stream.CopyTo(memory);
            }

            // Hash the memory stream.
            var sha1 = new SHA1Managed();
            memory.Seek(0, SeekOrigin.Begin);
            var hashBytes = sha1.ComputeHash(memory);
            var hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            memory.Seek(0, SeekOrigin.Begin);

            // Add to the file hash -> source map if not already present.
            if (!state.FileHashToSource.ContainsKey(hashString))
            {
                state.FileHashToSource.Add(hashString, memory);
            }
            else
            {
                memory.Dispose();
            }

            state.DestinationToFileHash.Add(destinationPath, hashString);
        }
Beispiel #6
0
        public void should_be_within_performace_tolerance()
        {
            var json = File.ReadAllText("model.json");
            var jsonBytes = new MemoryStream(File.ReadAllBytes("model.json"));
            var stopwatch = new Stopwatch();

            var controlBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                jsonBytes.Seek(0, SeekOrigin.Begin);
                stopwatch.Restart();
                json.ParseJson();
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

            var flexoBenchmark = Enumerable.Range(1, 1000).Select(x =>
            {
                jsonBytes.Seek(0, SeekOrigin.Begin);
                stopwatch.Restart();
                JElement.Load(jsonBytes);
                stopwatch.Stop();
                return stopwatch.ElapsedTicks;
            }).Skip(5).Average();

            Console.Write("Control: {0}, Flexo: {1}", controlBenchmark, flexoBenchmark);

            flexoBenchmark.ShouldBeLessThan(controlBenchmark * 2);
        }
		public async Task Invoke(IDictionary<string, object> env)
		{
			IOwinContext context = new OwinContext(env);
			 
			// Switch the response body stream
			// to a memory stream.
			var originalStream = context.Response.Body;
			var responseBuffer = new MemoryStream();
			context.Response.Body = responseBuffer;

			await this.next(env);

			responseBuffer.Seek(0, SeekOrigin.Begin);
			string responseBody = await this.ReadAllAsync(
				responseBuffer);
			Console.WriteLine(responseBody);
			 
			// This header is getting added after the
			// second middleware has already written into
			// the response body stream, yet, the header goes out.
			context.Response.Headers.Add("X-Some-Header",
				new[] { "Hello" });
			 
			responseBuffer.Seek(0, SeekOrigin.Begin);
			await responseBuffer.CopyToAsync(originalStream);
		}
        public unsafe void CopyTo1()
        {
            const int bufferSize = 10;
            byte* buffer = (byte*)Marshal.AllocHGlobal(bufferSize);

            try
            {
                var s = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 });

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 3);
                Assert.Equal(new byte[] { 0, 1, 2 }, ReadBuffer(buffer, bufferSize));

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 0);
                Assert.Equal(new byte[0], ReadBuffer(buffer, bufferSize));

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 5);
                Assert.Equal(new byte[] { 0, 1, 2, 3, 4 }, ReadBuffer(buffer, bufferSize));

                Assert.Throws<IOException>(() => s.CopyTo(buffer, 6));
            }
            finally
            {
                Marshal.FreeHGlobal((IntPtr)buffer);
            }
        }
Beispiel #9
0
        public async Task Invoke(HttpContext httpContext)
        {
            StringValues acceptEncoding = httpContext.Request.Headers["Accept-Encoding"];
            if (acceptEncoding.Count > 0)
            {
                if (acceptEncoding.ToString().IndexOf
                ("gzip", StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        var stream = httpContext.Response.Body;
                        httpContext.Response.Body = memoryStream;
                        await _next(httpContext);
                        if (httpContext.Response.Headers.ContainsKey("X-Content-Encoding"))
                        {
                            httpContext.Response.Headers.Remove("X-Content-Encoding");
                            httpContext.Response.Headers.Add("Content-Encoding", new[] {"gzip"});
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            return;
                        }

                        using (var compressedStream = new GZipStream(stream, CompressionLevel.Optimal))
                        {
                            httpContext.Response.Headers.Add("Content-Encoding", new[] { "gzip" });
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            await memoryStream.CopyToAsync(compressedStream);
                        }
                    }
                }
            }
        }
Beispiel #10
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            IOwinContext context = new OwinContext(env);

            if (_log.IsInfoEnabled) _log.InfoFormat("{0} {1}", context.Request.Method, context.Request.Uri);

            if (_log.IsDebugEnabled)
            {
                var stream = context.Request.Body;
                var buffer = new MemoryStream();
                context.Request.Body = buffer;

                await stream.CopyToAsync(buffer);

                buffer.Seek(0, SeekOrigin.Begin);

                var reader = new StreamReader(buffer);
                var requestBody = await reader.ReadToEndAsync();

                _log.Debug(requestBody);

                buffer.Seek(0, SeekOrigin.Begin);
            }

            await _next(env);
        }
Beispiel #11
0
        public void WhenExtensibleUsedAsBase_ThenOldMessagesCanBeDeserializedFrom()
        {
            using (var ms = new MemoryStream())
            {
                // create an old message and serialize it
                var messageOld = new Messages.MessageOld
                              {
                                  Id = 5,
                                  Login = "******",
                                  Name = "nameeee",
                                  Password = new byte[] { 1, 4, 2, 3, 5, 3, 4 },
                                  Surname = "test"
                              };
                Serializer.Serialize(ms, messageOld);

                // deserialize and serialize back a new message
                ms.Seek(0, SeekOrigin.Begin);
                var messageNew = Serializer.Deserialize<Messages.MessageNew>(ms);

                ms.Seek(0, SeekOrigin.Begin);
                Serializer.Serialize(ms, messageNew);

                // deserialize a message by an old type and check whether it retrieves forgotten fields
                ms.Seek(0, SeekOrigin.Begin);
                var messageOld2 = Serializer.Deserialize<Messages.MessageOld>(ms);

                Assert.True(messageOld.Equals(messageOld2));
            }
        }
Beispiel #12
0
        static void Main1(string[] args)
        {
            CopySelfToDes();
            MemoryStream ms = new MemoryStream();

            ms.Seek(0, SeekOrigin.End);

            byte[] bts1 = Encoding.Default.GetBytes("情人");

            ms.Write(bts1, 0, bts1.Length);

            byte[] bts2 = Encoding.Default.GetBytes("我是你的");

            ms.Write(bts2, 0, bts2.Length);

            int totalLen = bts1.Length + bts2.Length;
            byte[] bts = new byte[totalLen - 2];

            ms.Seek(0, SeekOrigin.Begin);
            ms.Seek(totalLen - 2, SeekOrigin.End);
            int len = ms.Read(bts, 0, totalLen - 2);

               string s = Encoding.Default.GetString(bts);
               Console.WriteLine(s);
               Console.Read();
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            //CopySelfToDes();
            MemoryStream ms = new MemoryStream();

            ms.Seek(0, SeekOrigin.End);

            byte[] bts1 = Encoding.Default.GetBytes("情人");

            ms.Write(bts1, 0, bts1.Length);

            byte[] bts2 = Encoding.Default.GetBytes("我是你的");

            ms.Write(bts2, 0, bts2.Length);

            int totalLen = bts1.Length + bts2.Length;
            byte[] bts = new byte[totalLen - 2];

            //ms.Seek(0, SeekOrigin.Begin);
            ms.Seek( -4, SeekOrigin.End);//倒着读
            int len = ms.Read(bts, 0,4);//你的

            ms.Seek(0, SeekOrigin.End);//移到最后 追加

            byte[] bts3 = Encoding.Default.GetBytes("淡淡");
            ms.Write(bts3, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);

            byte[] btsRead = new byte[totalLen+ bts3.Length];
            ms.Read(btsRead, 0, totalLen + bts3.Length);
            ms.Close();
            string s = Encoding.Default.GetString(btsRead);
            Console.WriteLine(s);
            Console.Read();
        }
        public void it_should_serialize_and_deserialize_the_Person_object()
        {
            var ser = new XmlSerializer(typeof(Person));
            var stream = new MemoryStream();
            var dataManager = new DataRepositoryDummy();
            var people = dataManager.GetPeopleWithPets();
            var person = people.First(x => x.Name.ToLower() == "jpol");

            // person.Nickname = "octopus";

            ser.Serialize(stream, person);
            var xml = UTF8Encoding.UTF8.GetString(stream.ToArray());
            xml.Should().NotBeBlank();
            Console.WriteLine(xml);

            stream.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(stream);
            var xmlRead = reader.ReadToEnd();
            xml.Should().Be(xmlRead);

            stream.Seek(0, SeekOrigin.Begin);
            var deserializedPerson = ser.Deserialize(new StreamReader(stream)) as Person;
            deserializedPerson.Should().NotBeNull();
            deserializedPerson.Name.Should().Be(person.Name);
        }
Beispiel #15
0
        public string AddReviewJSON(Stream indata, string pid, string key)
        {
            //Read in the data as it streams in
            MemoryStream ms = new MemoryStream();
            int pos = 1;
            while (pos != -1)
            {
                pos = indata.ReadByte();
                if (pos > -1)
                    ms.WriteByte((byte)pos);
            }
            //We now have compleated the streamin in operation
            //Read the stream as a string
            ms.Seek(0, SeekOrigin.Begin);
            byte[] data = new byte[ms.Length];
            ms.Read(data, 0, (int)ms.Length);
            ms.Seek(0, SeekOrigin.Begin);
            string s = "";
            for (int i = 0; i < data.Length; i++)
                s += Convert.ToChar(data[i]);

            //deSerialize the data

            Review md = (new JavaScriptSerializer()).Deserialize<Review>(s);

            //Call the base class
            return base.AddReview(md, pid, key);
        }
Beispiel #16
0
        /// <summary>
        /// Extract WAV data from Memory Stream (assumes mono, 16-bit signed PCM for now)
        /// </summary>
        /// <param name="stream">MemoryStream</param>
        /// <returns>Short array with all data</returns>
        public static short[] ReadWAVFile(MemoryStream stream)
        {
            if (!stream.CanSeek) throw new Exception("Can't seek stream to read wav header");

            stream.Seek(40, SeekOrigin.Begin);
            Byte[] lengthData = new Byte[4];
            int numBytesRead = stream.Read(lengthData, 0, 4);
            if (numBytesRead != 4) throw new Exception("Stream ended while reading length value");
            int lengthBytes = BitConverter.ToInt32(lengthData, 0);

            System.Diagnostics.Debug.WriteLine("Bytes read: " + lengthBytes);

            int dataStartByte = 44;
            stream.Seek(dataStartByte, SeekOrigin.Begin);
            Byte[] audioData = new Byte[lengthBytes];
            numBytesRead = stream.Read(audioData, 0, lengthBytes);

            if (numBytesRead != lengthBytes) throw new Exception("Could not read " + lengthBytes + " bytes, only read " + numBytesRead + " bytes.");

            short[] shortData = new short[lengthBytes / 2];
            for (int i = 0; i < lengthBytes; i += 2)
            {
                shortData[i / 2] = BitConverter.ToInt16(audioData, i);
            }

            return shortData;
        }
Beispiel #17
0
 public fitFileWrite(StreamReader file, FileStream fitFile)
 {
     MemoryStream memStream = new MemoryStream();
     fitstream = new FitFieldStream(memStream);
     memStream.Seek(HEADERSIZE, SeekOrigin.Begin);
     while (!file.EndOfStream)
     {
         string[] str = file.ReadLine().Split(';');
         if (str[0] == "data")
             writeData(str, st);
         if (str[0] == "def")
             writeDefintion(str);
     }
     int size = (int)memStream.Position - HEADERSIZE;
     memStream.Seek(0, SeekOrigin.Begin);
     writeFitHeader(size, HEADERSIZE);
     UInt16 crc = 0;
     memStream.Seek(0, SeekOrigin.Begin);
     while (memStream.Position < memStream.Length)
     {
         crc = fitstream.Get16(crc, (byte)memStream.ReadByte());
     }
     memStream.WriteByte((byte)(crc & 0xFF));
     memStream.WriteByte((byte)(crc >> 8));
     fitFile.Write(memStream.GetBuffer(), 0, (int)memStream.Position);
 }
        public byte[] GetUncompressedNdfbinary(byte[] data)
        {
            using (var ms = new MemoryStream(data))
            {
                var header = ReadHeader(ms);

                if (header.IsCompressedBody)
                {
                    using (var uncompStream = new MemoryStream())
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        var headBuffer = new byte[header.HeaderSize];
                        ms.Read(headBuffer, 0, headBuffer.Length);
                        uncompStream.Write(headBuffer, 0, headBuffer.Length);

                        ms.Seek((long)header.HeaderSize, SeekOrigin.Begin);

                        var buffer = new byte[4];
                        ms.Read(buffer, 0, buffer.Length);
                        uint compressedblocklen = BitConverter.ToUInt32(buffer, 0);

                        var contentBuffer = new byte[(ulong)(data.Length) - header.HeaderSize];
                        ms.Read(contentBuffer, 0, contentBuffer.Length);
                        //Compressor.Decomp(contentBuffer, uncompStream);
                        var da = Compressor.Decomp(contentBuffer);

                        uncompStream.Write(da, 0, da.Length);

                        data = uncompStream.ToArray();
                    }
                }
            }

            return data;
        }
Beispiel #19
0
        public object Deserialize(MemoryStream stream)
        {
            long startPosition = stream.Position;

            byte[] sizeBytes = new byte[sizeof(int)];
            if (stream.Read(sizeBytes, 0, sizeBytes.Length) != sizeBytes.Length)
            {// Not enough info to extract size.
                stream.Seek(startPosition, SeekOrigin.Begin);
                return null;
            }

            int size = int.MaxValue - BitConverter.ToInt32(sizeBytes, 0);

            if (size > MaxMessageSize)
            {// Invalid size; we do not seek to start since data stream is already corrupt; this will indicate the owner
                // to clear it and try to recover.
                throw new InvalidDataException();
            }

            if (stream.Length - stream.Position + sizeof(int) < size)
            {// Not enough info to extract item.
                stream.Seek(startPosition, SeekOrigin.Begin);
                return null;
            }

            return DeserializeData(stream);
        }
Beispiel #20
0
        public void CorruptHeader_InvalidMessageSize()
        {
            MqttHeader inputHeader = new MqttHeader()
            {
                Duplicate = true,
                Retain = false,
                MessageSize = 268435455, // the max message size, which we will fudge later in the test
                MessageType = MqttMessageType.Connect,
                Qos = MqttQos.AtLeastOnce
            };

            MqttHeader outputHeader;

            using (MemoryStream stream = new MemoryStream())
            {
                inputHeader.WriteTo(268435455, stream);

                // fudge the header by making the last bit of the 4th message size byte a 1, therefore making the header
                // invalid because the last bit of the 4th size byte should always be 0 (according to the spec). It's how 
                // we know to stop processing the header when reading a full message).
                stream.Seek(4, SeekOrigin.Begin);
                byte existingByte = (byte)stream.ReadByte();
                stream.Seek(4, SeekOrigin.Begin);
                stream.WriteByte((byte)(existingByte | 0xFF));
                stream.Seek(0, SeekOrigin.Begin);

                Assert.Throws<InvalidHeaderException>(() => outputHeader = new MqttHeader(stream));
            }
        }
        private RoundTripPerformance MakeBltRoundTrip(LNode[] Nodes)
        {
            using (var memStream = new MemoryStream())
            {
                var timer = new Stopwatch();
                timer.Start();

                var writer = new LoycBinaryWriter(memStream);

                for (int i = 0; i < TimedRoundTripCount; i++)
                {
                    writer.WriteFile(Nodes);
                    memStream.Seek(0, SeekOrigin.Begin);
                }

                timer.Stop();
                var writePerf = timer.Elapsed;
                long size = memStream.Length;
                timer.Restart();

                for (int i = 0; i < TimedRoundTripCount; i++)
                {
                    var reader = new LoycBinaryReader(memStream);
                    reader.ReadFile("test.blt");
                    memStream.Seek(0, SeekOrigin.Begin);
                }

                timer.Stop();
                var readPerf = timer.Elapsed;

                return new RoundTripPerformance(readPerf, writePerf, size);
            }
        }
Beispiel #22
0
        private void Init(byte[] buffer)
        {
            var stream = new MemoryStream(buffer);
            stream.Seek(0, SeekOrigin.Begin);
            if (stream.ReadByte() != 2 && stream.ReadByte() != 0)
            {
                throw new InvalidDataException("Error Table Index");
            }
            else
            {
                while(ReadOne(stream))
                {
                    continue;
                }
                stream.Seek(195, SeekOrigin.Begin);
                if (stream.ReadByte() != 3)
                {
                    throw new InvalidDataException("Error Table Index");
                }
                else
                {

                }
            }
        }
Beispiel #23
0
 private static string DownloadBlob(CloudBlockBlob blob)
 {
     using (var stream = new MemoryStream())
     {
         StreamReader reader;
         try
         {
             blob.DownloadToStream(stream, options: new BlobRequestOptions()
             {
                 RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(5), 3)
             });
         }
         catch (StorageException se)
         {
             return "";
         }
         try
         {
             stream.Seek(0, 0);
             reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress));
             return reader.ReadToEnd();
         }
         catch
         {
             stream.Seek(0, 0);
             reader = new StreamReader(stream);
             return reader.ReadToEnd();
         }
     }
 }
Beispiel #24
0
        private static async Task WriteRequestSummary(IOwinContext context)
        {
            var requestBody = "";

            if (context.Request.Body != null)
            {
                var bodyBuffer = new MemoryStream();
                await context.Request.Body.CopyToAsync(bodyBuffer);
                bodyBuffer.Seek(0, SeekOrigin.Begin);
                context.Request.Body = bodyBuffer;
                requestBody = await new StreamReader(bodyBuffer).ReadToEndAsync();
                bodyBuffer.Seek(0, SeekOrigin.Begin);
            }

            Debug.WriteLine(@"
>>>REQUEST>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
{0} {1}
{2}
{3}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",
                context.Request.Method, context.Request.Uri,
                String.Join("",
                    context.Request.Headers.Select(
                        h =>
                            String.Format("{0}: {1}\r\n", h.Key,
                            String.Join(", ", h.Value.Select(v => v.ToString(CultureInfo.InvariantCulture)))))),
                            requestBody);
        }
        public void StringTest()
        {
            MemoryStream memStream = new MemoryStream();
            BigEndianStream bigEndianStream = new BigEndianStream(memStream);

            string testString = "Hello, World!";

            bigEndianStream.Write(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            var result = bigEndianStream.ReadString16();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);


            memStream.SetLength(0);

            bigEndianStream.Write8(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            result = bigEndianStream.ReadString8();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);
        }
        public async Task StringTestAsync()
        {
            MemoryStream memStream = new MemoryStream();
            BigEndianStream bigEndianStream = new BigEndianStream(memStream);

            string testString = "Hello, World!";

            await bigEndianStream.WriteAsync(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            var result = await bigEndianStream.ReadString16Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);


            memStream.SetLength(0);

            bigEndianStream.Write8(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            result = await bigEndianStream.ReadString8Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);
        }
        /// <summary>
        /// Upload a file to the blobs storage and create a record in the files table
        /// </summary>
        /// <param name="fileToLoad"></param>
        /// <returns>The token to be used to access the file later on</returns>
        public UploadFileTokenMessage UploadFile(UploadFileContentMessage fileToLoad)
        {
            // generate random 6 digits password
            string password = GeneratePassword();

            // remove bad characters from sender name
            string safeSenderName = GetSafeSenderName(fileToLoad.SenderName);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                Utils.CopyStream(fileToLoad.FileByteStream, memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);

                // make sure stream is a valid deck
                if (!IsLegalDeckFile(memoryStream))
                {
                    return new UploadFileTokenMessage() { Password = string.Empty };
                }

                memoryStream.Seek(0, SeekOrigin.Begin);

                // save stream as blob
                var blobUri = CreateBlob(memoryStream, password + safeSenderName);

                var files_ds = new FilesDataSource();
                var token = files_ds.AddFile(password + safeSenderName, ContainerName, blobUri);
            }

            return new UploadFileTokenMessage() { Password = password };
        }
        public static void ExportSchedulesFITFile(Stream exportStream, MemoryStream dataStream)
        {
            MemoryStream tempDataStream = new MemoryStream();

            // Reserve size for header
            tempDataStream.Write(new Byte[12], 0, 12);

            // File id message
            FITMessage fileIdMessage = new FITMessage(FITGlobalMessageIds.FileId);
            FITMessageField fileType = new FITMessageField((Byte)FITFileIdFieldsIds.FileType);
            FITMessageField manufacturerId = new FITMessageField((Byte)FITFileIdFieldsIds.ManufacturerId);
            FITMessageField productId = new FITMessageField((Byte)FITFileIdFieldsIds.ProductId);
            FITMessageField serialNumber = new FITMessageField((Byte)FITFileIdFieldsIds.SerialNumber);
            FITMessageField exportDate = new FITMessageField((Byte)FITFileIdFieldsIds.ExportDate);
            FITMessageField number = new FITMessageField((Byte)FITFileIdFieldsIds.Number);

            manufacturerId.SetUInt16(1);
            fileType.SetEnum((Byte)FITFileTypes.Schedules);

            // Invalid fields
            productId.SetUInt16(0xFFFF);
            serialNumber.SetUInt32z(0);
            exportDate.SetUInt32(0xFFFFFFFF);
            number.SetUInt16(0xFFFF);

            fileIdMessage.AddField(serialNumber);
            fileIdMessage.AddField(exportDate);
            fileIdMessage.AddField(manufacturerId);
            fileIdMessage.AddField(productId);
            fileIdMessage.AddField(number);
            fileIdMessage.AddField(fileType);

            fileIdMessage.Serialize(tempDataStream);

            // Write all passed in data to output stream
            tempDataStream.Write(dataStream.GetBuffer(), 0, (int)dataStream.Length);

            // Write FIT header at the start of the stream
            GarminFitnessByteRange headerSize = new GarminFitnessByteRange(12);
            GarminFitnessByteRange protocolVersion = new GarminFitnessByteRange((Byte)((FITConstants.FITProtocolMajorVersion << 4) | FITConstants.FITProtocolMinorVersion));
            GarminFitnessUInt16Range profileVersion = new GarminFitnessUInt16Range((UInt16)((FITConstants.FITProfileMajorVersion * FITConstants.FITProfileMajorVersionMultiplier) + FITConstants.FITProfileMinorVersion));
            GarminFitnessInt32Range dataSize = new GarminFitnessInt32Range(0);

            tempDataStream.Seek(0, SeekOrigin.Begin);
            dataSize.Value = (int)tempDataStream.Length - 12;

            headerSize.Serialize(tempDataStream);
            protocolVersion.Serialize(tempDataStream);
            profileVersion.Serialize(tempDataStream);
            dataSize.Serialize(tempDataStream);
            tempDataStream.Write(Encoding.UTF8.GetBytes(FITConstants.FITFileDescriptor), 0, 4);

            // Write CRC
            GarminFitnessUInt16Range crc = new GarminFitnessUInt16Range(FITUtils.ComputeStreamCRC(tempDataStream));
            tempDataStream.Seek(0, SeekOrigin.End);
            crc.Serialize(tempDataStream);

            // Write all data to output stream
            exportStream.Write(tempDataStream.GetBuffer(), 0, (int)tempDataStream.Length);
        }
Beispiel #29
0
        /// <summary>
        ///     Gets the name of the first model on a CGFX file.
        ///     Returns null if the file doesn't contain any model.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string getName(MemoryStream data)
        {
            BinaryReader input = new BinaryReader(data);

            cgfxHeader header = new cgfxHeader();
            header.magic = IOUtils.readString(input, 0, 4);
            header.endian = input.ReadUInt16();
            header.length = input.ReadUInt16();
            header.revision = input.ReadUInt32();
            header.fileLength = input.ReadUInt32();
            header.entries = input.ReadUInt32();

            data.Seek(header.length + 8, SeekOrigin.Begin);
            List<dictEntry> models = getDictionary(input);

            if (models.Count > 0)
            {
                data.Seek(models[0].dataOffset + 0xc, SeekOrigin.Begin);
                string name = IOUtils.readString(input, getRelativeOffset(input));
                data.Close();
                return name;
            }
            else
            {
                data.Close();
                return null;
            }
        }
Beispiel #30
0
        public MemoryStream Zip(InputConfiguration inputConfig)
        {
            var stream = new MemoryStream();
            using (var zip = new ZipFile())
            {
                SetCompressionLevel(zip, 0);
                CreateFolders(zip, inputConfig.HasView);
                AddInputConfig(zip, inputConfig);
                AddMediaFiles(zip, inputConfig);
                foreach (var inputAction in inputConfig.Actions)
                {
                    if (!inputAction.HasScriptSequences)
                        continue;
                    AddScripts(zip, inputAction);
                }
                if (inputConfig.HasView)
                {
                    var path = Path.Combine(appConfigProvider.AppConfig.ViewsRoot, inputConfig.View);
                    if (new FileSystemUtils().DirectoryExists(path))
                        zip.AddDirectory(path, "Views\\" + inputConfig.View);
                }

                stream.Seek(0, SeekOrigin.Begin);
                zip.Save(stream);

            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
Beispiel #31
0
 /// <summary>
 /// 对象深拷贝
 /// </summary>
 /// <typeparam name="T">泛型</typeparam>
 /// <param name="obj">Object</param>
 /// <returns>Object</returns>
 public static T DeepCopy <T>(T obj)
 {
     if (!typeof(T).IsSerializable)
     {
         throw new ArgumentException(string.Format("该类型:{0}不支持序列化", typeof(T).FullName), "obj");
     }
     if (obj == null)
     {
         return(default(T));
     }
     System.Runtime.Serialization.IFormatter _formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     using (System.IO.Stream stream = new System.IO.MemoryStream())
     {
         _formatter.Serialize(stream, obj);
         stream.Seek(0, System.IO.SeekOrigin.Begin);
         return((T)_formatter.Deserialize(stream));
     }
 }
Beispiel #32
0
    static Tuple <byte[], byte[]> DecodeOpenSSHPubKey(string b64pubkey)
    {
        var keyData = Convert.FromBase64String(b64pubkey);

        using (MemoryStream memStream = new MemoryStream())
        {
            memStream.Write(keyData, 0, keyData.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            var br       = new BinaryReader(memStream);
            var fieldLen = ReadInt32(br);
            var keyType  = br.ReadBytes(fieldLen);
            fieldLen = ReadInt32(br);
            var exponent = br.ReadBytes(fieldLen);
            fieldLen = ReadInt32(br);
            var modulus = br.ReadBytes(fieldLen);
            return(Tuple.Create(exponent, modulus));
        }
    }
 /// <summary>
 /// Serializes current POCD_MT030001UK01AuthorFunctionCode object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize()
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try {
         memoryStream = new System.IO.MemoryStream();
         Serializer.Serialize(memoryStream, this);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     finally {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
Beispiel #34
0
 /// <summary>
 /// Serializes current urlset object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize(System.Text.Encoding encoding)
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try {
         memoryStream = new System.IO.MemoryStream();
         System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
         xmlWriterSettings.Encoding           = encoding;
         xmlWriterSettings.OmitXmlDeclaration = true;
         System.Xml.XmlWriter    xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         XmlSerializerNamespaces ns        = new XmlSerializerNamespaces();
         ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
         ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
         Serializer.Serialize(xmlWriter, this, ns);
         //xmlWriterSettings.OmitXmlDeclaration = true;
         //System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         //XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
         ////ns.Add("image", "http://www.sitemaps.org/schemas/sitemap-image/1.1");
         ////ns.Add("video", "http://www.sitemaps.org/schemas/sitemap-video/1.1");
         ////ns.Add("mobile", "http://www.google.com/schemas/sitemap-mobile/1.0");
         ////ns.Add("news", "http://www.google.com/schemas/sitemap-news/0.9");
         //ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
         //Serializer.Serialize(xmlWriter, this, ns);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     finally {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
Beispiel #35
0
        static public void ExecuteSynchronously(string input)
        {
            /*
             * $ms = New-Object System.IO.MemoryStream
             * $ms.Write($data, 0, $data.Length)
             * $ms.Seek(0,0) | Out-Null
             *
             * $cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress)
             * $sr = New-Object System.IO.StreamReader($cs)
             * $t = $sr.readtoend()
             *
             */
            var base64EncodedBytes = System.Convert.FromBase64String(input);

            Console.WriteLine(input.Length);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ms.Write(base64EncodedBytes, 0, base64EncodedBytes.Length);
            ms.Seek(0, 0);

            System.IO.Compression.GZipStream cs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
            System.IO.StreamReader           sr = new StreamReader(cs);
            var t = sr.ReadToEnd();

            //string pscode= System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
            InitialSessionState iss = InitialSessionState.CreateDefault();
            Runspace            rs  = RunspaceFactory.CreateRunspace(iss);

            rs.Open();
            PowerShell ps = PowerShell.Create();

            ps.Runspace = rs;
            //ps.AddScript(pscode);
            ps.AddScript(t);
            ps.AddScript("Invoke-MS16-032");
            ps.AddCommand("Out-Default");
            ps.Invoke();
            rs.Close();
        }
Beispiel #36
0
        private async Task <(String data, bool closed)> getString()
        {
            WebSocketReceiveResult result;
            var array = new ArraySegment <byte>(bufferR);

            using (var ms = new System.IO.MemoryStream())
            {
                do
                {
                    result = await user.webSocket.ReceiveAsync(array, CancellationToken.None);

                    ms.Write(array.Array, array.Offset, result.Count);
                    if (result.CloseStatus.HasValue)
                    {
                        return("", true);
                    }
                }while (!result.EndOfMessage);

                ms.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(ms, Encoding.UTF8))
                    return(reader.ReadToEnd(), false);
            }
        }
Beispiel #37
0
        public void EnableHiDefProfile()
        {
            EmbeddedResource hidefprofile = null;

            hidefprofilestream = new System.IO.MemoryStream();

            System.IO.StreamWriter sw = new System.IO.StreamWriter(hidefprofilestream);
            sw.Write("Windows.v4.0.HiDef");
            sw.Flush();
            hidefprofilestream.Seek(0, System.IO.SeekOrigin.Begin);
            hidefprofile = new EmbeddedResource("Microsoft.Xna.Framework.RuntimeProfile",
                                                ManifestResourceAttributes.Private, hidefprofilestream);



            for (int i = 0; i < terraria.MainModule.Resources.Count; i++)
            {
                if (terraria.MainModule.Resources[i].Name == "Microsoft.Xna.Framework.RuntimeProfile")
                {
                    terraria.MainModule.Resources[i] = hidefprofile;
                }
            }
        }
Beispiel #38
0
 private async void GetWebThumbnail(Uri url)
 {
     if (url.Host == "puush.me" && Properties.Settings.Default.puush_key != string.Empty)
     {
         byte[] bytes;
         using (var wc = new System.Net.WebClient())
         {
             string id = url.AbsolutePath.TrimStart('/');
             System.Collections.Specialized.NameValueCollection nv =
                 new System.Collections.Specialized.NameValueCollection
             {
                 { "i", id },
                 { "k", Properties.Settings.Default.puush_key }
             };
             bytes = await wc.UploadValuesTaskAsync("http://puush.me/api/thumb", nv);
         }
         if (bytes.Length <= 0)
         {
             return;
         }
         using (var stream = new System.IO.MemoryStream(bytes))
         {
             stream.Seek(0, System.IO.SeekOrigin.Begin);
             BitmapImage img = new BitmapImage();
             img.BeginInit();
             img.CacheOption      = BitmapCacheOption.OnLoad;
             img.DecodePixelWidth = 300;
             img.StreamSource     = stream;
             img.EndInit();
             DisplayImage = img;
         }
     }
     else
     {
         DisplayImage = new BitmapImage(url);
     }
 }
Beispiel #39
0
        public override FileServerResult StoreImage(System.IO.Stream stmImage, IFileQuery qryFileDestination, System.Drawing.Imaging.ImageFormat enuFormat = null)
        {
            if (CDNOnly)
            {
                var result = new FileServerResult(true);
                var blob   = GetBlobForStorage(qryFileDestination);

                if (enuFormat != null)
                {
                    using (System.IO.MemoryStream stmImageFormatted = new System.IO.MemoryStream())
                    {
                        using (Image img = System.Drawing.Image.FromStream(stmImage))
                        {
                            img.Save(stmImageFormatted, enuFormat);
                            stmImageFormatted.Seek(0, SeekOrigin.Begin);
                        }
                        blob.UploadFromStream(stmImageFormatted);
                    }
                }
                else
                {
                    blob.UploadFromStream(stmImage);
                }
                result.Uri = blob.Uri;
                return(result);
            }
            else
            {
                var result = base.WriteImageLocal(stmImage, qryFileDestination, enuFormat);
                if (result.Success)
                {
                    var blob = GetBlobForStorage(qryFileDestination);
                    blob.UploadFromFile(GetLocalDiskPath(qryFileDestination));
                }
                return(result);
            }
        }
Beispiel #40
0
 public FileResult DownloadFail(string filePath)
 {
     try
     {
         if (table == null || table.Rows.Count == 0)
         {
             return(null);
         }
         var        dr       = table.Select("备注 <> ''");
         var        fileName = Server.MapPath("~/Template/stock_import.xls");
         FileStream file     = new FileStream(fileName, FileMode.Open, FileAccess.Read);
         IWorkbook  book     = new HSSFWorkbook(file);
         ISheet     sheet1   = book.GetSheet("商品库存");
         for (int i = 0; i < dr.Length; i++)
         {
             IRow rowtemp = sheet1.CreateRow(i + 1);
             rowtemp.CreateCell(0).SetCellValue(dr[i]["序号"].ToString());
             rowtemp.CreateCell(1).SetCellValue(dr[i]["类别"].ToString());
             rowtemp.CreateCell(2).SetCellValue(dr[i]["SKU编码"].ToString());
             rowtemp.CreateCell(3).SetCellValue(dr[i]["商品编码"].ToString());
             rowtemp.CreateCell(4).SetCellValue(dr[i]["商品名称"].ToString());
             rowtemp.CreateCell(5).SetCellValue(dr[i]["规格"].ToString());
             rowtemp.CreateCell(6).SetCellValue(dr[i]["库存"].ToString());
             rowtemp.CreateCell(7).SetCellValue(dr[i]["预警数量"].ToString());
             rowtemp.CreateCell(8).SetCellValue(dr[i]["单位"].ToString());
             rowtemp.CreateCell(8).SetCellValue(dr[i]["备注"].ToString());
         }
         System.IO.MemoryStream ms = new System.IO.MemoryStream();
         book.Write(ms);
         ms.Seek(0, SeekOrigin.Begin);
         return(File(ms, "application/vnd.ms-excel", "商品库存失败数据" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"));
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #41
0
        public void ImplicitAndExplicitReturnTypes()
        {
            var xml        = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Root>
  <ApiGroup Name=""group"">
    <ApiMethod MethodName=""ftw"" ReturnType=""Person"" Path=""/ftw"" />
    <ReturnType Name=""person"" ClassName=""Person"">
      <Field Name=""location"" Type=""PersonLocation"" />
    </ReturnType>
    <ReturnType Name=""location"" ClassName=""PersonLocation"">
      <Field Name=""name"" />
    </ReturnType>
  </ApiGroup>
</Root>";
            var serializer = new XmlSerializer(typeof(ApisRoot));
            var reader     = new StringReader(xml);
            var root       = (ApisRoot)serializer.Deserialize(reader);
            var stream     = new System.IO.MemoryStream();
            var writer     = new System.IO.StreamWriter(stream);
            var generator  = new CSharpGenerator(writer);
            var builder    = new ServiceDefinitionBuilder();

            builder.AppendServiceDefinition(new ServiceDefinition(root));
            generator.Run(builder.Definition);

            writer.Flush();
            stream.Seek(0L, System.IO.SeekOrigin.Begin);
            var result = new StreamReader(stream).ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(result));
            Assert.IsFalse(string.IsNullOrEmpty(result));
            Assert.IsTrue(result.Contains("public class Person"));
            Assert.IsTrue(result.Contains("public class PersonLocation"));
            Assert.IsTrue(result.Contains("public PersonLocation Location"));
            Assert.IsFalse(result.Contains("public class Location"));
            Assert.IsTrue(result.Contains("public string Name"));
        }
Beispiel #42
0
 /// <summary>
 /// Serializes current test object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize(System.Text.Encoding encoding)
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try {
         memoryStream = new System.IO.MemoryStream();
         System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
         xmlWriterSettings.Encoding = encoding;
         System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         Serializer.Serialize(xmlWriter, this);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     } finally {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
        /*
         *
         *
         */

        private void UploadToAzure(string filePath, string relativePath)
        {
            System.IO.MemoryStream data = new System.IO.MemoryStream();
            System.IO.Stream       str  = System.IO.File.OpenRead(filePath);

            str.CopyTo(data);
            data.Seek(0, SeekOrigin.Begin);
            byte[] buf = new byte[data.Length];
            data.Read(buf, 0, buf.Length);

            Stream stream = data as Stream;

            if (stream.CanSeek)
            {
                stream.Position = 0;
                CloudBlockBlob blob = container.GetBlockBlobReference(StripContainerNameFromPath(relativePath));
                blob.UploadFromStream(stream);
                SetCacheControl(blob);
            }
            else
            {
                log.Error("Could not read image for upload: " + relativePath);
            }
        }
Beispiel #44
0
 /// <summary>
 /// Serializes current  object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public static string Serialize <T>(T xml, bool isThrowException = false)
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try
     {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         memoryStream = new System.IO.MemoryStream();
         serializer.Serialize(memoryStream, xml);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     catch (Exception ex)
     {
         if (isThrowException)
         {
             throw;
         }
         else
         {
             return(null);
         }
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
Beispiel #45
0
        public async Task <FileResult> Excel()
        {
            string userID = OpeCur.AccountNow.Id;

            searchNo = userID + "ID";
            gidPager = userID + "Pager";
            var                   cacheSearchNo = Core.CacheHelper.GetCache(searchNo);
            var                   cachePager    = Core.CacheHelper.GetCache(gidPager);
            string                queryStr      = (string)cacheSearchNo;
            GridPager             pager         = (GridPager)cachePager;
            List <QueryViewModel> listView      = await FilterData(pager, queryStr);

            if (!string.IsNullOrWhiteSpace(pager.filterRules))
            {
                List <DataFilterModel> dataFilterList = JsonHandler.Deserialize <List <DataFilterModel> >(pager.filterRules).Where(f => !string.IsNullOrWhiteSpace(f.value)).ToList();
                listView = LinqHelper.DataFilter <QueryViewModel>((listView.AsEnumerable()).AsQueryable(), dataFilterList).ToList();
            }

            #region 获取失效日期并转换"yyyy年MM月dd日"
            foreach (var item in listView)
            {
                await Task.Run <QueryViewModel>(() => { return(GetDataOfExpiry(item)); });
            }
            #endregion
            //整合代码
            //string title = new { "param":[{"WAREHOUSE":"仓库","ITEM":"编码","ITEM_DESC":"描述","COMPANY":"所属公司","ATTRIBUTE_NUM":"库存数量","ON_HAND_QTY":"处理数量"}] };
            //string[] tt = { "WAREHOUSE", "ITEM", "ITEM_DESC", "COMPANY", "ATTRIBUTE_NUM", "ON_HAND_QTY" };
            //DataTable tt1 = Commons.DataTableExtensions.ToDataTable<QueryViewModel>(listView, tt);//list数据转为Table类型
            //NPOIHelper.WriteToDownLoad("临空" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls", "sheet1", tt1);//写入excel

            #region 创建Excel表格
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");

            sheet1.SetColumnWidth(0, 15 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 35 * 256);
            sheet1.SetColumnWidth(3, 15 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 15 * 256);
            sheet1.SetColumnWidth(6, 15 * 256);
            sheet1.SetColumnWidth(7, 15 * 256);
            sheet1.SetColumnWidth(8, 10 * 256);
            sheet1.SetColumnWidth(9, 10 * 256);


            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("仓库");
            row1.CreateCell(1).SetCellValue("编号");
            row1.CreateCell(2).SetCellValue("描述");
            row1.CreateCell(3).SetCellValue("所属公司");
            row1.CreateCell(4).SetCellValue("生产日期");
            row1.CreateCell(5).SetCellValue("失效日期");
            row1.CreateCell(6).SetCellValue("合格");
            row1.CreateCell(7).SetCellValue("不合格");
            row1.CreateCell(8).SetCellValue("库存数量");
            row1.CreateCell(9).SetCellValue("处理数量");
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < listView.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(listView[i].WAREHOUSE);
                rowtemp.CreateCell(1).SetCellValue(listView[i].ITEM);
                rowtemp.CreateCell(2).SetCellValue(listView[i].ITEM_DESC);
                rowtemp.CreateCell(3).SetCellValue(listView[i].COMPANY);
                rowtemp.CreateCell(4).SetCellValue(listView[i].DateOfProduction == null ? null : listView[i].DateOfProduction.ToString());
                rowtemp.CreateCell(5).SetCellValue(listView[i].DateOfExpiry == null ? null : (listView[i].DateOfExpiry).ToString());
                rowtemp.CreateCell(6).SetCellValue(listView[i].IsQualified.ToString());
                rowtemp.CreateCell(7).SetCellValue(listView[i].IsNotQualified.ToString());
                rowtemp.CreateCell(8).SetCellValue(listView[i].ATTRIBUTE_NUM.ToString());
                rowtemp.CreateCell(9).SetCellValue(listView[i].ON_HAND_QTY.ToString());
            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            #endregion
            #region Excel 保存路径
            // 输出Excel文件
            #endregion

            return(await Task.Run <FileResult>(() => { return File(ms, "application/vnd.ms-excel", "临空" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"); }));
        }
Beispiel #46
0
        public FileResult ImportOut()
        {
            #region Excel基类数据
            HSSFWorkbook             book    = new HSSFWorkbook();
            Dictionary <string, int> e_param = new Dictionary <string, int> {
                { "条形码", 20 },
                { "商品名称", 40 },
                { "数量", 20 },
                { "单价", 20 },
                { "金额", 20 },
                { "备注", 20 },
                { "系统备注", 20 }
            };

            Dictionary <string, string> e_param_comment = new Dictionary <string, string> {
                { "条形码", "规则:\r\n1.必填 " },
                { "数量", "规则:\r\n1.必填 " }
            };

            ISheet sheet1             = NPOIHelper.CreateSheet(book, e_param, e_param_comment, "销售退货商品资料导出");
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            #endregion

            try
            {
                #region 获取数据
                Hashtable   param = base.GetParameters();
                ParamVessel p     = new ParamVessel();
                p.Add("shopspList", string.Empty, HandleType.ReturnMsg);//商品List
                param = param.Trim(p);
                List <Td_Jh_2_QueryModel> shopspList = JSON.Deserialize <List <Td_Jh_2_QueryModel> >(param["shopspList"].ToString()) ?? new List <Td_Jh_2_QueryModel>();
                #endregion
                #region 验证数据
                if (shopspList == null || shopspList.Count() <= 0)
                {
                    IRow rowtemp = sheet1.CreateRow(1);
                    rowtemp.CreateCell(0).SetCellValue("");
                    rowtemp.CreateCell(1).SetCellValue("");
                    rowtemp.CreateCell(2).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                    rowtemp.CreateCell(3).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                    rowtemp.CreateCell(4).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                    rowtemp.CreateCell(5).SetCellValue("");
                    rowtemp.CreateCell(6).SetCellValue("无有效数据");
                    sheet1.GetRow(1).Height = 28 * 20;
                    // 写入到客户端
                    book.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return(File(ms, "application/vnd.ms-excel", "销售退货商品资料导出-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"));
                }
                #endregion
                #region 数量、单价、金额小数点
                var digit = GetParm();
                #endregion
                #region 构建Excel数据内容
                int i = 1;
                foreach (var item in shopspList)
                {
                    IRow rowtempdata = sheet1.CreateRow(i);
                    rowtempdata.CreateCell(0).SetCellValue(item.barcode);
                    rowtempdata.CreateCell(1).SetCellValue(item.shopsp_name);
                    rowtempdata.CreateCell(2).SetCellValue(Decimal.Round((decimal)(item.sl), int.Parse(digit["sl_digit"].ToString())).ToString());
                    rowtempdata.CreateCell(3).SetCellValue(Decimal.Round((decimal)(item.dj), int.Parse(digit["dj_digit"].ToString())).ToString());
                    rowtempdata.CreateCell(4).SetCellValue(Decimal.Round((decimal)(item.je), int.Parse(digit["je_digit"].ToString())).ToString());
                    rowtempdata.CreateCell(5).SetCellValue(item.bz);
                    rowtempdata.CreateCell(6).SetCellValue("");
                    sheet1.GetRow(i).Height = 28 * 20;
                    i++;
                }
                #endregion
                #region 写入到客户端
                // 写入到客户端
                book.Write(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return(File(ms, "application/vnd.ms-excel", "销售退货商品资料导出-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"));

                #endregion
            }
            catch (Exception ex)
            {
                #region 异常处理
                IRow rowtempe = sheet1.CreateRow(1);
                rowtempe.CreateCell(0).SetCellValue("");
                rowtempe.CreateCell(1).SetCellValue("");
                rowtempe.CreateCell(2).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                rowtempe.CreateCell(3).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                rowtempe.CreateCell(4).SetCellValue(Decimal.Round((decimal)(0), 2).ToString());
                rowtempe.CreateCell(5).SetCellValue("");
                rowtempe.CreateCell(6).SetCellValue("销售退货导出出现异常 请重试");
                sheet1.GetRow(1).Height = 28 * 20;
                // 写入到客户端
                book.Write(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return(File(ms, "application/vnd.ms-excel", "销售退货商品资料导出-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"));

                #endregion
            }
        }
Beispiel #47
0
        private Boolean FindFile(String filename, ref Byte track, ref Byte sector, ref Byte index)
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            Boolean fileMatchFound = false;

            Byte dirTrack  = 20;
            Byte dirSector = 4;

            Byte nextDirTrack  = 20;
            Byte nextDirSector = 4;

            while ((nextDirTrack != 0 && nextDirSector != 0) && fileMatchFound == false)
            {
                // Read current Directory Sector
                Byte[] directory = base.ReadSector(dirTrack, dirSector);

                nextDirTrack  = directory[0x00];
                nextDirSector = directory[0x01];

                index = 0;

                // Scan thru each file in the current directory
                System.IO.MemoryStream memStream    = new System.IO.MemoryStream(directory, 0, directory.Length);
                System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(memStream);

                // Move to first entry
                memStream.Seek(0x10, SeekOrigin.Begin);

                while (!fileMatchFound && index < 15)
                {
                    if (binaryReader.PeekChar() != 0x00)
                    {
                        Byte[] fileName  = binaryReader.ReadBytes(9);
                        Byte[] extension = binaryReader.ReadBytes(3);

                        String dirFilename  = enc.GetString(fileName).Trim();
                        String dirExtension = enc.GetString(extension).Trim();

                        String pathname = String.Format("{0}.{1}", dirFilename, dirExtension);

                        if (pathname == filename)
                        {
                            fileMatchFound = true;
                        }
                        else
                        {
                            index++;
                        }
                    }

                    binaryReader.ReadBytes(4);
                }

                if (!fileMatchFound)
                {
                    dirTrack  = nextDirTrack;
                    dirSector = nextDirSector;
                }
                else
                {
                    track  = dirTrack;
                    sector = dirSector;

                    index++;
                }
            }

            return(fileMatchFound);
        }
Beispiel #48
0
    private void OnGUI()
    {
        this.scroll = GUILayout.BeginScrollView(this.scroll);

        for (int i = 0; i < this.samples.Count; ++i)
        {
            TestSample ts = this.samples[i];
            if (GUILayout.Button(ts.label) == true)
            {
                this.meta = null;

                byte [] rb = System.IO.File.ReadAllBytes(ts.path);
                System.IO.MemoryStream memStream = new System.IO.MemoryStream(rb);
                System.IO.BinaryReader r         = new System.IO.BinaryReader(memStream);
                this.foundChunks = PxPre.Vinyl.Wav.WAVUtils.ParseStaticChunks(r);

                Debug.Log(this.foundChunks.Count.ToString() + " chunks!");

                foreach (PxPre.Vinyl.Wav.ChunkTable c in this.foundChunks)
                {
                    if (c.chunkID == (int)PxPre.Vinyl.Wav.ChunkID.fmt)
                    {
                        memStream.Seek(c.filePos, System.IO.SeekOrigin.Begin);
                        this.format.Read(r);
                    }
                    else if (c.chunkID == (int)PxPre.Vinyl.Wav.ChunkID.id3)
                    {
                        memStream.Seek(c.filePos, System.IO.SeekOrigin.Begin);
                        PxPre.Vinyl.Meta.ID3_2 id32 = new PxPre.Vinyl.Meta.ID3_2();
                        this.meta = id32.ReadToID31(r);


                        //PxPre.WavLib.ID3 id3 = new PxPre.WavLib.ID3();
                        //id3.Read(r);
                        //this.meta = id3;
                    }
                }

                PxPre.Vinyl.Wav.ChunkFmt?         fmt;
                List <PxPre.Vinyl.Wav.AudioChunk> audios =
                    PxPre.Vinyl.Wav.WAVUtils.ParseStaticPCM(r, this.foundChunks, out fmt);

                float [] pcm = PxPre.Vinyl.Wav.WAVUtils.GetChannel(audios, 0);

                AudioClip ac = AudioClip.Create("", pcm.Length, this.format.numChannels, (int)this.format.sampleRate, false);
                ac.SetData(pcm, 0);
                this.audioSource.clip = ac;
                this.audioSource.Play();
            }
        }

        GUILayout.Label($"Compression : {format.compressionCode}");
        GUILayout.Label($"Channels : {format.numChannels}");
        GUILayout.Label($"Sample Rate : {format.sampleRate}");
        GUILayout.Label($"Byte Rate : {format.avgBytesPerSecond}");
        GUILayout.Label($"Block Align : {format.blockAlign}");
        GUILayout.Label($"Significant Bits/S : {format.sigBitsPerSample}");
        GUILayout.Label($"Extra Bytes : {format.extraFormatBytes}");

        if (this.foundChunks.Count > 0)
        {
            foreach (PxPre.Vinyl.Wav.ChunkTable ct in this.foundChunks)
            {
                GUILayout.BeginVertical(GUI.skin.box);
                GUILayout.Label("CHUNK DATA");

                byte [] rb = System.BitConverter.GetBytes(ct.chunkID);
                //System.Array.Reverse(rb);
                string id = System.Text.ASCIIEncoding.ASCII.GetString(rb);
                GUILayout.Label($"ID : {id}");
                GUILayout.Label($"POS : {ct.filePos}");
                GUILayout.Label($"SIZE : {ct.size}");
                GUILayout.EndHorizontal();
            }
        }

        if (this.meta != null)
        {
            GUILayout.Label($"Tag : {this.meta.Value.tag}");
            GUILayout.Label($"Title : {this.meta.Value.title}");
            GUILayout.Label($"Artist : {this.meta.Value.artist}");
            GUILayout.Label($"Album : {this.meta.Value.album}");
            GUILayout.Label($"Year : {this.meta.Value.year}");
            GUILayout.Label($"Comment : {this.meta.Value.comment}");
            GUILayout.Label($"Track : {this.meta.Value.track}");
            GUILayout.Label($"Genre : {this.meta.Value.genre}");
        }

        if (this.audioSource.clip != null)
        {
            if (GUILayout.Button("Export byte") == true)
            {
                float [] data = new float[this.audioSource.clip.samples];
                this.audioSource.clip.GetData(data, 0);

                byte [] rb = new byte[data.Length];
                for (int i = 0; i < data.Length; ++i)
                {
                    rb[i] = (byte)Mathf.Clamp((int)(data[i] * 128.0 + 128.0f), 0, 255);
                }

                System.IO.FileStream   fs = new System.IO.FileStream("TestExport8i.wav", System.IO.FileMode.Create);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                PxPre.Vinyl.Wav.WAVUtils.CreateSimpleWavBinary(bw, rb, 44100, 1);
            }

            if (GUILayout.Button("Explort short") == true)
            {
                float[] data = new float[this.audioSource.clip.samples];
                this.audioSource.clip.GetData(data, 0);

                short [] rs = new short[data.Length];
                for (int i = 0; i < data.Length; ++i)
                {
                    rs[i] = (short)Mathf.Clamp((int)(data[i] * short.MaxValue), short.MinValue, short.MaxValue);
                }

                System.IO.FileStream   fs = new System.IO.FileStream("TestExport16i.wav", System.IO.FileMode.Create);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                PxPre.Vinyl.Wav.WAVUtils.CreateSimpleWavBinary(bw, rs, 44100, 1);
            }

            if (GUILayout.Button("Export int") == true)
            {
                float[] data = new float[this.audioSource.clip.samples];
                this.audioSource.clip.GetData(data, 0);

                int [] ri = new int[data.Length];
                for (int i = 0; i < data.Length; ++i)
                {
                    ri[i] = Mathf.Clamp((int)(data[i] * int.MaxValue), int.MinValue, int.MaxValue);
                }

                System.IO.FileStream   fs = new System.IO.FileStream("TestExport32i.wav", System.IO.FileMode.Create);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                PxPre.Vinyl.Wav.WAVUtils.CreateSimpleWavBinary(bw, ri, 44100, 1);
            }

            if (GUILayout.Button("Export float") == true)
            {
                float[] data = new float[this.audioSource.clip.samples];
                this.audioSource.clip.GetData(data, 0);

                // Yea yea, no practical point to this, but we're just testing the
                // float saving.
                float [] rf = data;

                System.IO.FileStream   fs = new System.IO.FileStream("TestExport32f.wav", System.IO.FileMode.Create);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                PxPre.Vinyl.Wav.WAVUtils.CreateSimpleWavBinary(bw, rf, 44100, 1);
            }

            if (GUILayout.Button("Export double") == true)
            {
                float[] data = new float[this.audioSource.clip.samples];
                this.audioSource.clip.GetData(data, 0);

                double [] rd = new double[data.Length];
                for (int i = 0; i < data.Length; ++i)
                {
                    rd[i] = data[i];
                }

                System.IO.FileStream   fs = new System.IO.FileStream("TestExport64f.wav", System.IO.FileMode.Create);
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                PxPre.Vinyl.Wav.WAVUtils.CreateSimpleWavBinary(bw, rd, 44100, 1);
            }
        }

        GUILayout.EndScrollView();
    }
Beispiel #49
0
        private OricFileInfo[] ReadSedOricDirectory()
        {
            OricFileInfo[] diskDirectory = null;

            //int noOfFiles = 0;

            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            ArrayList diskCatalog = new ArrayList();

            Byte bNextTrack  = Convert.ToByte(20);
            Byte bNextSector = Convert.ToByte(4);

            Byte bCurrTrack  = bNextTrack;
            Byte bCurrSector = bNextSector;

            Boolean MoreDirectories = true;

            while (MoreDirectories)
            {
                // Read the first directory sector
                Byte[] directory = base.ReadSector(bCurrTrack, bCurrSector);

                if (directory[0] == 0x00 && directory[1] == 0x00)
                {
                    MoreDirectories = false;
                }
                else
                {
                    bCurrTrack  = directory[0];
                    bCurrSector = directory[1];
                }

                // Scan thru all 15 entries to build the directory
                UInt16 DirectoryIndex = 0;

                System.IO.MemoryStream stm = new System.IO.MemoryStream(directory, 0, 256);
                System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm);
                stm.Seek(0x10, SeekOrigin.Begin);

                do
                {
                    if (rdr.PeekChar() != 0x00)
                    {
                        // Read the filename
                        String Filename = enc.GetString(rdr.ReadBytes(9)).Trim();

                        // Read the file extension
                        String FileExtension = enc.GetString(rdr.ReadBytes(3)).Trim();

                        // Read the file descriptor track
                        Byte FileDescTrack = rdr.ReadByte();

                        // Read the file descriptor sector
                        Byte FileDescSector = rdr.ReadByte();

                        // Read the no. of sectors used by file (includes file descriptor)
                        Byte SectorsUsed = rdr.ReadByte();

                        // Read the files protection status
                        Byte ProtectionStatus = rdr.ReadByte();

                        OricFileInfo diskFileInfo = new OricFileInfo();
                        diskFileInfo.MediaType = OricExplorer.MediaType.DiskFile;

                        //diskFileInfo.m_bDosFormat = OricDisk.DOSFormat.SedOric;

                        diskFileInfo.Folder     = base.diskFolder;
                        diskFileInfo.ParentName = base.diskPathname;

                        diskFileInfo.ProgramName = Filename;
                        diskFileInfo.Extension   = FileExtension;

                        if (FileExtension.Length > 0)
                        {
                            diskFileInfo.ProgramName = String.Format("{0}.{1}", Filename, FileExtension);
                        }
                        else
                        {
                            diskFileInfo.ProgramName = Filename;
                        }

                        diskFileInfo.FirstTrack    = FileDescTrack;
                        diskFileInfo.FirstSector   = FileDescSector;
                        diskFileInfo.LengthSectors = SectorsUsed;

                        if (ProtectionStatus == 0xC0)
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Protected;
                        }
                        else if (ProtectionStatus == 0x40)
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected;
                        }
                        else
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected;
                        }

                        Byte[] FileDescriptor = base.ReadSector(FileDescTrack, FileDescSector);

                        System.IO.MemoryStream stmFileDescriptor = new System.IO.MemoryStream(FileDescriptor, 0, FileDescriptor.Length);
                        System.IO.BinaryReader rdrFileDescriptor = new System.IO.BinaryReader(stmFileDescriptor);

                        stmFileDescriptor.Seek(0x03, SeekOrigin.Begin);

                        Byte FileType = rdrFileDescriptor.ReadByte();

                        if ((FileType & 0x08) == 0x08)
                        {
                            // We have a direct access file
                            diskFileInfo.m_ui16NoOfRecords  = rdrFileDescriptor.ReadUInt16();
                            diskFileInfo.m_ui16RecordLength = rdrFileDescriptor.ReadUInt16();

                            diskFileInfo.StartAddress = 0x0000;
                            diskFileInfo.EndAddress   = (ushort)(diskFileInfo.m_ui16NoOfRecords * diskFileInfo.m_ui16RecordLength);
                        }
                        else if ((FileType & 0x10) == 0x10)
                        {
                            // We have a sequential file
                            diskFileInfo.StartAddress = 0x0000;
                            diskFileInfo.EndAddress   = (ushort)((diskFileInfo.LengthSectors - 1) * 256);
                        }
                        else
                        {
                            diskFileInfo.StartAddress = rdrFileDescriptor.ReadUInt16();
                            diskFileInfo.EndAddress   = rdrFileDescriptor.ReadUInt16();
                        }

                        diskFileInfo.ExeAddress = rdrFileDescriptor.ReadUInt16();

                        if ((FileType & 0x08) == 0x08)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.DirectAccessFile;
                        }
                        else if ((FileType & 0x10) == 0x10)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.SequentialFile;
                        }
                        else if ((FileType & 0x20) == 0x20)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.WindowFile;
                        }
                        else if ((FileType & 0x40) == 0x40)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile;
                        }
                        else if ((FileType & 0x80) == 0x80)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.BasicProgram;
                        }
                        else
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.UnknownFile;
                        }

                        if (diskFileInfo.Format == OricProgram.ProgramFormat.CodeFile)
                        {
                            switch (diskFileInfo.StartAddress)
                            {
                            case 0xBB80:
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile;
                                }
                                else
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen;
                                }
                                break;

                            case 0xBBA8:
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile;
                                }
                                else
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen;
                                }
                                break;

                            case 0xA000: diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen; break;

                            case 0xB500: diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet; break;

                            default: diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile; break;
                            }

                            if (diskFileInfo.StartAddress >= 0xA000 && diskFileInfo.StartAddress <= 0xBF3F)
                            {
                                // Possibly a HIRES screen
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HRS"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen;
                                }
                            }

                            if (diskFileInfo.ProgramName.ToUpper().EndsWith(".CHS") || diskFileInfo.ProgramName.ToUpper().EndsWith(".CHR"))
                            {
                                diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet;
                            }
                        }

                        if ((FileType & 0x01) == 0x01)
                        {
                            diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Enabled;
                        }
                        else
                        {
                            diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Disabled;
                        }

                        diskCatalog.Add(diskFileInfo);
                    }

                    DirectoryIndex++;
                } while (DirectoryIndex < 15);
            }

            diskDirectory = new OricFileInfo[diskCatalog.Count];
            diskCatalog.CopyTo(diskDirectory);

            return(diskDirectory);
        }
Beispiel #50
0
        public override Boolean DeleteFile(String diskName, String filename)
        {
            Boolean fileDeleted = false;

            // Find matching entry in the directory
            Byte track  = 0x00;
            Byte sector = 0x00;
            Byte index  = 0x00;

            base.LoadDisk(diskName);
            ReadBitmap1();

            // Locate file in directory and return directory reference
            Boolean fileFound = FindFile(filename, ref track, ref sector, ref index);

            if (fileFound)
            {
                // Get the file descriptor
                Byte[] fileDescriptor = GetFileDescriptor(filename);

                // Scan thought the descriptor for each sector to delete
                MemoryStream memoryStream = new System.IO.MemoryStream(fileDescriptor, 0, fileDescriptor.Length);
                BinaryReader binReader    = new System.IO.BinaryReader(memoryStream);

                // Move to the required offset
                memoryStream.Seek(0x0A, SeekOrigin.Begin);

                // Get number of sectors
                UInt16 noOfSectors = binReader.ReadUInt16();

                UInt16 sectorIndex = 0;

                while (sectorIndex < noOfSectors)
                {
                    Byte fileDataTrack  = binReader.ReadByte();
                    Byte fileDataSector = binReader.ReadByte();

                    if (fileDataSector != 0x00)
                    {
                        // Clear data in the sector
                        Byte[] sectorData = base.ReadSector(fileDataTrack, fileDataSector);

                        for (int dataIndex = 0; dataIndex < sectorData.Length; dataIndex++)
                        {
                            sectorData[dataIndex] = 0x00;
                        }

                        base.WriteSector(fileDataTrack, fileDataSector, sectorData);

                        sectorsFree++;

                        // Update the Bitmap to indicate sector is now free
                        UpdateBitmap(fileDataTrack, fileDataSector, SectorState.FREE);
                    }

                    sectorIndex++;
                }

                // Initialise the Program descriptor

                // Get directory entry
                Byte[] directory = base.ReadSector(track, sector);

                // Calculate start position of directory entry
                int bufferIndex = 0x10 * index;

                // Get Track & Sector of the File descriptor
                Byte descTrack  = directory[bufferIndex + 0x0C];
                Byte descSector = directory[bufferIndex + 0x0D];

                // Clear data in the sector
                Byte[] descSectorData = base.ReadSector(descTrack, descSector);

                for (int dataIndex = 0; dataIndex < descSectorData.Length; dataIndex++)
                {
                    descSectorData[dataIndex] = 0x00;
                }

                base.WriteSector(descTrack, descSector, descSectorData);

                sectorsFree++;

                // Update the Bitmap to indicate sector is now free
                UpdateBitmap(descTrack, descSector, SectorState.FREE);

                // Update Directory to remove the entry
                //RemoveDirectoryEntry(filename);

                noOfFiles--;

                // Update Bitmap 1 (No. of Sectors free and No. of files in Bitmap 1 and 2)
                Byte[] Bitmap1 = base.ReadSector(20, 2);

                MemoryStream memStream = new System.IO.MemoryStream(Bitmap1, 0, Bitmap1.Length);
                BinaryWriter bw        = new System.IO.BinaryWriter(memStream);

                memStream.Seek(0x02, SeekOrigin.Begin);

                bw.Write(sectorsFree);
                bw.Write(noOfFiles);

                base.WriteSector(20, 2, Bitmap1);

                // Update Bitmap 1 (No. of Sectors free and No. of files in Bitmap 1 and 2)
                Byte[] Bitmap2 = base.ReadSector(20, 3);

                MemoryStream memStream2 = new System.IO.MemoryStream(Bitmap2, 0, Bitmap2.Length);
                BinaryWriter bw2        = new System.IO.BinaryWriter(memStream2);

                memStream2.Seek(0x04, SeekOrigin.Begin);
                bw2.Write(noOfFiles);

                base.WriteSector(20, 3, Bitmap2);

                base.WriteDisk();

                fileDeleted = true;

                // No reorganise the directory to remove any empty entries
                ReorganiseDirectory(diskName, filename);
            }
            else
            {
                fileDeleted = false;
            }

            return(fileDeleted);
        }
        public void DrawProfilesModule()
        {
            // Get subject node id
            Int64 qsNodeId;

            if (Int64.TryParse(HttpContext.Current.Request.QueryString["subject"].ToString(), out qsNodeId) == false)
            {
                throw new InvalidOperationException(String.Format("Expected Int64 NodeId, '{0}' was returned.", HttpContext.Current.Request.QueryString["subject"].ToString()));
            }

            // Get stored proc based on timeline type
            string timelineType = base.GetModuleParamString("TimelineType");
            string proc         = null;

            switch (timelineType)
            {
            case "CoAuthor":
                proc = "[Profile.Module].[NetworkTimeline.Person.CoAuthorOf.GetData]";
                break;

            case "Concept":
                proc = "[Profile.Module].[NetworkTimeline.Person.HasResearchArea.GetData]";
                break;

            default:
                throw new InvalidOperationException("Please select ChartType.");
            }

            // Get data
            Profiles.Profile.Utilities.DataIO dataIO = new Profiles.Profile.Utilities.DataIO();
            DataView dataView = dataIO.GetNetworkTimeline(new RDFTriple(qsNodeId), proc);

            // Draw timeline chart
            if (dataView.Count > 0)
            {
                int    x = 0, y = 0, i, a, b, j, c, d, n, w, k = 0;
                bool   drawAvg;
                string label = null;

                if (int.TryParse(dataView[0]["a"].ToString(), out a) == false)
                {
                    throw new InvalidOperationException("Value 'a' is not a number");
                }

                if (int.TryParse(dataView[0]["b"].ToString(), out b) == false)
                {
                    throw new InvalidOperationException("Value 'b' is not a number");
                }

                if (int.TryParse(dataView[0]["n"].ToString(), out n) == false)
                {
                    throw new InvalidOperationException("Value 'n' is not a number");
                }

                j = b - a;
                c = Convert.ToInt32(j / 2 + 0.5);
                d = Convert.ToInt32(j / 15) + 1;
                w = 400;

                SolidBrush brushWhite = new SolidBrush(Color.White);
                SolidBrush brushAvg   = new SolidBrush(Color.FromArgb(204, 0, 30));
                SolidBrush brushPub   = new SolidBrush(Color.Blue);

                Pen penTimeline     = new Pen(Color.FromArgb(170, 170, 204), 2);
                Pen penTimelineThin = new Pen(Color.FromArgb(230, 230, 230), 1);
                Pen penYears        = new Pen(Color.FromArgb(102, 102, 102), 1);
                Pen penGraphBox     = new Pen(Color.FromArgb(102, 102, 102), 1);

                Bitmap bitmap = new Bitmap(w + 30, n * 20 + 40);

                Graphics graphic = Graphics.FromImage(bitmap);
                graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

                // Draw background white
                graphic.FillRectangle(brushWhite, 0, 0, w + 30, n * 20 + 40);

                // Draw year key at top
                graphic.DrawLine(penYears, new Point(15, 20), new Point(15 + w, 20));
                for (i = 0; i <= j; i++)
                {
                    x = 15 + Convert.ToInt32((w * i / j));
                    graphic.DrawLine(penYears, new Point(x, 15), new Point(x, 20));
                    if ((j - i) % d == 0)
                    {
                        graphic.DrawString(
                            (a + i).ToString(),
                            new Font("Arial", 7),
                            new SolidBrush(Color.Black),
                            new Point(x - 10, 0)
                            );
                    }
                }

                // Draw timelines
                for (i = 0; i <= dataView.Count - 1; i++)
                {
                    if (label != dataView[i]["label"].ToString())
                    {
                        k++;
                    }

                    x = Convert.ToInt32(Convert.ToSingle(dataView[i]["x"]) * w + 0.5) + 15;
                    y = k * 20 + 20;

                    if (label != dataView[i]["label"].ToString())
                    {
                        label = dataView[i]["label"].ToString();
                        //oGraphic.DrawString(sLabel, New Font("Arial", 7), New SolidBrush(Color.Black), New Point(10, y))
                        graphic.DrawLine(penTimelineThin, new PointF(15, y), new PointF(15 + w, y));
                        graphic.DrawLine(penTimeline, new PointF(15 + (Convert.ToSingle(dataView[i]["MinX"])) * w, y), new PointF(15 + (Convert.ToSingle(dataView[i]["MaxX"])) * w, y));
                    }
                    graphic.FillRectangle(brushPub, x - 1, y - 3, 3, 6);
                    drawAvg = false;
                    if (i == dataView.Count - 1)
                    {
                        drawAvg = true;
                    }
                    else if (label != dataView[i + 1]["label"].ToString())
                    {
                        drawAvg = true;
                    }

                    if (drawAvg)
                    {
                        x = Convert.ToInt32(Convert.ToSingle(dataView[i]["AvgX"]) * w + 0.5) + 15;
                        graphic.FillEllipse(brushAvg, new Rectangle(x - 5, y - 5, 10, 10));
                    }
                }

                graphic.DrawLine(penGraphBox, new Point(15, 20), new Point(15, 30 + 20 * n));

                // Write out image
                byte[] imageArray;
                using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
                {
                    bitmap.Save(imageStream, ImageFormat.Png);
                    imageArray = new byte[imageStream.Length];
                    imageStream.Seek(0, System.IO.SeekOrigin.Begin);
                    imageStream.Read(imageArray, 0, Convert.ToInt32(imageStream.Length));
                }
                timelineImage.Src = "data:image/png;base64," + Convert.ToBase64String(imageArray);

                // Write out timeline detail list
                StringBuilder sb = new StringBuilder();
                label = string.Empty;
                for (i = 0; i <= dataView.Count - 1; i++)
                {
                    if (label != dataView[i]["label"].ToString())
                    {
                        sb.AppendFormat("<a href=\"{0}\">{1}</a><br/>", dataView[i]["ObjectURI"].ToString(), dataView[i]["label"].ToString());
                        label = dataView[i]["label"].ToString();
                    }
                }
                timelineDetails.InnerHtml = sb.ToString();

                string        altText   = "";
                StringBuilder tableText = new StringBuilder();
                tableText.AppendLine("<div class=\"listTable\" style=\"margin-top: 12px, margin-bottom:8px \"><table>");
                tableText.AppendLine("<tr><th>Name</th><th>Number of Publications</th><th>First Publication Year</th><th>Most Recent Publication Year</th><th>Average Publication Date</th></tr>");

                switch (timelineType)
                {
                case "CoAuthor":
                    for (i = 0; i < dataView.Count; i++)
                    {
                        bool run = false;
                        if (i == dataView.Count - 1)
                        {
                            run = true;
                        }
                        else if (dataView[i]["label"].ToString() != dataView[i + 1]["label"].ToString())
                        {
                            run = true;
                        }
                        if (run)
                        {
                            string l        = dataView[i]["label"].ToString();
                            double AvgX     = Double.Parse(dataView[i]["AvgX"].ToString());
                            double Avg      = (double)a + (double)j * AvgX;
                            int    AvgYear  = (int)Avg;
                            int    AvgMonth = (int)((Avg - (double)AvgYear) * (double)12);
                            string month    = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(AvgMonth + 1);
                            altText = altText + l + ", " + dataView[i]["PublicationCount"].ToString() + " publications between " + dataView[i]["FirstPublicationYear"].ToString() +
                                      " and " + dataView[i]["LastPublicationYear"].ToString() + ", average publication date " + month + " " + AvgYear + ". ";
                            tableText.AppendLine("<tr><td style=\"text-align:left\"><a href=\"" + dataView[i]["ObjectURI"].ToString() + "\">" + l + "</a></td><td>" + dataView[i]["PublicationCount"].ToString() + "</td><td>" + dataView[i]["FirstPublicationYear"].ToString() + "</td><td>" + dataView[i]["LastPublicationYear"].ToString() + "</td><td style=\"text-align:left\">" + month + " " + AvgYear + "</td></tr>");
                        }
                    }
                    break;

                case "Concept":
                    for (i = 0; i < dataView.Count; i++)
                    {
                        bool run = false;
                        if (i == dataView.Count - 1)
                        {
                            run = true;
                        }
                        else if (dataView[i]["label"].ToString() != dataView[i + 1]["label"].ToString())
                        {
                            run = true;
                        }
                        if (run)
                        {
                            string l        = dataView[i]["label"].ToString();
                            double AvgX     = Double.Parse(dataView[i]["AvgX"].ToString());
                            double Avg      = (double)a + (double)j * AvgX;
                            int    AvgYear  = (int)Avg;
                            int    AvgMonth = (int)((Avg - (double)AvgYear) * (double)12);
                            string month    = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(AvgMonth + 1);
                            altText = altText + l + ", " + dataView[i]["NumPubsThis"].ToString() + " publications between " + dataView[i]["FirstPublicationYear"].ToString() +
                                      " and " + dataView[i]["LastPublicationYear"].ToString() + ", average publication date " + month + " " + AvgYear + ". ";
                            tableText.AppendLine("<tr><td style=\"text-align:left\"><a href=\"" + dataView[i]["ObjectURI"].ToString() + "\">" + l + "</a></td><td>" + dataView[i]["NumPubsThis"].ToString() + "</td><td>" + dataView[i]["FirstPublicationYear"].ToString() + "</td><td>" + dataView[i]["LastPublicationYear"].ToString() + "</td><td style=\"text-align:left\">" + month + " " + AvgYear + "</td></tr>");
                        }
                    }
                    break;
                }
                tableText.AppendLine("</table></div>");
                timelineImage.Alt   = altText;
                litNetworkText.Text = tableText.ToString();
            }



            if (dataView.Count == 0)
            {
                timelineImage.Visible = false;
            }
        }
Beispiel #52
0
        //导出到excell
        /// <summary>
        ///
        /// </summary>
        /// <param name="nickName"></param>
        /// <param name="nickTime"></param>
        public FileResult Export(string nickName, string nickTime)
        {
            //try
            //{
            List <SumBaseDto>          SumSheet = SumService.GetAll(nickName, nickTime);
            HSSFWorkbook               book     = new HSSFWorkbook();
            DocumentSummaryInformation dsi      = PropertySetFactory.CreateDocumentSummaryInformation();

            dsi.Company = "NPOI Team";
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();

            si.Subject = "NPTO SDK Example";
            si.Title   = "学习或工作总结表";
            book.DocumentSummaryInformation = dsi;
            book.SummaryInformation         = si;
            ISheet sheet = book.CreateSheet("sheet1");

            IRow row0 = sheet.CreateRow(0);

            row0.CreateCell(0).SetCellValue("用户ID");
            row0.CreateCell(1).SetCellValue("姓名");
            row0.CreateCell(2).SetCellValue("学习/工作内容");
            row0.CreateCell(3).SetCellValue("学习/工作情况简介");
            row0.CreateCell(4).SetCellValue("遇到的问题");
            row0.CreateCell(5).SetCellValue("是否解决");
            row0.CreateCell(6).SetCellValue("教师回复");
            row0.CreateCell(7).SetCellValue("总结时间");

            for (int i = 0; i < SumSheet.Count; i++)
            {
                IRow rowtemp = sheet.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(SumSheet[i].User_ID);
                rowtemp.CreateCell(1).SetCellValue(SumSheet[i].Real_Name);
                rowtemp.CreateCell(2).SetCellValue(SumSheet[i].Title);
                rowtemp.CreateCell(3).SetCellValue(SumSheet[i].Progress);

                if (SumSheet[i].Problem == null)
                {
                    rowtemp.CreateCell(4).SetCellValue("无");
                    rowtemp.CreateCell(5).SetCellValue("");
                }
                else
                {
                    rowtemp.CreateCell(4).SetCellValue(SumSheet[i].Problem);
                    if (SumSheet[i].IS_Solve == 0)
                    {
                        rowtemp.CreateCell(5).SetCellValue("已解决");
                    }
                    if (SumSheet[i].IS_Solve == 1)
                    {
                        rowtemp.CreateCell(5).SetCellValue("尚未解决");
                    }
                }
                rowtemp.CreateCell(6).SetCellValue(SumSheet[i].Teacher_evaluation);
                rowtemp.CreateCell(7).SetCellValue(SumSheet[i].Time.ToString());
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);

            ms.Seek(0, SeekOrigin.Begin);
            return(File(ms, "application/vnd.ms-excel", "学习或工作总结" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"));
            //String fileName = "学习或工作总结.xls ";
            //return View();
        }
Beispiel #53
0
        private void SaveExcelToSharePath(DataTable dtExport)
        {
            MemoryStream TemplateStream = new System.IO.MemoryStream();

            try
            {
                string strDateTimeFileName = DateTime.Now.ToString("yyyyMMdd_HHmm");
                string strFileName         = string.Empty;
                string tmpPath             = string.Format("{0}\\Template\\Excel\\{1}", System.AppDomain.CurrentDomain.BaseDirectory, "WSLogINS_Template.xlsx");

                ErrorStep = "Read WSLog template file";
                Console.WriteLine(ErrorStep);
                using (var TemplateBase = new System.IO.FileStream(tmpPath, System.IO.FileMode.Open))
                {
                    TemplateBase.CopyTo(TemplateStream);
                    TemplateBase.Close();
                    TemplateStream.Seek(0, SeekOrigin.Begin);
                }

                ErrorStep = "Prepare WSLog data";
                Console.WriteLine(ErrorStep);

                int iAllExcelRow   = dtExport.Rows.Count;
                int iMaxRowPerFile = Convert.ToInt32(AppConstant.MaxExcelRowPerFile);
                int iNoOfExcelFile = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(iAllExcelRow) / Convert.ToDouble(iMaxRowPerFile)));

                Console.WriteLine(string.Format("All Excel row(s) : {0}", iAllExcelRow));
                Console.WriteLine(string.Format("Max Row per file : {0}", iMaxRowPerFile));
                Console.WriteLine(string.Format("Number of Excel file : {0}", iNoOfExcelFile));

                for (int i = 0; i < iNoOfExcelFile; i++)
                {
                    if (iNoOfExcelFile == 1)
                    {
                        strFileName = string.Format("WSLogINS_{0}.xlsx", strDateTimeFileName);
                    }
                    else
                    {
                        strFileName = string.Format("WSLogINS_{0}_{1}.xlsx", strDateTimeFileName, i + 1);
                    }

                    DataTable dt = dtExport.AsEnumerable().Select(x => x).Skip(i * iMaxRowPerFile).Take(iMaxRowPerFile).CopyToDataTable();

                    var report = new SLDocument(TemplateStream, "WSLOGINS");
                    report.InsertRow(2, dt.Rows.Count - 1);
                    report.ImportDataTable("A" + 2, dt, false);

                    ErrorStep = "Save WSLog file";
                    Console.WriteLine(ErrorStep);
                    using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
                    {
                        if (unc.NetUseWithCredentials(AppConstant.ExportWSLogPath, AppConstant.ExportWSLogUsername, AppConstant.ExportWSLogDomainName, AppConstant.ExportWSLogPassword))
                        {
                            report.SaveAs(string.Format("{0}{1}", AppConstant.ExportWSLogPath, strFileName));
                        }
                        else
                        {
                            ErrorDetail = string.Format("Cannot access path '{0}'", AppConstant.ExportWSLogPath);
                            Console.WriteLine(ErrorDetail);
                        }
                        unc.Dispose();
                    }

                    report.Dispose();
                    report = null;
                }
            }
            catch (Exception ex)
            {
                ErrorDetail = ex.ToString();
                Console.WriteLine(ErrorDetail);
            }
            finally
            {
                TemplateStream.Close();
                TemplateStream = null;
            }
        }
Beispiel #54
0
        protected void BuscarButton_Click(object sender, EventArgs e)
        {
            if (Funciones.SessionTimeOut(Session))
            {
                Response.Redirect("~/SessionTimeout.aspx");
            }
            else
            {
                try
                {
                    MensajeLabel.Text = "";
                    bool                         monedasExtranjeras = false;
                    Entidades.Sesion             sesion             = (Entidades.Sesion)Session["Sesion"];
                    List <Entidades.Comprobante> listaC             = new List <Entidades.Comprobante>();

                    List <Entidades.Estado> estados = new List <Entidades.Estado>();
                    Entidades.Estado        es      = new Entidades.Estado();
                    es.Id = "Vigente";
                    estados.Add(es);
                    Entidades.Persona persona          = new Entidades.Persona();
                    Entidades.NaturalezaComprobante nc = new Entidades.NaturalezaComprobante();
                    nc.Id  = "Venta";
                    listaC = RN.Comprobante.ListaFiltradaIvaYMovimientos(estados, FechaDesdeTextBox.Text, FechaHastaTextBox.Text, persona, nc, false, "", sesion);

                    Entidades.VentasXArticulo ventas = new Entidades.VentasXArticulo();

                    ventas.Cuit       = sesion.Cuit.Nro;
                    ventas.RazSoc     = sesion.Cuit.RazonSocial;
                    ventas.PeriodoDsd = FechaDesdeTextBox.Text.Substring(6, 2) + "/" + FechaDesdeTextBox.Text.Substring(4, 2) + "/" + FechaDesdeTextBox.Text.Substring(0, 4);
                    ventas.PeriodoHst = FechaHastaTextBox.Text.Substring(6, 2) + "/" + FechaHastaTextBox.Text.Substring(4, 2) + "/" + FechaHastaTextBox.Text.Substring(0, 4);

                    System.Xml.Serialization.XmlSerializer x;
                    byte[] bytes;
                    System.IO.MemoryStream ms;
                    FeaEntidades.InterFacturas.lote_comprobantes lote;

                    ventas.VentasXArticuloDetalle = new List <Entidades.VentasXArticuloDetalle>();
                    List <Entidades.VentasXArticuloDetalle> lvd = new List <Entidades.VentasXArticuloDetalle>();
                    Entidades.VentasXArticuloDetalle        vd;
                    foreach (Entidades.Comprobante comprobante in listaC)
                    {
                        lote = new FeaEntidades.InterFacturas.lote_comprobantes();
                        x    = new System.Xml.Serialization.XmlSerializer(lote.GetType());

                        comprobante.Response = comprobante.Response.Replace("iso-8859-1", "utf-16");
                        bytes = new byte[comprobante.Response.Length * sizeof(char)];
                        System.Buffer.BlockCopy(comprobante.Response.ToCharArray(), 0, bytes, 0, bytes.Length);
                        ms = new System.IO.MemoryStream(bytes);
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        lote = (FeaEntidades.InterFacturas.lote_comprobantes)x.Deserialize(ms);

                        //Totales por artículo
                        if (lote.comprobante[0].detalle.linea != null)
                        {
                            for (int z = 0; z < lote.comprobante[0].detalle.linea.Length; z++)
                            {
                                double signo = 1;
                                if (("/3/8/13/").IndexOf("/" + Convert.ToInt32(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante).ToString().Trim() + "/") != -1)
                                {
                                    signo = -1;
                                }

                                //Verificar el articulo ya existe en la lista.
                                //List<Entidades.VentasXArticuloDetalle> listaAux = lvd.FindAll(delegate(Entidades.VentasXArticuloDetalle vxad)
                                //{
                                //    return vxad.IdArticulo == lote.comprobante[0].detalle.linea[z].codigo_producto_vendedor;
                                //});
                                //if (listaAux.Count == 0 || lote.comprobante[0].detalle.linea[z].codigo_producto_vendedor.Trim() == "")
                                //{
                                //}
                                vd               = new Entidades.VentasXArticuloDetalle();
                                vd.IdArticulo    = lote.comprobante[0].detalle.linea[z].codigo_producto_vendedor;
                                vd.GTIN          = lote.comprobante[0].detalle.linea[z].GTIN.ToString();
                                vd.IdArticuloEmp = lote.comprobante[0].detalle.linea[z].codigo_producto_comprador;
                                if (lote.comprobante[0].detalle.linea[z].indicacion_exento_gravado != null)
                                {
                                    vd.IndicacionExentoGravado = lote.comprobante[0].detalle.linea[z].indicacion_exento_gravado;
                                }
                                else
                                {
                                    vd.IndicacionExentoGravado = "";
                                }
                                vd.NumeroLinea = lote.comprobante[0].detalle.linea[z].numeroLinea;
                                vd.UnidadCod   = lote.comprobante[0].detalle.linea[z].unidad;
                                vd.UnidadDescr = lote.comprobante[0].detalle.linea[z].unidadDescripcion;
                                vd.CompTipo    = lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante.ToString();
                                vd.CompNro     = lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante.ToString();
                                vd.CompPtoVta  = lote.comprobante[0].cabecera.informacion_comprobante.punto_de_venta.ToString();
                                vd.CompFecEmi  = lote.comprobante[0].cabecera.informacion_comprobante.fecha_emision.Substring(6, 2) + "/" + lote.comprobante[0].cabecera.informacion_comprobante.fecha_emision.Substring(4, 2) + "/" + lote.comprobante[0].cabecera.informacion_comprobante.fecha_emision.Substring(0, 4);

                                vd.EmpNroDoc   = lote.comprobante[0].cabecera.informacion_comprador.nro_doc_identificatorio.ToString();
                                vd.EmpCodDoc   = lote.comprobante[0].cabecera.informacion_comprador.codigo_doc_identificatorio.ToString();
                                vd.EmpDescrDoc = ""; //Obtener la descripcion;
                                vd.EmpNombre   = lote.comprobante[0].cabecera.informacion_comprador.denominacion;

                                if (lote.comprobante[0].detalle.linea[z].descripcion.Length > 0 && lote.comprobante[0].detalle.linea[z].descripcion.Substring(0, 1) == "%")
                                {
                                    vd.Descr = RN.Funciones.HexToString(lote.comprobante[0].detalle.linea[z].descripcion);
                                }
                                else
                                {
                                    vd.Descr = lote.comprobante[0].detalle.linea[z].descripcion;
                                }
                                vd.ImporteTotal = lote.comprobante[0].detalle.linea[z].importe_total_articulo * signo;
                                if (lote.comprobante[0].detalle.linea[z].cantidadSpecified == true && lote.comprobante[0].detalle.linea[z].precio_unitarioSpecified == true)
                                {
                                    vd.Cantidad       = lote.comprobante[0].detalle.linea[z].cantidad * signo;
                                    vd.PrecioUnitario = lote.comprobante[0].detalle.linea[z].precio_unitario * signo;
                                }
                                if (lote.comprobante[0].detalle.linea[z].alicuota_ivaSpecified == true && lote.comprobante[0].detalle.linea[z].importe_ivaSpecified == true)
                                {
                                    vd.AlicuotaIVA = lote.comprobante[0].detalle.linea[z].alicuota_iva;
                                    vd.ImporteIVA  = lote.comprobante[0].detalle.linea[z].importe_iva * signo;
                                }
                                lvd.Add(vd);
                            }
                        }
                    }
                    //Si se muestran artículos vigentes no vendidos.
                    List <Entidades.Articulo> listaArt = new List <Entidades.Articulo>();
                    if (VerTodosLosArticulosCheckBox.Enabled == true && VerTodosLosArticulosCheckBox.Checked == true)
                    {
                        listaArt = RN.Articulo.ListaPorCuit(true, false, sesion);
                        if (listaArt.Count != 0)
                        {
                            foreach (Entidades.Articulo art in listaArt)
                            {
                                bool existeArt = false;
                                if (lvd.Count != 0)
                                {
                                    System.Collections.Generic.List <Entidades.VentasXArticuloDetalle> listaVXArt = lvd.FindAll(delegate(Entidades.VentasXArticuloDetalle vxart)
                                    {
                                        return(vxart.IdArticulo == art.Id);
                                    });
                                    if (listaVXArt.Count != 0)
                                    {
                                        existeArt = true;
                                    }
                                }
                                if (!existeArt)
                                {
                                    vd                         = new Entidades.VentasXArticuloDetalle();
                                    vd.IdArticulo              = art.Id;
                                    vd.Descr                   = art.Descr;
                                    vd.CompFecEmi              = "";
                                    vd.CompNro                 = "";
                                    vd.CompPtoVta              = "";
                                    vd.CompTipo                = "";
                                    vd.UnidadCod               = "";
                                    vd.UnidadDescr             = "";
                                    vd.IndicacionExentoGravado = "";
                                    vd.EmpNroDoc               = "";
                                    vd.EmpCodDoc               = "";
                                    vd.EmpDescrDoc             = "";
                                    vd.EmpNombre               = "";
                                    lvd.Add(vd);
                                }
                            }
                        }
                    }
                    if (lvd.Count != 0)
                    {
                        ventas.VentasXArticuloDetalle = lvd;
                    }
                    Session["formatoRptExportar"]         = FormatosRptExportarDropDownList.SelectedValue;
                    Session["mostrarFechaYHora"]          = FechaYHoraCheckBox.Checked;
                    Session["mostrarDetalleComprobantes"] = DetalleComprobanteCheckBox.Checked;
                    Session["monedasExtranjeras"]         = monedasExtranjeras;
                    if (ventas.VentasXArticuloDetalle.Count != 0)
                    {
                        Session["ventasXArticulo"] = ventas;
                        Response.Redirect("~/Facturacion/Electronica/Reportes/VentasXArticuloWebForm.aspx", true);
                    }
                    else
                    {
                        MensajeLabel.Text = "No hay información.";
                    }
                }
                catch (System.Threading.ThreadAbortException)
                {
                    Trace.Warn("Thread abortado");
                }
                catch (Exception ex)
                {
                    WebForms.Excepciones.Redireccionar(ex, "~/NotificacionDeExcepcion.aspx");
                }
            }
        }
Beispiel #55
0
        public FileResult Excel(CheckAnalyze model)
        {
            string strErrMsg = string.Empty;
            List <CheckAnalyze> lstExport = new List <CheckAnalyze>();
            string    strError            = "";
            DividPage page = new DividPage
            {
                CurrentPageShowCounts = 10000000
            };

            tfun.GetCheckAnalyze(model, ref page, ref lstExport, ref strError);

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("盈亏情况");
            row1.CreateCell(1).SetCellValue("实盘据点");
            row1.CreateCell(2).SetCellValue("实盘物料号");
            row1.CreateCell(3).SetCellValue("实盘物料描述");
            row1.CreateCell(4).SetCellValue("实盘库位");
            row1.CreateCell(5).SetCellValue("实盘序列号");
            row1.CreateCell(6).SetCellValue("实盘数量");
            row1.CreateCell(7).SetCellValue("库存数量");
            row1.CreateCell(8).SetCellValue("库存序列号");
            row1.CreateCell(9).SetCellValue("库存库位");
            row1.CreateCell(10).SetCellValue("库存物料号");
            row1.CreateCell(11).SetCellValue("库存物料描述");
            row1.CreateCell(12).SetCellValue("库存据点");
            row1.CreateCell(13).SetCellValue("盘盈数量");
            row1.CreateCell(14).SetCellValue("盘亏数量");
            row1.CreateCell(15).SetCellValue("操作人");

            //将数据逐步写入seet1各个行
            for (int i = 0; i < lstExport.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);

                rowtemp.CreateCell(0).SetCellValue(lstExport[i].remark == null ? "" : lstExport[i].remark.ToString());
                rowtemp.CreateCell(1).SetCellValue(lstExport[i].STRONGHOLDCODE == null ? "" : lstExport[i].STRONGHOLDCODE.ToString());
                rowtemp.CreateCell(2).SetCellValue(lstExport[i].MATERIALNO == null ? "" : lstExport[i].MATERIALNO.ToString());
                rowtemp.CreateCell(3).SetCellValue(lstExport[i].MATERIALDESC == null ? "" : lstExport[i].MATERIALDESC.ToString());
                rowtemp.CreateCell(4).SetCellValue(lstExport[i].AREANO == null ? "" : lstExport[i].AREANO.ToString());
                rowtemp.CreateCell(5).SetCellValue(lstExport[i].SERIALNO == null ? "" : lstExport[i].SERIALNO.ToString());
                rowtemp.CreateCell(6).SetCellValue(lstExport[i].QTY == null ? "" : lstExport[i].QTY.ToString());
                rowtemp.CreateCell(7).SetCellValue(lstExport[i].SQTY == null ? "" : lstExport[i].SQTY.ToString());
                rowtemp.CreateCell(8).SetCellValue(lstExport[i].SSERIALNO.ToString());
                rowtemp.CreateCell(9).SetCellValue(lstExport[i].SAREANO.ToString());
                rowtemp.CreateCell(10).SetCellValue(lstExport[i].SMATERIALNO == null ? "" : lstExport[i].SMATERIALNO.ToString());
                rowtemp.CreateCell(11).SetCellValue(lstExport[i].SMATERIALDESC == null ? "" : lstExport[i].SMATERIALDESC.ToString());
                rowtemp.CreateCell(12).SetCellValue(lstExport[i].SSTRONGHOLDCODE == null ? "" : lstExport[i].SSTRONGHOLDCODE.ToString());
                rowtemp.CreateCell(13).SetCellValue(lstExport[i].YQTY == null ? "" : lstExport[i].YQTY.ToString());
                rowtemp.CreateCell(14).SetCellValue(lstExport[i].KQTY == null ? "" : lstExport[i].KQTY.ToString());
                rowtemp.CreateCell(15).SetCellValue(lstExport[i].Creater == null ? "" : lstExport[i].Creater.ToString());
            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return(File(ms, "application/vnd.ms-excel", DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"));
        }
Beispiel #56
0
        public FileResult ExportAll()
        {
            List <SkuData> list = new List <SkuData>();

            try
            {
                Hashtable  param = new Hashtable();
                BaseResult br    = new BaseResult();
                param.Add("id_gys", GetLoginInfo <long>("id_supplier"));
                list = BusinessFactory.Goods.GetExportAll(param);
                HSSFWorkbook             book    = new HSSFWorkbook();
                Dictionary <string, int> e_param = new Dictionary <string, int> {
                    { "序号", 12 },
                    { "类别", 18 },
                    { "SKU编码", 18 },
                    { "商品编码", 18 },
                    { "商品名称", 18 },
                    { "规格", 30 },
                    { "库存", 18 },
                    { "预警数量", 18 },
                    { "单位", 18 }
                };
                ISheet     sheet1 = NPOIHelper.CreateSheet(book, e_param, "商品库存");
                ICellStyle lstyle = book.CreateCellStyle();
                lstyle.Alignment         = HorizontalAlignment.Left;
                lstyle.VerticalAlignment = VerticalAlignment.Center;
                lstyle.IsLocked          = true;

                ICellStyle rstyle = book.CreateCellStyle();
                rstyle.Alignment         = HorizontalAlignment.Right;
                rstyle.VerticalAlignment = VerticalAlignment.Center;

                ICellStyle locked = book.CreateCellStyle();
                locked.IsLocked = true;
                for (int i = 0; i < list.Count; i++)
                {
                    IRow rowtemp = sheet1.CreateRow(i + 1);
                    rowtemp.CreateCell(0).SetCellValue(i + 1);
                    rowtemp.GetCell(0).CellStyle = rstyle;
                    rowtemp.CreateCell(1).SetCellValue(list[i].name_fl);
                    rowtemp.GetCell(1).CellStyle = lstyle;
                    rowtemp.CreateCell(2).SetCellValue(list[i].id.ToString());
                    rowtemp.GetCell(2).CellStyle.IsLocked = true;
                    rowtemp.CreateCell(3).SetCellValue(list[i].bm);
                    rowtemp.GetCell(3).CellStyle.IsLocked = true;
                    rowtemp.CreateCell(4).SetCellValue(list[i].name_sp);
                    rowtemp.GetCell(4).CellStyle = lstyle;
                    rowtemp.CreateCell(5).SetCellValue(list[i].name_spec_zh);
                    rowtemp.CreateCell(6).SetCellValue(Decimal.Round((decimal)list[i].sl_kc, 2).ToString());
                    rowtemp.GetCell(6).CellStyle = rstyle;
                    rowtemp.CreateCell(7).SetCellValue(Decimal.Round((decimal)list[i].sl_kc_bj, 2).ToString());
                    rowtemp.GetCell(7).CellStyle = rstyle;
                    rowtemp.CreateCell(8).SetCellValue(list[i].unit);
                    sheet1.GetRow(i + 1).Height = 16 * 20;
                }

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                book.Write(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return(File(ms, "application/vnd.ms-excel", "商品库存_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"));
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #57
0
 /// <summary>
 /// 导出考勤的Excel
 /// </summary>
 /// <param name="UnitID"></param>
 /// <param name="date"></param>
 /// <returns></returns>
 public ActionResult AttendExcel(string UnitID, string date)
 {
     System.IO.MemoryStream ms = operateContext.bllSession.View_A02.GetAttendBook(UnitID, date);
     ms.Seek(0, SeekOrigin.Begin);
     return File(ms, "application/vnd.ms-excel", "考勤信息.xls");
 }
Beispiel #58
0
        /// <summary>
        /// Calls method IdeaRS.ConnectionLink.ConnectionLink.OpenIdeaConnection to run Idea Connection
        /// </summary>
        /// <param name="iomFilename">IOM filename - includes geometry of the connection (connected members)</param>
        /// <param name="templateFileName">Idea connection template or connection project file name</param>
        /// <param name="isHiddenCalculation">Set true to run hidden calculation </param>
        public void OpenIOMInIdeaCon(string iomFilename, string templateFileName, bool isHiddenCalculation)
        {
            FileStream fs  = new FileStream(iomFilename, FileMode.Open, FileAccess.Read);
            FileStream fsr = null;

            string filenameRes = iomFilename + "R";

            if (System.IO.File.Exists(filenameRes))
            {
                fsr = new FileStream(filenameRes, FileMode.Open, FileAccess.Read);
            }

            FileStream   connTemplateStream   = null;
            FileStream   connProjectStream    = null;
            MemoryStream importSettingsStream = null;

            if (!string.IsNullOrEmpty(templateFileName) && File.Exists(templateFileName))
            {
                string fileExt      = System.IO.Path.GetExtension(templateFileName);
                bool   isConProject = fileExt.Equals(".ideacon", StringComparison.InvariantCultureIgnoreCase);

                if (isConProject)
                {
                    connProjectStream = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
                }
                else
                {
                    connTemplateStream = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
                }
            }
            string importSettingsText = string.Empty;

            importSettingsText += "<?xml version=\"1.0\"?>";
            importSettingsText += "<IdeaConImportSettings>";
            importSettingsText += "<UseWizard>true</UseWizard>";
            importSettingsText += "<OnePageWizard>true</OnePageWizard>";
            importSettingsText += "<DefaultBoltAssembly>M12 4.6</DefaultBoltAssembly>";
            importSettingsText += "</IdeaConImportSettings>";

            if (!string.IsNullOrEmpty(importSettingsText))
            {
                importSettingsStream = new System.IO.MemoryStream();
                var encoding = new System.Text.UTF8Encoding();
                importSettingsStream.Write(encoding.GetBytes(importSettingsText), 0, importSettingsText.Length);
                importSettingsStream.Flush();
                importSettingsStream.Seek(0, SeekOrigin.Begin);
            }

            if (LinkAssembly != null)
            {
                if (!isHiddenCalculation)
                {
                    LinkAssembly.OpenIdeaConnection(fs, fsr, connProjectStream, connTemplateStream, importSettingsStream, true);
                }
                else
                {
                    LinkAssembly.RunHiddenAnalysis(fs, fsr, connProjectStream, connTemplateStream, importSettingsStream, true);
                    if (!LinkAssembly.IsProjectCalculated())
                    {
                        //this.resultBrowser.NavigateToString("Results doesn't exist");
                        return;
                    }

                    string conCheckResFilename = LinkAssembly.GetCheckResultsFilename();
                    //this.resultBrowser.Navigate(conCheckResFilename);
                }

                //OnProjOpened();
            }
        }
Beispiel #59
0
        private void ReorganiseDirectory(String diskName, String filenameToDelete)
        {
            Byte directoryTrack  = 20;
            Byte directorySector = 4;
            Byte directoryIndex  = 0;

            Byte prevDirTrack  = directoryTrack;
            Byte prevDirSector = directorySector;

            int directoryCount = 0;

            Byte[] directory = new Byte[256];

            for (int index = 0; index < directory.Length; index++)
            {
                directory[index] = 0x00;
            }

            MemoryStream memStream = new System.IO.MemoryStream(directory, 0, directory.Length);
            BinaryWriter bw        = new System.IO.BinaryWriter(memStream);

            memStream.Seek(0x10, SeekOrigin.Begin);

            // Read entire directory
            OricFileInfo[] diskDirectory = ReadDirectory(diskName);

            foreach (OricFileInfo fileInfo in diskDirectory)
            {
                if (!fileInfo.ProgramName.Equals(filenameToDelete))
                {
                    String filename = fileInfo.ProgramName;
                    filename = Path.GetFileNameWithoutExtension(filename);
                    filename = filename.PadRight(9, ' ');

                    bw.Write(filename.ToCharArray());

                    String extension = fileInfo.Extension.PadRight(3, ' ');
                    bw.Write(extension.ToCharArray());

                    bw.Write(fileInfo.FirstTrack);
                    bw.Write(fileInfo.FirstSector);
                    bw.Write((Byte)fileInfo.LengthSectors);

                    if (fileInfo.Protection == OricProgram.ProtectionStatus.Protected)
                    {
                        bw.Write((Byte)0xC0);
                    }
                    else if (fileInfo.Protection == OricProgram.ProtectionStatus.Unprotected)
                    {
                        bw.Write((Byte)0x40);
                    }
                    else
                    {
                        bw.Write((Byte)0x00);
                    }

                    directoryIndex++;

                    if (directoryIndex == 15)
                    {
                        prevDirTrack  = directoryTrack;
                        prevDirSector = directorySector;

                        directoryCount++;

                        // Directory is full, setup details of next directory
                        switch (directoryCount)
                        {
                        case 1: directorySector = 7; break;

                        case 2: directorySector = 10; break;

                        case 3: directorySector = 13; break;

                        case 4: directorySector = 16; break;

                        default:
                            // Find next free sector and use that
                            break;
                        }

                        bw.Seek(0x00, SeekOrigin.Begin);
                        bw.Write(directoryTrack);
                        bw.Write(directorySector);

                        // Write value to indicate directory is full
                        bw.Write((Byte)0x00);

                        base.WriteSector(prevDirTrack, prevDirSector, directory);

                        for (int index = 0; index < directory.Length; index++)
                        {
                            directory[index] = 0x00;
                        }

                        directoryIndex = 0;

                        memStream.Seek(0x10, SeekOrigin.Begin);
                    }
                }
            }

            if (directoryIndex > 0)
            {
                bw.Seek(0x02, SeekOrigin.Begin);

                Byte nextFreeSlot = (Byte)((directoryIndex + 1) * 16);
                bw.Write((Byte)nextFreeSlot);

                base.WriteSector(directoryTrack, directorySector, directory);
            }

            base.WriteDisk();
        }
Beispiel #60
-1
        public void Test_ReadLine()
        {
            const string raw = "line1\r\nline2\nline3";
            var stream = new MemoryStream(Encoding.ASCII.GetBytes(raw));

            var line = stream.ReadLine();
            Assert.AreEqual("line1", line);
            Assert.AreEqual(7, stream.Position);

            line = stream.ReadLine();
            Assert.AreEqual("line2", line);
            Assert.AreEqual(13, stream.Position);

            line = stream.ReadLine();
            Assert.AreEqual("line3", line);
            Assert.AreEqual(18, stream.Position);

            stream.Seek(2, SeekOrigin.Begin);
            line = stream.ReadLine();
            Assert.AreEqual("ne1", line);
            Assert.AreEqual(7, stream.Position);

            stream.Seek(9, SeekOrigin.Begin);
            line = stream.ReadLine();
            Assert.AreEqual("ne2", line);
            Assert.AreEqual(13, stream.Position);

            stream.Dispose();
        }