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

public ToArray ( ) : byte[]
Результат byte[]
Пример #1
1
        public override byte[] GetEncoding()
        {
            try
            {
                MemoryStream outputStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));

                MessagesEncodingUtil.WriteMessageType(binaryWriter, this);

                if (PeerAddress.PrivateEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PrivateEndPoint.ToString());

                if (PeerAddress.PublicEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PublicEndPoint.ToString());

                binaryWriter.Flush();

                byte[] buffer = outputStream.ToArray();

                if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
                    return outputStream.ToArray();
                else
                    throw new BinaryEncodingException();
            }
            catch (Exception)
            {
                throw new BinaryEncodingException("Decode");
            }
        }
Пример #2
1
        public byte[] Encrypt(byte[] block)
        {
            ICryptoTransform enc = null;
            Aes.Mode = CipherMode.CBC;
            Aes.Key = key;
            Aes.GenerateIV();
            Console.WriteLine("Key: {0} IV: {1}", CNetwork.ByteArrayToString(Aes.Key), CNetwork.ByteArrayToString(Aes.IV));

            CryptoStream cstream = null;
            MemoryStream mem = null;
            byte[] toEncrypt = null;

            try
            {
                cstream = null;
                mem = new MemoryStream();
                toEncrypt = block;
                enc = Aes.CreateEncryptor();
                cstream = new CryptoStream(mem, enc, CryptoStreamMode.Write);
                cstream.Write(toEncrypt, 0, toEncrypt.Length);
            }
            finally
            {
                if (cstream != null)
                    Aes.Clear();
                cstream.Close();
            }

            Console.WriteLine(CNetwork.ByteArrayToString(mem.ToArray()));

            return mem.ToArray();
        }
		public static byte[] nextToken(Stream input, byte[] delimiter)
		{
			int nextByte;

			//If the stream has already ended, return null
			if ((nextByte = input.ReadByte()) == -1)
				return null;

			MemoryStream tokenBuffer = new MemoryStream();
			do
			{
				tokenBuffer.WriteByte((byte)nextByte);
				byte[] currentToken = tokenBuffer.ToArray();
				if (endsWith(currentToken, delimiter))
				{
					int tokenLength = currentToken.Length - delimiter.Length;
					byte[] token = new byte[tokenLength];
					Array.Copy(currentToken, 0, token, 0, tokenLength);

					return token;
				}
			}
			while ((nextByte = input.ReadByte()) != -1);

			return tokenBuffer.ToArray();
		}
        public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
        {
            using (var memoryBuffer = new MemoryStream(1024))
            using (var streamWriter = new StreamWriter(memoryBuffer, utf8Encoding))
            {
                WriteQuery(new JsonWriter(streamWriter), query);
                streamWriter.Flush();

                var data = memoryBuffer.ToArray();
                memoryBuffer.Seek(0, SeekOrigin.Begin);

                if (logger.InformationEnabled())
                {
                    string dataStr = Encoding.UTF8.GetString(data);
                    logger.Information("JSON query: {0}", dataStr);
                }

                var tokenHeader = BitConverter.GetBytes(query.token);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(tokenHeader, 0, tokenHeader.Length);
                memoryBuffer.Write(tokenHeader, 0, tokenHeader.Length);

                var lengthHeader = BitConverter.GetBytes(data.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(lengthHeader, 0, lengthHeader.Length);
                memoryBuffer.Write(lengthHeader, 0, lengthHeader.Length);

                memoryBuffer.Write(data, 0, data.Length);

                logger.Debug("Writing packet, {0} bytes", data.Length);
                data = memoryBuffer.ToArray();
                await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
        }
        public void Download(byte[] data, int bufferSize, DownloadSegmentPositions[] segmentPositionInfos)
        {
            BeforeDownload();

            DownloadStream inputStream = new DownloadStream(data);

            IList<ISegmentDownloadTask> segmentDownloadTasks = new List<ISegmentDownloadTask>(segmentPositionInfos.Length);
            IList<DownloadStream> downloadStreams = new List<DownloadStream>(segmentPositionInfos.Length);
            MemoryStream outputStream = new MemoryStream();
            for (int i = 0; i < segmentPositionInfos.Length; i++)
            {
                DownloadSegmentPositions segmentPosition = segmentPositionInfos[i];
                byte[] dataPart = data.Skip((int) segmentPosition.StartPosition).Take((int)(segmentPosition.EndPosition - segmentPosition.StartPosition + 1)).ToArray();
                DownloadStream downloadStream = new DownloadStream(dataPart);
                segmentDownloadTasks.Add(CreateSegmentDownloadTask(bufferSize, CreateSegmentDownloader(downloadStream, segmentPosition), CreateSegmentWriter(outputStream)));
                downloadStreams.Add(downloadStream);
            }

            SegmentDownloadManager segmentDownloadManager = new SegmentDownloadManager(new SegmentDownloadTaskCollection(segmentDownloadTasks));
            segmentDownloadManager.Start();
            segmentDownloadManager.Finish(true);

            AfterDownload();

            long totalDownloads = downloadStreams.Sum(x => x.TotalDownloads);
            Assert.AreEqual(data.Length, totalDownloads);
            Assert.AreEqual(inputStream.ToArray().Take(data.Length).ToArray(), outputStream.ToArray().Take(data.Length).ToArray());
            Assert.AreEqual(inputStream.ToArray(), outputStream.ToArray());
        }
Пример #6
0
        public static String hashAndEncode(byte[] password, int hashalg, byte[] salt, int icount, byte[] challenge)
        {
            byte[] hash;
            if (hashalg == 0)
            {
                hash = sha1(password);
            }
            else
            {
                hash = HashPasswordV2(hashalg, salt, icount, password);
            }

            if (challenge.Length > 0)
            {
                var ms = new MemoryStream();
                ms.Write(challenge, 0, challenge.Length);
                ms.Write(hash, 0, hash.Length);

                if (hashalg == 0)
                    hash = sha1(ms.ToArray());
                else
                {
                    hash = HashPasswordV2(hashalg, salt, icount, ms.ToArray());
                }
            }
            return hexEncode(hash);
        }
Пример #7
0
        public void ExtractSnippet(string fileName, string pattern, string expectedFile)
        {
            // Run the extraction
            ISnippetExtractor snippetExtractor;
            if (!this.extractorCache.TryGetValue(fileName, out snippetExtractor))
            {
                snippetExtractor = new XmlSnippetExtractor(this.SourceDirectories);
                this.extractorCache[fileName] = snippetExtractor;
            }
            Projbook.Core.Model.Snippet snippet = snippetExtractor.Extract(fileName, pattern);

            // Load the expected file content
            MemoryStream memoryStream = new MemoryStream();
            using (var fileReader = new StreamReader(new FileStream(Path.GetFullPath(Path.Combine("Resources", "Expected", expectedFile)), FileMode.Open)))
            using (var fileWriter = new StreamWriter(memoryStream))
            {
                fileWriter.Write(fileReader.ReadToEnd());
            }

            Console.WriteLine(System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()).Replace("\r\n", Environment.NewLine));
            Console.WriteLine(snippet.Content.Replace("\r\n", Environment.NewLine));

            // Assert
            Assert.AreEqual(
                System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()).Replace("\r\n", Environment.NewLine),
                snippet.Content.Replace("\r\n", Environment.NewLine));
        }
Пример #8
0
        public static IObservable<byte[]> MinimumBuffer(this IObservable<byte[]> input, int minimumBufSize)
        {
            return Observable.Create<byte[]>(observer =>
            {
                MemoryStream memStream = new MemoryStream();

                return input.Subscribe(
                    bytes =>
                    {
                        memStream.Write(bytes, 0, bytes.Length);
                        if (memStream.Length >= minimumBufSize)
                        {
                            Debug.Assert(memStream.Position == memStream.Length);
                            observer.OnNext(memStream.ToArray());

                            memStream.SetLength(0);// truncate the stream
                            memStream.Position = 0;
                        }
                    },
                    observer.OnError,
                    () =>
                    {
                        if (memStream.Length > 0)
                            observer.OnNext(memStream.ToArray());
                        observer.OnCompleted();
                    }
                    );
            });
        }
Пример #9
0
        public static async Task<Stream> CompressAsync(CompressionType type, Stream original)
        {            
            using (var ms = new MemoryStream())
            {
                Stream compressedStream = null;

                if (type == CompressionType.deflate)
                {
                    compressedStream = new DeflateStream(ms, CompressionMode.Compress);
                }
                else if (type == CompressionType.gzip)
                {
                    compressedStream = new GZipStream(ms, CompressionMode.Compress);
                }

                if (type != CompressionType.none)
                {
                    using (compressedStream)
                    {
                        await original.CopyToAsync(compressedStream);
                    }

                    //NOTE: If we just try to return the ms instance, it will simply not work
                    // a new stream needs to be returned that contains the compressed bytes.
                    // I've tried every combo and this appears to be the only thing that works.

                    byte[] output = ms.ToArray();
                    return new MemoryStream(ms.ToArray());
                }

                //not compressed
                return original;
            }
        }
Пример #10
0
        /// <summary>
        /// Convert the Webstreamlogo (Online or Default) to byte[]
        /// </summary>
        public static byte[] ImageFromLogo(string path)
        {
            var ms = new MemoryStream();

              try
              {
            var imageRequest = (HttpWebRequest)WebRequest.Create(path);
            imageRequest.Credentials = CredentialCache.DefaultCredentials;
            using (var imageReponse = (HttpWebResponse)imageRequest.GetResponse())
            {
              using (var imageStream = imageReponse.GetResponseStream())
              {
            if (imageStream != null) Image.FromStream(imageStream).Save(ms, ImageFormat.Png);
              }
            }
              }
              catch (Exception)
              {
            var s = ServiceRegistration.Get<IPathManager>().GetPath(@"<PLUGINS>\Webradio\Skin\default\images\DefaultLogo.png");
            Image.FromFile(s).Save(ms, ImageFormat.Png);
            return ms.ToArray();
            throw;
              }
              return ms.ToArray();
        }
Пример #11
0
        public void ServerPackageRepositoryReadsDerivedData()
        {
            // Arrange
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            var package = new PackageBuilder() { Id = "Test", Version = new System.Version("1.0"), Description = "Description" };
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo");
            mockFile.Setup(m => m.GetStream()).Returns(new MemoryStream());
            package.Files.Add(mockFile.Object);
            package.Authors.Add("Test Author");
            var memoryStream = new MemoryStream();
            package.Save(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            mockProjectSystem.Object.AddFile("foo.nupkg");
            mockProjectSystem.Setup(c => c.OpenFile(It.IsAny<string>())).Returns(() => new MemoryStream(memoryStream.ToArray()));
            var serverRepository = new ServerPackageRepository(new DefaultPackagePathResolver(mockProjectSystem.Object), mockProjectSystem.Object);
            serverRepository.HashProvider = GetHashProvider();

            // Act
            var packages = serverRepository.GetPackagesWithDerivedData();

            // Assert
            byte[] data = memoryStream.ToArray();
            Assert.AreEqual(data.Length, packages.Single().PackageSize);
            CollectionAssert.AreEquivalent(data.Select(Invert).ToArray(), Convert.FromBase64String(packages.Single().PackageHash));
            Assert.AreEqual(data.Length, packages.Single().PackageSize);
        }
Пример #12
0
 public void Run()
 {
   var registerer = new MessageRegisterer();
   registerer.AddMessageTypes(typeof(IPerformSingleTaskOnComputersMessage), typeof(IInstallAssemblyMessage));
   var implementations = new MessageInterfaceImplementations(new DefaultMessageInterfaceImplementationFactory(), registerer);
   var factory = new MessageFactory(implementations, new MessageDefinitionFactory());
   var assembly = factory.Create<IInstallAssemblyMessage>(m =>
   {
     m.ArtifactId = Guid.Empty;
     m.AssemblyFilename = "Jacob.exe";
   });
   var message = factory.Create<IPerformSingleTaskOnComputersMessage>(m =>
   {
     m.OperationId = Guid.NewGuid();
     m.Title = "Nothing";
     m.Message = assembly;
     m.ComputerNames = new string[0];
     m.Birthday = DateTime.UtcNow;
   });
   var formatter = new XmlTransportMessageBodyFormatter(registerer, new MtaMessageMapper(implementations, factory, registerer));
   formatter.Initialize();
   using (var stream = new MemoryStream())
   {
     formatter.Serialize(new IMessage[] { message }, stream);
     Console.WriteLine(Encoding.ASCII.GetString(stream.ToArray()));
     using (var reading = new MemoryStream(stream.ToArray()))
     {
       var read = formatter.Deserialize(reading);
     }
   }
 }
		private static void TestByte( Byte value )
		{
			var output = new MemoryStream();
			Packer.Create( output ).Pack( value );
			Assert.AreEqual( value, Unpacking.UnpackByte( new MemoryStream( output.ToArray() ) ) );
			Assert.AreEqual( value, Unpacking.UnpackByte( output.ToArray() ).Value );
		}
        /// <summary>
        /// Send information about this CityServer to the LoginServer...
        /// </summary>
        /// <param name="Client">The client connected to the LoginServer.</param>
        public static void SendServerInfo(NetworkClient Client)
        {
            PacketStream Packet = new PacketStream(0x64, 0);
            Packet.WriteByte(0x64);

            MemoryStream PacketBody = new MemoryStream();
            BinaryWriter PacketWriter = new BinaryWriter(PacketBody);

            PacketWriter.Write((string)GlobalSettings.Default.CityName);
            PacketWriter.Write((string)GlobalSettings.Default.CityDescription);
            PacketWriter.Write((string)Settings.BINDING.Address.ToString());
            PacketWriter.Write((int)Settings.BINDING.Port);
            PacketWriter.Write((byte)1); //CityInfoStatus.OK
            PacketWriter.Write((ulong)GlobalSettings.Default.CityThumbnail);
            PacketWriter.Write((string)GlobalSettings.Default.ServerID);
            PacketWriter.Write((ulong)GlobalSettings.Default.Map);
            PacketWriter.Flush();

            Packet.WriteUInt16((ushort)(PacketBody.ToArray().Length + PacketHeaders.UNENCRYPTED));

            Packet.Write(PacketBody.ToArray(), 0, (int)PacketWriter.BaseStream.Length);
            Packet.Flush();

            PacketWriter.Close();

            Client.Send(Packet.ToArray());
        }
        public void NewToOld()
        {
            var oldSub = new Subscription("the message", new Uri("http://bob/phil"));
            IList<Subscription> oldSubs = new List<Subscription>();
            oldSubs.Add(oldSub);

            using (var newStream = new MemoryStream())
            {
                NewWriter.Serialize(newStream, oldSubs);

                newStream.Position = 0;

                using (var oldStream = new MemoryStream())
                {
                    using (var str = File.OpenRead(_pathToFile))
                    {
                        var buff = new byte[str.Length];
                        str.Read(buff, 0, buff.Length);
                        oldStream.Write(buff, 0, buff.Length);
                    }

                    if (File.Exists(".\\my_msg_2.txt")) File.Delete(".\\my_msg_2.txt");
                    using (var fs = File.OpenWrite(".\\my_msg_2.txt"))
                    {
                        fs.Write(newStream.ToArray(), 0, newStream.ToArray().Length);
                    }

                    StreamAssert.AreEqual(oldStream, newStream);
                }
            }
        }
Пример #16
0
        public override byte[] GetEncoding()
        {
            try
            {
                MemoryStream outputStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));

                MessagesEncodingUtil.WriteMessageType(binaryWriter, this);
                MessagesEncodingUtil.WriteInt(binaryWriter, ByteArray.Length);
                MessagesEncodingUtil.WriteByteArray(binaryWriter, ByteArray);

                binaryWriter.Flush();

                byte[] buffer = outputStream.ToArray();

                if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
                    return outputStream.ToArray();
                else
                    throw new BinaryEncodingException();
            }
            catch (Exception)
            {
                throw new BinaryEncodingException("Decode");
            }
        }
Пример #17
0
        public void We_should_go_through_the_list_quickly()
        {
            DerivedObject obj = new DerivedObject("Chris", "Patterson", "Pimp");
            DerivedObject obj2 = new DerivedObject("Joe", "Blow", "Daddy");

            //IObjectFormatter fomatter = new XmlObjectFormatter();

            MemoryStream mstream = new MemoryStream();

            using(IObjectFormatter formatter = new BEncodeObjectFormatter(mstream))
            using(IObjectSerializer serializer = new BasicObjectSerializer(formatter))
            {
                serializer.Serialize(formatter, obj);
                serializer.Serialize(formatter, obj2);
            }

            Debug.WriteLine("DATA: " + Encoding.UTF8.GetString(mstream.ToArray()));

            MemoryStream mdecode = new MemoryStream(mstream.ToArray());

            using(BDecode decoder = new BDecode(mdecode))
            {
                object newObj = decoder.Read(TimeSpan.FromSeconds(200));

                Assert.That(newObj, Is.Not.Null);
                Assert.That(newObj, Is.TypeOf(typeof(DerivedObject)), "Invalid Type Received");

                object newObj2 = decoder.Read(TimeSpan.FromSeconds(200));

                Assert.That(newObj2, Is.Not.Null);
                Assert.That(newObj2, Is.TypeOf(typeof(DerivedObject)), "Invalid Type Received");

            }
        }
        public void NewToOld()
        {
            var oldMsg = new OldCacheUpdateRequest(new Uri("http://bob/phil"));
            var oldold = Factory.ConvertToOldCacheUpdateRequest(oldMsg);
            using (var newStream = new MemoryStream())
            {
                PlainFormatter.Serialize(newStream, oldold);

                newStream.Position = 0;

                using (var oldStream = new MemoryStream())
                {
                    using (var str = File.OpenRead(_pathToFile))
                    {
                        var buff = new byte[str.Length];
                        str.Read(buff, 0, buff.Length);
                        oldStream.Write(buff, 0, buff.Length);
                    }

                    var newFileName = ".\\new-{0}.txt".FormatWith(oldMsg.GetType().Name);
                    if (File.Exists(newFileName)) File.Delete(newFileName);
                    using (var fs = File.OpenWrite(newFileName))
                    {
                        fs.Write(newStream.ToArray(), 0, newStream.ToArray().Length);
                    }

                    StreamAssert.AreEqual(oldStream, newStream);
                }
            }
        }
Пример #19
0
        public static SteamPacket CreatePacket(byte[] rawData)
        {
            SteamPacket packet;
            SteamPacketTypes packetType = (SteamPacketTypes)rawData[0];

            MemoryStream byteStream = new MemoryStream(rawData.Length - 1);
            byteStream.Write(rawData, 1, rawData.Length - 1);

            switch(packetType)
            {
                case SteamPacketTypes.S2C_CHALLENGE:
                    packet = new ChallengeResponsePacket(byteStream.ToArray());
                    break;

                case SteamPacketTypes.S2A_INFO2:
                    packet = new SourceServerInfoResponsePacket(byteStream.ToArray());
                    break;

                case SteamPacketTypes.S2A_RULES:
                    packet = new ServerRulesResponsePacket(byteStream.ToArray());
                    break;

                case SteamPacketTypes.S2A_PLAYER:
                    packet = new PlayersResponsePacket(byteStream.ToArray());
                    break;

                default:
                    packet = new SteamPacket(packetType, byteStream.ToArray());
                    break;
            }

            return packet;
        }
Пример #20
0
        public string DecryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            Byte[] byt = new byte[64];
            try
            {
                ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

                byt = Convert.FromBase64String(Value);

                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();

                cs.Close();
                string test = Encoding.UTF8.GetString(ms.ToArray());
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw (new Exception("An error occurred while decrypting string", ex));
            }
        }
Пример #21
0
// ---------------------------------------------------------------------------    
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        // Use previous examples to create PDF files
        MovieLinks1 m = new MovieLinks1(); 
        byte[] pdfM = Utility.PdfBytes(m);
        LinkActions l = new LinkActions();
        byte[] pdfL = l.CreatePdf();
        // Create readers.
        PdfReader[] readers = {
          new PdfReader(pdfL),
          new PdfReader(pdfM)
        };
        
        // step 1
        //Document document = new Document();
        // step 2
        using (var ms = new MemoryStream()) { 
          // step 1
          using (Document document = new Document()) {
            using (PdfCopy copy = new PdfCopy(document, ms)) {
              // step 3
              document.Open();
              // step 4
              int n;
              // copy the pages of the different PDFs into one document
              for (int i = 0; i < readers.Length; i++) {
                readers[i].ConsolidateNamedDestinations();
                n = readers[i].NumberOfPages;
                for (int page = 0; page < n; ) {
                  copy.AddPage(copy.GetImportedPage(readers[i], ++page));
                }
              }
              // Add named destination  
              copy.AddNamedDestinations(
                // from the second document
                SimpleNamedDestination.GetNamedDestination(readers[1], false),
                // using the page count of the first document as offset
                readers[0].NumberOfPages
              );
            }
            zip.AddEntry(RESULT1, ms.ToArray());
          }
          
          // Create a reader
          PdfReader reader = new PdfReader(ms.ToArray());
          // Convert the remote destinations into local destinations
          reader.MakeRemoteNamedDestinationsLocal();
          using (MemoryStream ms2 = new MemoryStream()) {
            // Create a new PDF containing the local destinations
            using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
            }
            zip.AddEntry(RESULT2, ms2.ToArray());
          }
          
        }
        zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM);
        zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL);
        zip.Save(stream);             
      }   
   }
Пример #22
0
        public ITestResult Perform()
        {
            byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };

            Asn1Encodable[] values =
            {
                new Cast5CbcParameters(testIv, 128),
                new NetscapeCertType(NetscapeCertType.Smime),
                new VerisignCzagExtension(new DerIA5String("hello")),
            #if INCLUDE_IDEA
                new IdeaCbcPar(testIv),
            #endif
                new NetscapeRevocationUrl(new DerIA5String("http://test"))
            };

            #if INCLUDE_IDEA
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");
            #else
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvFgtodHRwOi8vdGVzdA==");
            #endif

            try
            {
                MemoryStream bOut = new MemoryStream();
                Asn1OutputStream aOut = new Asn1OutputStream(bOut);

                for (int i = 0; i != values.Length; i++)
                {
                    aOut.WriteObject(values[i]);
                }

                if (!Arrays.AreEqual(bOut.ToArray(), data))
                {
                    return new SimpleTestResult(false, Name + ": Failed data check");
                }

                Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

                for (int i = 0; i != values.Length; i++)
                {
                    Asn1Object o = aIn.ReadObject();

                    if (!values[i].Equals(o))
                    {
                        return new SimpleTestResult(false, Name + ": Failed equality test for " + o);
                    }

                    if (o.GetHashCode() != values[i].GetHashCode())
                    {
                        return new SimpleTestResult(false, Name + ": Failed hashCode test for " + o);
                    }
                }

                return new SimpleTestResult(true, Name + ": Okay");
            }
            catch (Exception e)
            {
                return new SimpleTestResult(false, Name + ": Failed - exception " + e.ToString(), e);
            }
        }
Пример #23
0
 public string Receive()
 {
     int ib = 0x00;
     MemoryStream ms = new MemoryStream();
     for (; _stream.ReadByte() != 0x0B; ) ;
     while (true) {
         if (ib == 0x1C) {
             ib = _stream.ReadByte();
             if (ib == 0x0D)
                 break;
             ms.WriteByte(0x1C);
             ms.WriteByte((byte)ib);
         }
         else {
             ib = _stream.ReadByte();
             if (ib != 0x1C)
                 ms.WriteByte((byte)ib);
         }
     }
     if (_version3) {
         _stream.Write(ACK, 0, ACK.Length);
         _stream.Flush();
     }
     #if SILVERLIGHT
     return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
     #else
     return Encoding.ASCII.GetString(ms.ToArray());
     #endif
 }
Пример #24
0
        public static String Cryption(string text, string password, bool boolCrypt)
        {
            byte[] utf8_Salt = new byte[] { 0x26, 0x19, 0x81, 0x4E, 0xA0, 0x6D, 0x95, 0x34, 0x26, 0x75, 0x64, 0x05, 0xF6 };

            PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(password, utf8_Salt);

            Rijndael i_Alg = Rijndael.Create();
            i_Alg.Key = i_Pass.GetBytes(32);
            i_Alg.IV = i_Pass.GetBytes(16);

            ICryptoTransform i_Trans = (boolCrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

            MemoryStream i_Mem = new MemoryStream();
            CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

            byte[] utf8_Data;
            if (boolCrypt) utf8_Data = Encoding.Unicode.GetBytes(text);
            else utf8_Data = Convert.FromBase64String(text);

            try
            {
                i_Crypt.Write(utf8_Data, 0, utf8_Data.Length);
                i_Crypt.Close();
            }
            catch { return null; }

            if (boolCrypt) return Convert.ToBase64String(i_Mem.ToArray());
            else return Encoding.Unicode.GetString(i_Mem.ToArray());
        }
Пример #25
0
        public async Task<string> Request(string data)
        {
            var oWebRequest =
                (HttpWebRequest) WebRequest.Create("http://" + _ipEndPoint.Address + ":" + _ipEndPoint.Port);
            oWebRequest.Method = "POST";
            oWebRequest.ContentType = "text/plain";

            var stream = oWebRequest.GetRequestStream();
            var dataToSend = Encoding.UTF8.GetBytes(data);
            stream.Write(dataToSend, 0, dataToSend.Length);

            var oWebResponse = await oWebRequest.GetResponseAsync();
            var receiveStream = oWebResponse.GetResponseStream();

            try
            {
                if (receiveStream == null)
                    throw new Exception("ReceiveStream == null");

                var ms = new MemoryStream();
                receiveStream.CopyTo(ms);
                var array = ms.ToArray();

                if (array.Length > 0)
                  return Encoding.UTF8.GetString(ms.ToArray());

            }
            catch (Exception)
            {
                return string.Empty;
            }
            return string.Empty;
        }
Пример #26
0
        public static void VerifyAndSave(this Image image, string filename, Action<Stream> save = null)
        {
            var directory = Path.GetDirectoryName(filename);
            if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);

            var ms = new MemoryStream();
            if (save != null)
                save(ms);
            else
                image.SaveAsPng(ms);

            if (File.Exists(filename))
            {
                try
                {
                    Assert.Equal(ms.ToArray(), File.ReadAllBytes(filename));
                }
                catch
                {
                    var actualName = Path.Combine(
                        Path.GetDirectoryName(filename),
                        $"{ Path.GetFileNameWithoutExtension(filename) }.actual{ Path.GetExtension(filename) }");
                    File.WriteAllBytes(actualName, ms.ToArray());
                    throw;
                }
            }
            else
            {
                File.WriteAllBytes(filename, ms.ToArray());
            }
        }
Пример #27
0
        public string Decrypt(string encryptStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(PrivateKey);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            #if !NET451
            var aes = System.Security.Cryptography.Aes.Create();
            #else
            var aes = Rijndael.Create();
            #endif
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray(), 0, mStream.ToArray().Count());
                    }
                }
            }
            catch { }
            #if NET451
            aes.Clear();
            #endif

            return decrypt;
        }
Пример #28
0
		/// <summary>
		/// Serializes this <see cref="Token"/> instance as a string that can be
		/// included as part of a return_to variable in a querystring. 
		/// This string is cryptographically signed to protect against tampering.
		/// </summary>
		public string Serialize(INonceStore store) {
			using (MemoryStream dataStream = new MemoryStream()) {
				if (!persistSignature(store)) {
					Debug.Assert(!persistNonce(Endpoint, store), "Without a signature, a nonce is meaningless.");
					dataStream.WriteByte(0); // there will be NO signature.
					StreamWriter writer = new StreamWriter(dataStream);
					Endpoint.Serialize(writer);
					writer.Flush();
					return Convert.ToBase64String(dataStream.ToArray());
				} else {
					using (HashAlgorithm shaHash = createHashAlgorithm(store))
					using (CryptoStream shaStream = new CryptoStream(dataStream, shaHash, CryptoStreamMode.Write)) {
						StreamWriter writer = new StreamWriter(shaStream);
						Endpoint.Serialize(writer);
						if (persistNonce(Endpoint, store))
							writer.WriteLine(Nonce.Code);
						
						writer.Flush();
						shaStream.Flush();
						shaStream.FlushFinalBlock();

						byte[] hash = shaHash.Hash;
						byte[] data = new byte[1 + hash.Length + dataStream.Length];
						data[0] = 1; // there is a signature
						Buffer.BlockCopy(hash, 0, data, 1, hash.Length);
						Buffer.BlockCopy(dataStream.ToArray(), 0, data, 1 + hash.Length, (int)dataStream.Length);

						return Convert.ToBase64String(data);
					}
				}
			}
		}
        public object Search(queryrequest xml)
        {
            SemWeb.Query.Query query = null;

            string q = string.Empty;

            try
            {
                query = new SparqlEngine(new StringReader(xml.query));
            }
            catch (QueryFormatException ex)
            {
                var malformed = new malformedquery();

                malformed.faultdetails = ex.Message;

                return malformed;
            }

            // Load the data from sql server
            SemWeb.Stores.SQLStore store;

            string connstr = ConfigurationManager.ConnectionStrings["SemWebDB"].ConnectionString;

            DebugLogging.Log(connstr);

            store = (SemWeb.Stores.SQLStore)SemWeb.Store.CreateForInput(connstr);

            //Create a Sink for the results to be writen once the query is run.
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            try
            {
                // Run the query.
                query.Run(store, sink);

            }
            catch (Exception ex)
            {
                // Run the query.
                query.Run(store, sink);
                DebugLogging.Log("Run the query a second time");
                DebugLogging.Log(ex.Message);

            }
            //flush the writer then  load the memory stream
            writer.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            //Write the memory stream out to the response.
            ASCIIEncoding ascii = new ASCIIEncoding();
            DebugLogging.Log(ascii.GetString(ms.ToArray()).Replace("???", ""));
            writer.Close();

            DebugLogging.Log("End of Processing");

            return SerializeXML.DeserializeObject(ascii.GetString(ms.ToArray()).Replace("???", ""), typeof(sparql)) as sparql;
        }
		public void TestNil()
		{
			var output = new MemoryStream();
			Packer.Create( output ).PackNull();
			Assert.AreEqual( null, Unpacking.UnpackNull( new MemoryStream( output.ToArray() ) ) );
			Assert.AreEqual( null, Unpacking.UnpackNull( output.ToArray() ).Value );
		}
        /// <summary>
        /// Create model.
        ///
        /// Uploads training files to customize a translation model. You can customize a model with a forced glossary or
        /// with a parallel corpus:
        /// * Use a *forced glossary* to force certain terms and phrases to be translated in a specific way. You can
        /// upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model
        /// is limited to 10 MB.
        /// * Use a *parallel corpus* when you want your custom model to learn from general translation patterns in
        /// parallel sentences in your samples. What your model learns from a parallel corpus can improve translation
        /// results for input text that the model has not been trained on. You can upload multiple parallel corpora
        /// files with a request. To successfully train with parallel corpora, the corpora files must contain a
        /// cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a
        /// custom model is limited to 250 MB.
        ///
        /// Depending on the type of customization and the size of the uploaded files, training time can range from
        /// minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized
        /// with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then
        /// customize the resulting model with a forced glossary.
        ///
        /// You can create a maximum of 10 custom models per language pair. For more information about customizing a
        /// translation model, including the formatting and character restrictions for data files, see [Customizing your
        /// model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing).
        ///
        /// #### Supported file formats
        ///
        ///  You can provide your training data for customization in the following document formats:
        /// * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for the exchange of
        /// translation memories.
        /// * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an XML specification for the
        /// exchange of translation memories.
        /// * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases.
        /// The first row contains the language code.
        /// * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns for aligned sentences and
        /// phrases. The first row contains the language code.
        /// * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and phrases.
        /// * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns for aligned sentences and
        /// phrases. The first row contains the language code.
        ///
        /// You must encode all text data in UTF-8 format. For more information, see [Supported document formats for
        /// training
        /// data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data).
        ///
        ///
        /// #### Specifying file formats
        ///
        ///  You can indicate the format of a file by including the file extension with the file name. Use the file
        /// extensions shown in **Supported file formats**.
        ///
        /// Alternatively, you can omit the file extension and specify one of the following `content-type`
        /// specifications for the file:
        /// * **TMX** - `application/x-tmx+xml`
        /// * **XLIFF** - `application/xliff+xml`
        /// * **CSV** - `text/csv`
        /// * **TSV** - `text/tab-separated-values`
        /// * **JSON** - `application/json`
        /// * **Microsoft Excel** - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
        ///
        /// For example, with `curl`, use the following `content-type` specification to indicate the format of a CSV
        /// file named **glossary**:
        ///
        /// `--form "forced_glossary=@glossary;type=text/csv"`.
        /// </summary>
        /// <param name="baseModelId">The ID of the translation model to use as the base for customization. To see
        /// available models and IDs, use the `List models` method. Most models that are provided with the service are
        /// customizable. In addition, all models that you create with parallel corpora customization can be further
        /// customized with a forced glossary.</param>
        /// <param name="forcedGlossary">A file with forced glossary terms for the source and target languages. The
        /// customizations in the file completely overwrite the domain translation data, including high frequency or
        /// high confidence phrase translations.
        ///
        /// You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB.
        /// A forced glossary must contain single words or short phrases. For more information, see **Supported file
        /// formats** in the method description.
        ///
        /// *With `curl`, use `--form forced_glossary=@{filename}`.*. (optional)</param>
        /// <param name="parallelCorpus">A file with parallel sentences for the source and target languages. You can
        /// upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel
        /// corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a
        /// maximum of 500,000 parallel sentences across all corpora.
        ///
        /// A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can
        /// have a cumulative maximum size of 250 MB. For more information, see **Supported file formats** in the method
        /// description.
        ///
        /// *With `curl`, use `--form parallel_corpus=@{filename}`.*. (optional)</param>
        /// <param name="name">An optional model name that you can use to identify the model. Valid characters are
        /// letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32
        /// characters. (optional)</param>
        /// <returns><see cref="TranslationModel" />TranslationModel</returns>
        public DetailedResponse <TranslationModel> CreateModel(string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)
        {
            if (string.IsNullOrEmpty(baseModelId))
            {
                throw new ArgumentNullException("`baseModelId` is required for `CreateModel`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <TranslationModel> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (forcedGlossary != null)
                {
                    var forcedGlossaryContent = new ByteArrayContent(forcedGlossary.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                    forcedGlossaryContent.Headers.ContentType = contentType;
                    formData.Add(forcedGlossaryContent, "forced_glossary", "filename");
                }

                if (parallelCorpus != null)
                {
                    var parallelCorpusContent = new ByteArrayContent(parallelCorpus.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                    parallelCorpusContent.Headers.ContentType = contentType;
                    formData.Add(parallelCorpusContent, "parallel_corpus", "filename");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/models");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(baseModelId))
                {
                    restRequest.WithArgument("base_model_id", baseModelId);
                }
                if (!string.IsNullOrEmpty(name))
                {
                    restRequest.WithArgument("name", name);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "CreateModel"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <TranslationModel>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <TranslationModel>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #32
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     try
     {
         base.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
         string text = Globals.CreateVerifyCode(4);
         int    num  = 45;
         int    num2 = text.Length * 20;
         System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(num2 - 3, 40);
         System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
         graphics.Clear(System.Drawing.Color.AliceBlue);
         graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Gray, 0f), 0, 0, bitmap.Width - 1, bitmap.Height - 3);
         System.Random      random = new System.Random();
         System.Drawing.Pen pen    = new System.Drawing.Pen(System.Drawing.Color.LightGray, 0f);
         for (int i = 0; i < 50; i++)
         {
             int x = random.Next(0, bitmap.Width);
             int y = random.Next(0, bitmap.Height);
             graphics.DrawRectangle(pen, x, y, 1, 1);
         }
         char[] array = text.ToCharArray();
         System.Drawing.StringFormat stringFormat = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoClip);
         stringFormat.Alignment     = System.Drawing.StringAlignment.Center;
         stringFormat.LineAlignment = System.Drawing.StringAlignment.Center;
         System.Drawing.Color[] array2 = new System.Drawing.Color[]
         {
             System.Drawing.Color.Black,
             System.Drawing.Color.Red,
             System.Drawing.Color.DarkBlue,
             System.Drawing.Color.Green,
             System.Drawing.Color.Brown,
             System.Drawing.Color.DarkCyan,
             System.Drawing.Color.Purple,
             System.Drawing.Color.DarkGreen
         };
         for (int j = 0; j < array.Length; j++)
         {
             int num3 = random.Next(7);
             random.Next(4);
             System.Drawing.Font  font  = new System.Drawing.Font("Microsoft Sans Serif", 17f, System.Drawing.FontStyle.Bold);
             System.Drawing.Brush brush = new System.Drawing.SolidBrush(array2[num3]);
             System.Drawing.Point point = new System.Drawing.Point(14, 11);
             float num4 = (float)random.Next(-num, num);
             graphics.TranslateTransform((float)point.X, (float)point.Y);
             graphics.RotateTransform(num4);
             graphics.DrawString(array[j].ToString(), font, brush, 1f, 10f, stringFormat);
             graphics.RotateTransform(-num4);
             graphics.TranslateTransform(2f, (float)(-(float)point.Y));
         }
         System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
         bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);
         base.Response.ClearContent();
         base.Response.ContentType = "image/gif";
         base.Response.BinaryWrite(memoryStream.ToArray());
         graphics.Dispose();
         bitmap.Dispose();
     }
     catch
     {
     }
 }
Пример #33
0
        public void DownloadPDFFormat()
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("File");
            try
            {
                Document pdfReport = new Document(PageSize.A4, 100, 91, 100, 93);
                System.IO.MemoryStream msReport = new System.IO.MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
                pdfReport.Open();
                DBConnectionHandler1 db = new DBConnectionHandler1();
                SqlConnection        cn = db.getconnection();
                cn.Open();
                SqlCommand    cmd = new SqlCommand("select * from UploadLogo", cn);
                SqlDataReader dr  = cmd.ExecuteReader();
                if (dr.Read())
                {
                    if (dr.GetString(1).ToString() != "")
                    {
                        iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(@dr.GetString(1).ToString().Trim());
                        image1.SetAbsolutePosition(70, 100);
                        PdfContentByte by = writer.DirectContent;
                        PdfTemplate    tp = by.CreateTemplate(170, 190);
                        tp.AddImage(image1);
                        by.AddTemplate(tp, 175, 660);
                        cn.Close();
                        dr.Close();
                    }
                }
                string datetime = string.Empty;
                datetime = Convert.ToString(System.DateTime.Now);

                string str = string.Empty;

                if (txtitemno.Text != "")
                {
                    str = ("   Model_No. : " + txtitemno.Text);
                }
                if (ddlStatus.Text != "")
                {
                    str = ("   LostStatus : " + ddlStatus.Text);
                }
                if (ddllocation.Text != "")
                {
                    str = ("    Location : " + ddllocation.Text);
                }
                //if (txtfoundby.Text != "")
                //    str = ("   Found By : " + txtfoundby.Text);
                if (txtsignoutby.Text != "")
                {
                    str = ("   IssuedTo_Name : " + txtsignoutby.Text);
                }
                if (txtsigninby.Text != "")
                {
                    str = ("   IssuedBy_Name : " + txtsigninby.Text);
                }

                if (txtdatefrom.Text != "" && txtdateto.Text != "")
                {
                    str = ("   Date  From :" + txtdatefrom.Text + "      To :" + txtdateto.Text);
                }



                Phrase headerPhrase = new Phrase("                                     Item Report                                                       ", FontFactory.GetFont("Garamond", 14));

                headerPhrase.Add("      Generated On : ");
                headerPhrase.Add(datetime);
                //headerPhrase.Add("                                                                           Searching Parameter  : ");
                //headerPhrase.Add(str);


                HeaderFooter header = new HeaderFooter(headerPhrase, false);
                header.Border    = Rectangle.NO_BORDER;
                header.Alignment = Element.ALIGN_CENTER;
                header.Alignment = Element.ALIGN_BOTTOM;
                pdfReport.Header = header;
                pdfReport.Add(headerPhrase);


                // Creates the Table
                PdfPTable ptData = new PdfPTable(gvItemTable1.Columns.Count - 1);
                ptData.SpacingBefore       = 8;
                ptData.DefaultCell.Padding = 1;
                float[] headerwidths = new float[gvItemTable1.Columns.Count - 1]; // percentage

                headerwidths[0] = 3.2F;
                headerwidths[1] = 3.2F;
                headerwidths[2] = 3.2F;
                headerwidths[3] = 3.2F;
                headerwidths[4] = 3.2F;
                headerwidths[5] = 3.2F;
                // headerwidths[6] = 3.2F;
                // headerwidths[7] = 3.2F;
                //headerwidths[8] = 3.2F;

                ptData.SetWidths(headerwidths);
                ptData.WidthPercentage = 100;
                ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptData.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;

                //Insert the Table Headers
                for (int intK = 0; intK < gvItemTable1.Columns.Count - 1; intK++)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.BorderWidth     = 0.001f;
                    cell.BackgroundColor = new Color(200, 200, 200);
                    cell.BorderColor     = new Color(100, 100, 100);
                    if (gvItemTable1.Columns[intK + 1].HeaderText.ToString() != "")
                    {
                        cell.Phrase = new Phrase(gvItemTable1.Columns[intK + 1].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD));
                        ptData.AddCell(cell);
                    }
                }

                ptData.HeaderRows = 1; // this is the end of the table header

                //Insert the Table Data

                for (int intJ = 0; intJ < gvItemTable1.Items.Count; intJ++)
                {
                    for (int intK = 0; intK < gvItemTable1.Columns.Count - 1; intK++)
                    {
                        PdfPCell cell = new PdfPCell();
                        cell.BorderWidth     = 0.001f;
                        cell.BorderColor     = new Color(100, 100, 100);
                        cell.BackgroundColor = new Color(250, 250, 250);
                        if (gvItemTable1.Items[intJ].Cells[intK + 3].Text.ToString() != "")
                        {
                            cell.Phrase = new Phrase(gvItemTable1.Items[intJ].Cells[intK + 3].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                            ptData.AddCell(cell);
                        }
                        else
                        {
                            cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                            ptData.AddCell(cell);
                        }
                    }
                }

                //Insert the Table

                pdfReport.Add(ptData);

                //Closes the Report and writes to Memory Stream

                pdfReport.Close();

                //Writes the Memory Stream Data to Response Object
                Response.Clear();

                Response.AddHeader("content-disposition", string.Format("attachment;filename=InventoryReport.pdf"));
                Response.Charset     = "";
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(msReport.ToArray());
                Response.End();
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
            }
        }
Пример #34
0
        static public int LzmaBenchmark(Int32 numIterations, UInt32 dictionarySize)
        {
            if (numIterations <= 0)
            {
                return(0);
            }
            if (dictionarySize < (1 << 18))
            {
                System.Console.WriteLine("\nError: dictionary size for benchmark must be >= 19 (512 KB)");
                return(1);
            }
            System.Console.Write("\n       Compressing                Decompressing\n\n");

            Compression.LZMA.Encoder encoder = new Compression.LZMA.Encoder();
            Compression.LZMA.Decoder decoder = new Compression.LZMA.Decoder();


            CoderPropID[] propIDs =
            {
                CoderPropID.DictionarySize,
            };
            object[] properties =
            {
                (Int32)(dictionarySize),
            };

            UInt32 kBufferSize           = dictionarySize + kAdditionalSize;
            UInt32 kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize;

            encoder.SetCoderProperties(propIDs, properties);
            System.IO.MemoryStream propStream = new System.IO.MemoryStream();
            encoder.WriteCoderProperties(propStream);
            byte[] propArray = propStream.ToArray();

            CBenchRandomGenerator rg = new CBenchRandomGenerator();

            rg.Set(kBufferSize);
            rg.Generate();
            CRC crc = new CRC();

            crc.Init();
            crc.Update(rg.Buffer, 0, rg.BufferSize);

            CProgressInfo progressInfo = new CProgressInfo();

            progressInfo.ApprovedStart = dictionarySize;

            UInt64 totalBenchSize      = 0;
            UInt64 totalEncodeTime     = 0;
            UInt64 totalDecodeTime     = 0;
            UInt64 totalCompressedSize = 0;

            MemoryStream inStream         = new MemoryStream(rg.Buffer, 0, (int)rg.BufferSize);
            MemoryStream compressedStream = new MemoryStream((int)kCompressedBufferSize);
            CrcOutStream crcOutStream     = new CrcOutStream();

            for (Int32 i = 0; i < numIterations; i++)
            {
                progressInfo.Init();
                inStream.Seek(0, SeekOrigin.Begin);
                compressedStream.Seek(0, SeekOrigin.Begin);
                encoder.Code(inStream, compressedStream, -1, -1, progressInfo);
                TimeSpan sp2        = DateTime.UtcNow - progressInfo.Time;
                UInt64   encodeTime = (UInt64)sp2.Ticks;

                long compressedSize = compressedStream.Position;
                if (progressInfo.InSize == 0)
                {
                    throw (new Exception("Internal ERROR 1282"));
                }

                UInt64 decodeTime = 0;
                for (int j = 0; j < 2; j++)
                {
                    compressedStream.Seek(0, SeekOrigin.Begin);
                    crcOutStream.Init();

                    decoder.SetDecoderProperties(propArray);
                    UInt64          outSize   = kBufferSize;
                    System.DateTime startTime = DateTime.UtcNow;
                    decoder.Code(compressedStream, crcOutStream, 0, (Int64)outSize, null);
                    TimeSpan sp = (DateTime.UtcNow - startTime);
                    decodeTime = (ulong)sp.Ticks;
                    if (crcOutStream.GetDigest() != crc.GetDigest())
                    {
                        throw (new Exception("CRC Error"));
                    }
                }
                UInt64 benchSize = kBufferSize - (UInt64)progressInfo.InSize;
                PrintResults(dictionarySize, encodeTime, benchSize, false, 0);
                System.Console.Write("     ");
                PrintResults(dictionarySize, decodeTime, kBufferSize, true, (ulong)compressedSize);
                System.Console.WriteLine();

                totalBenchSize      += benchSize;
                totalEncodeTime     += encodeTime;
                totalDecodeTime     += decodeTime;
                totalCompressedSize += (ulong)compressedSize;
            }
            System.Console.WriteLine("---------------------------------------------------");
            PrintResults(dictionarySize, totalEncodeTime, totalBenchSize, false, 0);
            System.Console.Write("     ");
            PrintResults(dictionarySize, totalDecodeTime,
                         kBufferSize * (UInt64)numIterations, true, totalCompressedSize);
            System.Console.WriteLine("    Average");
            return(0);
        }
Пример #35
0
        private void SavePic(BitmapSource bitmap)
        {
            TestingData.ProfilePhoto = new BitmapImage();

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;

            //HACK
            TestingData.SubjectCode = "11";

            var PICTURE_FILENAME = string.Format("{0}.jpg", TestingData.sheet._id);
            //var PICTURE_FILENAME = "";
            string serverPath = @"C:\PCTest\pic\";
            var    picPath    = System.IO.Path.Combine(serverPath, PICTURE_FILENAME);

            if (!Directory.Exists(serverPath))
            {
                Directory.CreateDirectory(serverPath);
            }

            using (var fstream = new System.IO.FileStream(picPath, FileMode.Create))
            {
                encoder.Save(fstream);
                fstream.Flush();
                fstream.Close();
                fstream.Dispose();

                webcam.Stop();
                _isCameraOn = false;
            }

            var profileBitmap = BitmapFromSource(bitmap);

            ProfilePhoto = profileBitmap;


            TestingData.ProfilePhoto = new BitmapImage();
            Uri uri = new Uri(picPath, UriKind.RelativeOrAbsolute);

            TestingData.ProfilePhoto.BeginInit();
            TestingData.ProfilePhoto.UriSource   = uri;
            TestingData.ProfilePhoto.CacheOption = BitmapCacheOption.OnLoad;
            TestingData.ProfilePhoto.EndInit();

            //save image to server
            byte[] bit = new byte[0];

            using (var stream = new System.IO.MemoryStream())
            {
                JpegBitmapEncoder encoder2 = new JpegBitmapEncoder();
                encoder2.Frames.Add(BitmapFrame.Create(bitmap));
                encoder2.QualityLevel = 100;
                encoder2.Save(stream);
                bit = stream.ToArray();

                OnsiteServices svc = new OnsiteServices();

                PicRequest picre = new PicRequest
                {
                    FileName = PICTURE_FILENAME,
                    bytes    = bit
                };
                svc.SavePic(picre);

                stream.Flush();
                stream.Close();
                stream.Dispose();
            }
        }
Пример #36
0
        public SCARFSurveyAnswerModels SCARFSurveyPost([FromBody] SCARFSurveyAnswerModels SCARFSurveyModel)
        {
            SCARFSurveyAnswerModels OnjSCARFSurvey = new SCARFSurveyAnswerModels();

            try
            {
                if (String.IsNullOrEmpty(SCARFSurveyModel.WorkDayId.Trim()))
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "WorkDay Id is Required";
                }
                else if (String.IsNullOrEmpty(SCARFSurveyModel.LearnerName.Trim()))
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "Learner Name is Required";
                }
                else if (String.IsNullOrEmpty(SCARFSurveyModel.managerName.Trim()))
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "Manager Name is Required";
                }
                else if (String.IsNullOrEmpty(SCARFSurveyModel.managerEmailID.Trim()))
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "Manager Email Address is Required";
                }
                else if (SCARFSurveyModel.StatusText.Length > 300)
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "StatusText length exceeded.";
                }
                else if (SCARFSurveyModel.CertaintyText.Length > 300)
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "CertaintyText length exceeded.";
                }
                else if (SCARFSurveyModel.AutonomyText.Length > 300)
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "AutonomyText length exceeded.";
                }
                else if (SCARFSurveyModel.RelatednessText.Length > 300)
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "RelatednessText length exceeded.";
                }
                else if (SCARFSurveyModel.FairnessText.Length > 300)
                {
                    SCARFSurveyModel.IsErrrorMsg = true;
                    SCARFSurveyModel.Message     = "FairnessText length exceeded.";
                }
                if (SCARFSurveyModel.IsErrrorMsg == false)
                {
                    SCARFSurveyModel.SCARFSurveyId = 0;
                    OnjSCARFSurvey.WorkDayId       = SCARFSurveyModel.WorkDayId;
                    OnjSCARFSurvey.LearnerName     = SCARFSurveyModel.LearnerName;
                    OnjSCARFSurvey.managerName     = SCARFSurveyModel.managerName;
                    OnjSCARFSurvey.managerEmailID  = SCARFSurveyModel.managerEmailID;
                    OnjSCARFSurvey.Status          = SCARFSurveyModel.Status;
                    OnjSCARFSurvey.StatusText      = SCARFSurveyModel.StatusText;
                    OnjSCARFSurvey.Certainty       = SCARFSurveyModel.Certainty;
                    OnjSCARFSurvey.CertaintyText   = SCARFSurveyModel.CertaintyText;
                    OnjSCARFSurvey.Autonomy        = SCARFSurveyModel.Autonomy;
                    OnjSCARFSurvey.AutonomyText    = SCARFSurveyModel.AutonomyText;
                    OnjSCARFSurvey.Relatedness     = SCARFSurveyModel.Relatedness;
                    OnjSCARFSurvey.RelatednessText = SCARFSurveyModel.RelatednessText;
                    OnjSCARFSurvey.Fairness        = SCARFSurveyModel.Fairness;
                    OnjSCARFSurvey.FairnessText    = SCARFSurveyModel.FairnessText;

                    int result = BCBSDataAccess.SaveDataSCARFSurvey(OnjSCARFSurvey);

                    Util.LogInfo("Post", "After dsave call :" + result);
                    if (result > 0)
                    {
                        SCARFSurveyModel.SCARFSurveyId = result;
                        SCARFSurveyModel.IsErrrorMsg   = false;
                        SCARFSurveyModel.Message       = "Sucess";

                        var model = BCBSDataAccess.GetSCARFSurveyDataForPDF(SCARFSurveyModel.SCARFSurveyId);
                        if (model != null)
                        {
                            model.managerName = OnjSCARFSurvey.managerName;
                            string html = RenderViewToString("SCARFSurveyAnswer", "~/views/Shared/_SCARFSurveyAnswerPDF.cshtml", model);

                            model.ReportDate = model.ReportDate;
                            byte[] buffer = Render(html);
                            using (MemoryStream stream = new System.IO.MemoryStream())
                            {
                                Document  pdfDoc = new Document(PageSize.A4, 20f, 20f, 20f, 20f);
                                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
                                writer.CloseStream = false;
                                pdfDoc.Open();
                                StringReader sr = new StringReader(html);
                                XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
                                pdfDoc.Close();
                                buffer = stream.ToArray();

                                Attachment AttachmentMemoryStream = new Attachment(new MemoryStream(buffer), "SCARFSurveyAnswer" + SCARFSurveyModel.SCARFSurveyId + ".PDF");

                                //File Write in Folder With Out Mail
                                //string FilePathandName = @"C:\Logs\" + "SCARFSurveyAnswer" + SCARFSurveyModel.SCARFSurveyId + ".PDF";
                                //File.WriteAllBytes(FilePathandName, buffer);

                                #region Mail Sending
                                var    subject      = ConfigurationManager.AppSettings["MailSubject"] + model.LearnerName;
                                var    physicalPath = Util.ResolveFileName(@"Template\EmailTemplate.txt");
                                var    content      = File.ReadAllText(physicalPath);
                                string emailContent = content.Replace("@LearnerName", model.LearnerName).Replace("@ManagerName", model.managerName);
                                Util.SendMail(OnjSCARFSurvey.managerEmailID, subject, emailContent, AttachmentMemoryStream);
                            }
                            #endregion
                        }
                        SCARFSurveyModel.WorkDayId       = "";
                        SCARFSurveyModel.LearnerName     = "";
                        SCARFSurveyModel.managerName     = "";
                        SCARFSurveyModel.managerEmailID  = "";
                        SCARFSurveyModel.Status          = "";
                        SCARFSurveyModel.StatusText      = "";
                        SCARFSurveyModel.Certainty       = "";
                        SCARFSurveyModel.CertaintyText   = "";
                        SCARFSurveyModel.Autonomy        = "";
                        SCARFSurveyModel.AutonomyText    = "";
                        SCARFSurveyModel.Relatedness     = "";
                        SCARFSurveyModel.RelatednessText = "";
                        SCARFSurveyModel.Fairness        = "";
                        SCARFSurveyModel.FairnessText    = "";
                    }
                    else if (result == -1)
                    {
                        SCARFSurveyModel.SCARFSurveyId   = 0;
                        SCARFSurveyModel.IsErrrorMsg     = true;
                        SCARFSurveyModel.Message         = "Duplicate WorkDayId";
                        SCARFSurveyModel.WorkDayId       = "";
                        SCARFSurveyModel.LearnerName     = "";
                        SCARFSurveyModel.managerName     = "";
                        SCARFSurveyModel.managerEmailID  = "";
                        SCARFSurveyModel.Status          = "";
                        SCARFSurveyModel.StatusText      = "";
                        SCARFSurveyModel.Certainty       = "";
                        SCARFSurveyModel.CertaintyText   = "";
                        SCARFSurveyModel.Autonomy        = "";
                        SCARFSurveyModel.AutonomyText    = "";
                        SCARFSurveyModel.Relatedness     = "";
                        SCARFSurveyModel.RelatednessText = "";
                        SCARFSurveyModel.Fairness        = "";
                    }
                    else
                    {
                        SCARFSurveyModel.SCARFSurveyId = 0;
                        SCARFSurveyModel.IsErrrorMsg   = true;
                        SCARFSurveyModel.Message       = "Fail";
                    }
                    SCARFSurveyModel.WorkDayId       = OnjSCARFSurvey.WorkDayId;
                    SCARFSurveyModel.managerName     = OnjSCARFSurvey.managerName;
                    SCARFSurveyModel.LearnerName     = OnjSCARFSurvey.LearnerName;
                    SCARFSurveyModel.managerEmailID  = OnjSCARFSurvey.managerEmailID;
                    SCARFSurveyModel.Status          = OnjSCARFSurvey.Status;
                    SCARFSurveyModel.StatusText      = OnjSCARFSurvey.StatusText;
                    SCARFSurveyModel.Certainty       = OnjSCARFSurvey.Certainty;
                    SCARFSurveyModel.CertaintyText   = OnjSCARFSurvey.CertaintyText;
                    SCARFSurveyModel.Autonomy        = OnjSCARFSurvey.Autonomy;
                    SCARFSurveyModel.AutonomyText    = OnjSCARFSurvey.AutonomyText;
                    SCARFSurveyModel.Relatedness     = OnjSCARFSurvey.Relatedness;
                    SCARFSurveyModel.RelatednessText = OnjSCARFSurvey.RelatednessText;
                    SCARFSurveyModel.Fairness        = OnjSCARFSurvey.Fairness;
                    SCARFSurveyModel.FairnessText    = OnjSCARFSurvey.FairnessText;
                    SCARFSurveyModel.ReportDate      = OnjSCARFSurvey.ReportDate;
                }
            }
            catch (Exception ex)
            {
                string DetailsMessageError = null;
                if (ex.InnerException != null)
                {
                    DetailsMessageError = ex.InnerException.Message + " " + ex.StackTrace;
                }
                else
                {
                    DetailsMessageError = ex.StackTrace;
                }
                Util.LoggError(new System.Diagnostics.StackFrame(0).GetMethod().Name,
                               ex.Message, DetailsMessageError);
                SCARFSurveyModel.IsErrrorMsg = true;
                SCARFSurveyModel.Message     = "Exception block: " + DetailsMessageError;
            }
            return(SCARFSurveyModel);
        }
Пример #37
0
        public Texture FetchNew()
        {
            if (CachedTexture != null)
            {
                return(CachedTexture);
            }

            var texInfo = FetchTexInfo();

            if (texInfo == null)
            {
                return(null);
            }

            int  height      = texInfo.Texture?.Header?.Height ?? 0;
            int  width       = texInfo.Texture?.Header?.Width ?? 0;
            int  dxgiFormat  = texInfo.Texture?.Header?.DXGIFormat ?? 0;
            int  mipmapCount = texInfo.Texture?.Mipmaps ?? 0;
            uint fourCC      = FourCCDX10;
            int  arraySize   = texInfo.Texture?.Header?.TextureCount ?? 1;

            if (arraySize < 1)
            {
                arraySize = 1;
            }

            DDS ppDdsHeader_ForDebug = null;

            bool hasFullCubeDDSCaps2 = false;

            int dataStartOffset = 0;

            var br = new BinaryReaderEx(false, texInfo.DDSBytes);

            bool hasHeader = br.ReadASCII(4) == "DDS ";

            int blockSize = !hasHeader?GetBlockSize(texInfo.Texture.Format) : -1;

            if (hasHeader)
            {
                DDS header = new DDS(texInfo.DDSBytes);
                height      = header.dwHeight;
                width       = header.dwWidth;
                mipmapCount = header.dwMipMapCount;
                fourCC      = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(header.ddspf.dwFourCC), 0);

                if ((header.dwCaps2 & FullCubeDDSCaps2) == FullCubeDDSCaps2)
                {
                    hasFullCubeDDSCaps2 = true;
                }

                if (header.header10 != null)
                {
                    arraySize  = (int)header.header10.arraySize;
                    dxgiFormat = (int)header.header10.dxgiFormat;
                }

                dataStartOffset = header.DataOffset;

                ppDdsHeader_ForDebug = header;
            }
            else
            {
                if (texInfo.Platform == TPF.TPFPlatform.PS4)
                {
                    switch (texInfo.Texture.Format)
                    {
                    case 0:
                    case 1:
                    case 25:
                    case 103:
                    case 108:
                    case 109:
                        fourCC = FourCCDX10;     //DX10
                        break;

                    case 5:
                    case 100:
                    case 102:
                    case 106:
                    case 107:
                    case 110:
                        fourCC = FourCCDX10;     //DX10
                        break;

                    case 22:
                        fourCC = 0x71;
                        break;

                    case 105:
                        fourCC = 0;
                        break;
                    }
                }
                else if (texInfo.Platform == TPF.TPFPlatform.PS3)
                {
                    switch (texInfo.Texture.Format)
                    {
                    case 0:
                    case 1:
                        fourCC = 0x31545844;
                        break;

                    case 5:
                        fourCC = 0x35545844;
                        break;

                    case 9:
                    case 10:
                        fourCC = 0;
                        break;
                    }
                }

                if (mipmapCount == 0)
                {
                    // something Hork came up with :fatcat:
                    mipmapCount = (int)(1 + Math.Floor(Math.Log(Math.Max(width, height), 2)));
                }

                dataStartOffset = 0;
            }

            SurfaceFormat surfaceFormat;

            if (fourCC == FourCCDX10)
            {
                // See if there are DX9 textures
                int fmt = dxgiFormat;
                if (fmt == 70 || fmt == 71 || fmt == 72)
                {
                    surfaceFormat = SurfaceFormat.Dxt1;
                }
                else if (fmt == 73 || fmt == 74 || fmt == 75)
                {
                    surfaceFormat = SurfaceFormat.Dxt3;
                }
                else if (fmt == 76 || fmt == 77 || fmt == 78)
                {
                    surfaceFormat = SurfaceFormat.Dxt5;
                }
                else if (fmt == 79 || fmt == 80 || fmt == 81)
                {
                    surfaceFormat = SurfaceFormat.ATI1;
                }
                else if (fmt == 82 || fmt == 83 || fmt == 84)
                {
                    surfaceFormat = SurfaceFormat.ATI2;
                }
                else if (fmt == 95)
                {
                    surfaceFormat = SurfaceFormat.BC6HUF16;
                }
                else if (fmt == 96)
                {
                    surfaceFormat = SurfaceFormat.BC6HSF16;
                }
                else if (fmt == 94)
                {
                    surfaceFormat = SurfaceFormat.BC6HTypeless;
                }
                else if (fmt == 97 || fmt == 98 || fmt == 99)
                {
                    surfaceFormat = SurfaceFormat.BC7;
                }
                else
                {
                    // No DX10 texture support in monogame yet
                    Console.WriteLine($"Unable to load {TexName} because it uses DX10+ exclusive texture type.");
                    CachedTexture = Main.DEFAULT_TEXTURE_MISSING_CUBE;
                    TPFReference  = null;
                    return((TextureCube)CachedTexture);
                }
            }
            else
            {
                surfaceFormat = GetSurfaceFormatFromString(System.Text.Encoding.ASCII.GetString(BitConverter.GetBytes(fourCC)));
            }

            bool mipmaps = mipmapCount > 0;

            // apply memes
            if (texInfo.Platform == TPF.TPFPlatform.PC || texInfo.Platform == TPF.TPFPlatform.PS3)
            {
                width   = IsCompressedFormat(surfaceFormat) ? ((width + 3) & ~0x3) : width;
                height  = IsCompressedFormat(surfaceFormat) ? ((height + 3) & ~0x3) : height;
                mipmaps = true;
            }
            else if (texInfo.Platform == TPF.TPFPlatform.PS4)
            {
                width  = (int)(Math.Ceiling(width / 4f) * 4f);
                height = (int)(Math.Ceiling(height / 4f) * 4f);
            }
            //else if (texInfo.Platform == TPF.TPFPlatform.PS3)
            //{
            //    throw new NotImplementedException();
            //}
            else
            {
                throw new NotImplementedException();
            }

            Texture tex = null;

            int paddedWidth  = 0;
            int paddedHeight = 0;
            int paddedSize   = 0;
            int copyOffset   = dataStartOffset;

            bool isCubeMap = (texInfo.Texture?.Type == TPF.TexType.Cubemap) || arraySize >= 6 || hasFullCubeDDSCaps2;

            if (isCubeMap)
            {
                tex = new TextureCube(GFX.Device, width, true, surfaceFormat);
            }
            else
            {
                tex = new Texture2D(GFX.Device, width, height,
                                    mipmapCount > 1,
                                    surfaceFormat,
                                    arraySize);
            }

            if (texInfo.Platform == TPF.TPFPlatform.PC || texInfo.Platform == TPF.TPFPlatform.PS3)
            {
                for (int i = 0; i < arraySize; i++)
                {
                    for (int j = 0; j < mipmapCount; j++)
                    {
                        var mipInfo = GetMipInfo(surfaceFormat, width, height, j, isCubeMap);

                        paddedSize = mipInfo.ByteCount;

                        //if (surfaceFormat == SurfaceFormat.Dxt1 || surfaceFormat == SurfaceFormat.Dxt1SRgb)
                        //    paddedSize /= 2;

                        //if (GameDataManager.GameType == GameDataManager.GameTypes.DS1R && surfaceFormat == SurfaceFormat.Dxt1)
                        //    paddedSize /= 2;

                        if (isCubeMap)
                        {
                            ((TextureCube)tex).SetData((CubeMapFace)i, j, null, br.GetBytes(copyOffset, paddedSize), 0, paddedSize);
                        }
                        else
                        {
                            try
                            {
                                ((Texture2D)tex).SetData(j, i, null, br.GetBytes(copyOffset, paddedSize), 0, paddedSize);
                            }
                            catch (ArgumentException)
                            {
                                try
                                {
                                    ((Texture2D)tex).SetData(j, i, null, br.GetBytes(copyOffset, paddedSize / 2), 0, paddedSize);
                                }
                                catch
                                {
                                }
                            }
                        }

                        copyOffset += paddedSize;
                    }
                }
            }
            else if (texInfo.Platform == TPF.TPFPlatform.PS4)
            {
                if (isCubeMap)
                {
                    throw new NotImplementedException();
                    //for (int i = 0; i < arraySize; i++)
                    //{
                    //    int currentWidth = width;
                    //    int currentHeight = height;

                    //    void SetPaddedSize_PS4(int w, int h)
                    //    {
                    //        if (isCubeMap)
                    //        {
                    //            if (texInfo.Texture.Format == 22)
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 8f) * 8f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 8f) * 8f);
                    //                paddedSize = paddedWidth * paddedHeight * blockSize;
                    //            }
                    //            else
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 32f) * 32f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 32f) * 32f);
                    //                paddedSize = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                    //            }
                    //        }
                    //        else
                    //        {
                    //            if (texInfo.Texture.Format == 105)
                    //            {
                    //                paddedWidth = w;
                    //                paddedHeight = h;
                    //                paddedSize = paddedWidth * paddedHeight * blockSize;
                    //            }
                    //            else
                    //            {
                    //                paddedWidth = (int)(Math.Ceiling(w / 32f) * 32f);
                    //                paddedHeight = (int)(Math.Ceiling(h / 32f) * 32f);
                    //                paddedSize = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                    //            }
                    //        }
                    //    }

                    //    SetPaddedSize_PS4(currentWidth, currentHeight);

                    //    copyOffset = dataStartOffset + paddedSize * i;

                    //    for (int j = 0; j < mipmapCount; j++)
                    //    {
                    //        if (j > 0)
                    //        {
                    //            SetPaddedSize_PS4(currentWidth, currentHeight);

                    //            copyOffset += paddedSize * i;
                    //        }

                    //        var deswizzler = new DDSDeswizzler(texInfo.Texture.Format, br.GetBytes(copyOffset, paddedSize), blockSize);

                    //        byte[] deswizzledMipMap = null;

                    //        deswizzler.CreateOutput();
                    //        deswizzler.DDSWidth = paddedWidth;
                    //        deswizzler.DeswizzleDDSBytesPS4(currentWidth, currentHeight);
                    //        deswizzledMipMap = deswizzler.OutputBytes;

                    //        var finalBytes = (deswizzledMipMap ?? deswizzler.InputBytes);

                    //        using (var tempMemStream = new System.IO.MemoryStream(finalBytes.Length))
                    //        {
                    //            var tempWriter = new BinaryWriter(tempMemStream);

                    //            if (texInfo.Texture.Format == 22)
                    //            {
                    //                for (int h = 0; h < currentHeight; h++)
                    //                {
                    //                    tempWriter.Write(finalBytes, h * paddedWidth * blockSize, currentWidth * blockSize);
                    //                }
                    //            }
                    //            else
                    //            {
                    //                for (int h = 0; h < (int)Math.Ceiling(currentHeight / 4f); h++)
                    //                {
                    //                    tempWriter.Write(finalBytes, (int)(h * Math.Ceiling(paddedWidth / 4f) * blockSize), (int)(Math.Ceiling(currentWidth / 4f) * blockSize));
                    //                }
                    //            }

                    //            if (isCubeMap)
                    //            {
                    //                ((TextureCube)tex).SetData((CubeMapFace)j, i, null, tempMemStream.ToArray(), 0, finalBytes.Length);
                    //            }
                    //            else
                    //            {
                    //                ((Texture2D)tex).SetData(j, i, null, tempMemStream.ToArray(), 0, finalBytes.Length);
                    //            }


                    //        }

                    //        copyOffset += (arraySize - i) * paddedSize + paddedSize * 2;

                    //        if (currentWidth > 1)
                    //            currentWidth /= 2;

                    //        if (currentHeight > 1)
                    //            currentHeight /= 2;
                    //    }
                    //}
                }
                else
                {
                    int currentWidth  = width;
                    int currentHeight = height;

                    for (int j = 0; j < mipmapCount; j++)
                    {
                        if (texInfo.Texture.Format == 105)
                        {
                            paddedWidth  = currentWidth;
                            paddedHeight = currentHeight;
                            paddedSize   = paddedWidth * paddedHeight * blockSize;
                        }
                        else
                        {
                            paddedWidth  = (int)(Math.Ceiling(currentWidth / 32f) * 32f);
                            paddedHeight = (int)(Math.Ceiling(currentHeight / 32f) * 32f);
                            paddedSize   = (int)(Math.Ceiling(paddedWidth / 4f) * Math.Ceiling(paddedHeight / 4f) * blockSize);
                        }

                        var deswizzler = new DDSDeswizzler(texInfo.Texture.Format, br.GetBytes(copyOffset, paddedSize), blockSize);

                        byte[] deswizzledMipMap = null;

                        deswizzler.CreateOutput();
                        deswizzler.DDSWidth = paddedWidth;
                        deswizzler.DeswizzleDDSBytesPS4(currentWidth, currentHeight);
                        deswizzledMipMap = deswizzler.OutputBytes;

                        var finalBytes = (deswizzledMipMap ?? deswizzler.InputBytes);

                        using (var tempMemStream = new System.IO.MemoryStream())
                        {
                            var tempWriter = new BinaryWriter(tempMemStream);


                            if (texInfo.Texture.Format == 105)
                            {
                                tempWriter.Write(finalBytes);
                            }
                            else
                            {
                                for (int h = 0; h < (int)Math.Ceiling(currentHeight / 4f); h++)
                                {
                                    tempWriter.Write(finalBytes, (int)(h * Math.Ceiling(paddedWidth / 4f) * blockSize), (int)(Math.Ceiling(currentWidth / 4f) * blockSize));
                                }
                            }

                            ((Texture2D)tex).SetData(j, 0, null, tempMemStream.ToArray(), 0, (int)tempMemStream.Length);
                        }

                        copyOffset += paddedSize;

                        if (currentWidth > 1)
                        {
                            currentWidth /= 2;
                        }

                        if (currentHeight > 1)
                        {
                            currentHeight /= 2;
                        }
                    }
                }
            }

            CachedTexture?.Dispose();

            CachedTexture = tex;

            return(CachedTexture);
        }
Пример #38
0
        /// <summary>
        /// 插入到excel的cell
        /// </summary>
        /// <param name="fileName">excel文件名</param>
        /// <param name="dst">目标 (行,列,值)</param>
        /// <param name="sheetName">默认sheetName,可以不写</param>
        public static void WriteToExcelCell(string fileName, List <Tuple <int, int, object, string> > customCell, string sheetName = "sheet1")
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book  = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet = book.CreateSheet(sheetName);
            foreach (var item in customCell)
            {
                int    r                   = item.Item1;
                int    c                   = item.Item2;
                object content             = item.Item3;
                NPOI.SS.UserModel.IRow row = null;
                if (sheet.GetRow(r) == null)
                {
                    row = sheet.CreateRow(r);
                }
                else
                {
                    row = sheet.GetRow(r);
                }
                NPOI.SS.UserModel.ICell cell = row.CreateCell(c);
                cell.SetCellValue(content.ToString());
                string objType = item.Item4.ToString();
                #region 类型转换
                try
                {
                    switch (objType)
                    {
                    case "System.String":    //字符串类型
                        cell.SetCellValue(content.ToString());
                        break;

                    case "System.DateTime":    //日期类型
                        DateTime dateV;
                        DateTime.TryParse(content.ToString(), out dateV);
                        string strtime = dateV.ToString("yyyy-MM-dd HH:mm:ss");
                        if (strtime.Substring(11, 8) == "00:00:00")
                        {
                            strtime = dateV.ToString("yyyy-MM-dd");
                        }
                        cell.SetCellValue(strtime);
                        break;

                    case "System.Boolean":    //布尔型
                        bool boolV = false;
                        bool.TryParse(content.ToString(), out boolV);
                        cell.SetCellValue(boolV);
                        break;

                    case "System.Int16":    //整型
                        cell.SetCellValue(Convert.ToInt16(content));
                        break;

                    case "System.Int32":
                        cell.SetCellValue(Convert.ToInt32(content));
                        break;

                    case "System.Int64":
                        cell.SetCellValue(Convert.ToInt64(content));
                        break;

                    case "System.Byte":
                        cell.SetCellValue(Convert.ToInt32(content));
                        break;

                    case "System.Decimal":    //浮点型
                        cell.SetCellValue(Convert.ToDouble(content));
                        break;

                    case "System.Double":
                        cell.SetCellValue(Convert.ToDouble(content));
                        break;

                    case "System.DBNull":    //空值处理
                        cell.SetCellValue("");
                        break;

                    default:
                        cell.SetCellValue(content.ToString());
                        break;
                    }
                }
                catch
                {
                    cell.SetCellValue(content.ToString());
                }
                #endregion
            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            byte[] b = ms.ToArray();
            File.WriteAllBytes(fileName, b);
            book = null;
            ms.Close();
            ms.Dispose();
        }
Пример #39
0
    ///  <summary>
    ///  创建随机码图片
    ///  </summary>
    ///  <param  name="randomcode">随机码</param>
    protected void CreateImage(string randomcode)
    {
        int      randAngle = 45;                       //随机转动角度
        int      mapwidth  = (int)(randomcode.Length * 16);
        Bitmap   map       = new Bitmap(mapwidth, 28); //创建图片背景,设置其长宽
        Graphics graph     = Graphics.FromImage(map);

        graph.Clear(Color.AliceBlue);
        graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);    //画一个边框

        Random rand = new Random();

        // 生成背景噪点
        Pen blackPen = new Pen(Color.LightGray, 0);

        for (int i = 0; i < 50; i++)
        {
            int x = rand.Next(0, map.Width);
            int y = rand.Next(0, map.Height);
            graph.DrawRectangle(blackPen, x, y, 1, 1);
        }

        //验证码旋转,防止机器识别
        char[] chars = randomcode.ToCharArray();    //拆散字符串成单字符数组

        //文字距中
        StringFormat format = new StringFormat(StringFormatFlags.NoClip);

        format.Alignment     = StringAlignment.Center;
        format.LineAlignment = StringAlignment.Center;

        // 定义随机颜色列表
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        // 定义随机字体字体
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

        for (int i = 0; i < chars.Length; i++)
        {
            int cindex = rand.Next(7);
            int findex = rand.Next(5);

            Font  f = new System.Drawing.Font(font[findex], 16, System.Drawing.FontStyle.Bold);    // 字体样式(参数2为字体大小)
            Brush b = new System.Drawing.SolidBrush(c[cindex]);

            Point dot   = new Point(11, 11);       // 括号内数值越大,字符间距越大
            float angle = rand.Next(0, randAngle); // 转动的度数,如果将0改为-randAngle,那么旋转角度为-45度~45度

            graph.TranslateTransform(dot.X, dot.Y);
            graph.RotateTransform(angle);
            graph.DrawString(chars[i].ToString(), f, b, 2, 6, format);     // 第4、5个参数控制左、上间距
            graph.RotateTransform(-angle);
            graph.TranslateTransform(2, -dot.Y);
        }

        //生成图片
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/gif";
        Response.BinaryWrite(ms.ToArray());
        graph.Dispose();
        map.Dispose();
    }
Пример #40
0
        static public byte[] Create(HttpPostedFileBase FileUploader)
        {
            if (FileUploader == null)
            {
                return(null);
            }
            if (!FileUploader.ContentType.StartsWith("image"))
            {
                return(null);
            }

            var _Bytes = new byte[FileUploader.ContentLength];

            FileUploader.InputStream.Read(_Bytes, 0, FileUploader.ContentLength);

            using (var ms = new MemoryStream(_Bytes))
            {
                Bitmap imgIn  = new Bitmap(ms);
                double y      = imgIn.Height;
                double x      = imgIn.Width;
                int    height = 100;
                int    width  = 200;
                int    Radius = 100;

                double factor = 1;
                if (width > 0)
                {
                    factor = width / x;
                }
                else if (height > 0)
                {
                    factor = height / y;
                }
                System.IO.MemoryStream outStream = new System.IO.MemoryStream();
                Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
                imgOut.SetResolution(72, 72);
                Graphics g = Graphics.FromImage(imgOut);
                g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
                Brush brush = new System.Drawing.SolidBrush(Color.Transparent);
                for (int i = 0; i < 4; i++)
                {
                    Point[] CornerUpLeft = new Point[3];
                    CornerUpLeft[0].X = 0;
                    CornerUpLeft[0].Y = 0;
                    CornerUpLeft[1].X = Radius;
                    CornerUpLeft[1].Y = 0;
                    CornerUpLeft[2].X = 0;
                    CornerUpLeft[2].Y = Radius;
                    System.Drawing.Drawing2D.GraphicsPath pathCornerUpLeft =
                        new System.Drawing.Drawing2D.GraphicsPath();
                    pathCornerUpLeft.AddArc(CornerUpLeft[0].X, CornerUpLeft[0].Y,
                                            Radius, Radius, 180, 90);
                    pathCornerUpLeft.AddLine(CornerUpLeft[0].X, CornerUpLeft[0].Y,
                                             CornerUpLeft[1].X, CornerUpLeft[1].Y);
                    pathCornerUpLeft.AddLine(CornerUpLeft[0].X, CornerUpLeft[0].Y,
                                             CornerUpLeft[2].X, CornerUpLeft[2].Y);
                    g.FillPath(brush, pathCornerUpLeft);
                    pathCornerUpLeft.Dispose();
                    imgOut.RotateFlip(RotateFlipType.Rotate90FlipNone);
                }
                imgOut.Save(outStream, ImageFormat.Png);
                return(outStream.ToArray());
            }
        }
Пример #41
0
        /// <summary>
        /// Compare two documents.
        ///
        /// Compares two input documents. Documents must be in the same format.
        /// </summary>
        /// <param name="file1">The first document to compare.</param>
        /// <param name="file2">The second document to compare.</param>
        /// <param name="file1ContentType">The content type of file1. (optional)</param>
        /// <param name="file2ContentType">The content type of file2. (optional)</param>
        /// <param name="file1Label">A text label for the first document. (optional, default to file_1)</param>
        /// <param name="file2Label">A text label for the second document. (optional, default to file_2)</param>
        /// <param name="model">The analysis model to be used by the service. For the **Element classification** and
        /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
        /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
        /// batch-processing requests. (optional)</param>
        /// <returns><see cref="CompareReturn" />CompareReturn</returns>
        public DetailedResponse <CompareReturn> CompareDocuments(System.IO.MemoryStream file1, System.IO.MemoryStream file2, string file1ContentType = null, string file2ContentType = null, string file1Label = null, string file2Label = null, string model = null)
        {
            if (file1 == null)
            {
                throw new ArgumentNullException("`file1` is required for `CompareDocuments`");
            }
            if (file2 == null)
            {
                throw new ArgumentNullException("`file2` is required for `CompareDocuments`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <CompareReturn> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file1 != null)
                {
                    var file1Content = new ByteArrayContent(file1.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(file1ContentType, out contentType);
                    file1Content.Headers.ContentType = contentType;
                    formData.Add(file1Content, "file_1", "filename");
                }

                if (file2 != null)
                {
                    var file2Content = new ByteArrayContent(file2.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(file2ContentType, out contentType);
                    file2Content.Headers.ContentType = contentType;
                    formData.Add(file2Content, "file_2", "filename");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/comparison");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(file1Label))
                {
                    restRequest.WithArgument("file_1_label", file1Label);
                }
                if (!string.IsNullOrEmpty(file2Label))
                {
                    restRequest.WithArgument("file_2_label", file2Label);
                }
                if (!string.IsNullOrEmpty(model))
                {
                    restRequest.WithArgument("model", model);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "CompareDocuments"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <CompareReturn>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <CompareReturn>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #42
0
        /// <summary>
        /// Submit a batch-processing request.
        ///
        /// Run Compare and Comply methods over a collection of input documents.
        ///
        /// **Important:** Batch processing requires the use of the [IBM Cloud Object Storage
        /// service](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage).
        /// The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using batch
        /// processing](https://cloud.ibm.com/docs/services/compare-comply?topic=compare-comply-batching#before-you-batch).
        /// </summary>
        /// <param name="function">The Compare and Comply method to run across the submitted input documents.</param>
        /// <param name="inputCredentialsFile">A JSON file containing the input Cloud Object Storage credentials. At a
        /// minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name`
        /// parameter.</param>
        /// <param name="inputBucketLocation">The geographical location of the Cloud Object Storage input bucket as
        /// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
        /// `ap-geo`.</param>
        /// <param name="inputBucketName">The name of the Cloud Object Storage input bucket.</param>
        /// <param name="outputCredentialsFile">A JSON file that lists the Cloud Object Storage output credentials. At a
        /// minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the
        /// `output_bucket_name` parameter.</param>
        /// <param name="outputBucketLocation">The geographical location of the Cloud Object Storage output bucket as
        /// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
        /// `ap-geo`.</param>
        /// <param name="outputBucketName">The name of the Cloud Object Storage output bucket.</param>
        /// <param name="model">The analysis model to be used by the service. For the **Element classification** and
        /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
        /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
        /// batch-processing requests. (optional)</param>
        /// <returns><see cref="BatchStatus" />BatchStatus</returns>
        public DetailedResponse <BatchStatus> CreateBatch(string function, System.IO.MemoryStream inputCredentialsFile, string inputBucketLocation, string inputBucketName, System.IO.MemoryStream outputCredentialsFile, string outputBucketLocation, string outputBucketName, string model = null)
        {
            if (string.IsNullOrEmpty(function))
            {
                throw new ArgumentNullException("`function` is required for `CreateBatch`");
            }
            if (inputCredentialsFile == null)
            {
                throw new ArgumentNullException("`inputCredentialsFile` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(inputBucketLocation))
            {
                throw new ArgumentNullException("`inputBucketLocation` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(inputBucketName))
            {
                throw new ArgumentNullException("`inputBucketName` is required for `CreateBatch`");
            }
            if (outputCredentialsFile == null)
            {
                throw new ArgumentNullException("`outputCredentialsFile` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(outputBucketLocation))
            {
                throw new ArgumentNullException("`outputBucketLocation` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(outputBucketName))
            {
                throw new ArgumentNullException("`outputBucketName` is required for `CreateBatch`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <BatchStatus> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (inputCredentialsFile != null)
                {
                    var inputCredentialsFileContent = new ByteArrayContent(inputCredentialsFile.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/json", out contentType);
                    inputCredentialsFileContent.Headers.ContentType = contentType;
                    formData.Add(inputCredentialsFileContent, "input_credentials_file", "filename");
                }

                if (inputBucketLocation != null)
                {
                    var inputBucketLocationContent = new StringContent(inputBucketLocation, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    inputBucketLocationContent.Headers.ContentType = null;
                    formData.Add(inputBucketLocationContent, "input_bucket_location");
                }

                if (inputBucketName != null)
                {
                    var inputBucketNameContent = new StringContent(inputBucketName, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    inputBucketNameContent.Headers.ContentType = null;
                    formData.Add(inputBucketNameContent, "input_bucket_name");
                }

                if (outputCredentialsFile != null)
                {
                    var outputCredentialsFileContent = new ByteArrayContent(outputCredentialsFile.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/json", out contentType);
                    outputCredentialsFileContent.Headers.ContentType = contentType;
                    formData.Add(outputCredentialsFileContent, "output_credentials_file", "filename");
                }

                if (outputBucketLocation != null)
                {
                    var outputBucketLocationContent = new StringContent(outputBucketLocation, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    outputBucketLocationContent.Headers.ContentType = null;
                    formData.Add(outputBucketLocationContent, "output_bucket_location");
                }

                if (outputBucketName != null)
                {
                    var outputBucketNameContent = new StringContent(outputBucketName, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    outputBucketNameContent.Headers.ContentType = null;
                    formData.Add(outputBucketNameContent, "output_bucket_name");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/batches");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(function))
                {
                    restRequest.WithArgument("function", function);
                }
                if (!string.IsNullOrEmpty(model))
                {
                    restRequest.WithArgument("model", model);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "CreateBatch"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <BatchStatus>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <BatchStatus>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /*Performing AES encryption of a sting or file at a path provided using a key also provided to the metode.
         * The first step is to check the key and insure that the value provided is
         * not less than 16 charters in lenght. As the text box the key is taken from
         * will not allow the user to input more than 16 charters there is no need to
         * check if the user has entered more than 16 charters.
         * The next step will be for the string of plain text or the the data read from the file
         * and key to be convered to ascii.
         * Next the memory stream that will store our result is inisalised for use as well
         * as the crypto stream that will perform the encryption using the symmetrical algorthm
         * object that has been created with the type of encryption as well as the key
         * and padding type. After this it is required for this system that the result
         * be converted to Hex before it can be output in a text box for the user. If
         * the data is not converted to Hex then the data will be compramised when it
         * is output in the text box because not all ascii values when convered back
         * to a string can be displayed in a text box. This will corupt the data and
         * result in errors when trying to decrypt the corupted data.
         * If the file encryption is used the data will be writen back to the file
         * and a result message will be displaied to the user.*/
        private string performRIJNDAELEncryption(string s, string k, byte[] iv)
        {
            if (k.Length < keySizebit / 8)
            {
                MessageBox.Show("Please insure your Key is " + keySizebit / 8 + " charters long");
                return("");
            }

            if (iv.Length < 16)
            {
                MessageBox.Show("Please insure your IV is 16 charters long");
                return("");
            }
            else
            {
                desObj.IV = iv;
            }

            //Switch used to check the type of data being encrypted, data can be a text string or a path to a file.
            switch (dataTypeForEncrypt)
            {
            case Data_Type.TEXT:
                plainbytes = Encoding.ASCII.GetBytes(s);
                break;

            case Data_Type.FILE:
                path = s;
                if (copyFile)
                {
                    copy_File(path);    /*This Will create a copy of the file you wish to encrypt so that you do not loose your data if you
                                         * have had an issue with the encryption or have lost your key.*/
                }
                try
                {
                    plainbytes = File.ReadAllBytes(path);     /*Reads the data as bytes to an array from the file of the path
                                                               * provided.*/
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Please enter a valid file path or insure the path is pointing to the correct file.\n" + ex.Message);
                    return("");
                }
                break;
            }

            //Stores the key provided as Ascii values.
            desObj.Key = Encoding.ASCII.GetBytes(k);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream           cs = new CryptoStream(ms, desObj.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(plainbytes, 0, plainbytes.Length);
            cs.Close();
            chipherBytes = ms.ToArray();
            ms.Close();

            //Switch used to check the type of data being encrypted, data can be a text string or a path to a file.
            switch (dataTypeForEncrypt)
            {
            case Data_Type.TEXT:
                s = ByteArrayToString(chipherBytes);     //Converts the bytes result to a string and returns it as the result.
                break;

            case Data_Type.FILE:
                File.WriteAllBytes(path, chipherBytes);
                s = getFileNameFromPath(path) + " File encrypted.\n";     //shows to the user that there file has been encrypted.
                break;
            }

            return(s);
        }
        /*Performs AES decryption to an encrypted string or file at a given path using the key that is
        * passed to the method. It will first check that the key the user has passed meets the requirements of the algorithim,
        * using the AES encryption will require the use of a key that is 16 charters in lenght.
        * If the user enters a key that is less than 16 charters in lenght they will given an error message
        * shown as a message box requesting that they increase the key size. The metode will also return
        * an empty string and not perform the decription.
        * Due to an issue with text boxes displaying ascii values that cannot be displayed that would simply
        * show as "?", this would effectavly corrupt the encrypted string. To avoide this I convert the encrypted
        * data to HEX and out put it as a string. This means that during the decryption of the data I must convert
        * the data back to ascii in order to perform the decryption. To pervent this from happening as well as
        * using a Hex value I also use a try catch to catch the exception throuwn and create a message box that
        * will give information on the error instead of crashing the program. If the user is decrypting a file
        * the result will be writen back to the file as well as a message to the user of the result.*/
        private string performRIJNDAELDecryption(string s, string k, byte[] iv)
        {
            if (k.Length < keySizebit / 8)
            {
                MessageBox.Show("Please insure your Key is " + keySizebit / 8 + " charters long");
                return("");
            }


            if (iv.Length < 16)
            {
                MessageBox.Show("Please insure your IV is 16 charters long");
                return("");
            }
            else
            {
                desObj.IV = iv;
            }


            //Switch used to check the type of data being decrypted, data can be a text string or a path to a file.
            switch (dataTypeForEncrypt)
            {
            case Data_Type.TEXT:
                chipherBytes = StringToByteArray(s);
                break;

            case Data_Type.FILE:
                path = s;
                try
                {
                    chipherBytes = File.ReadAllBytes(path);     /*Reads the data as bytes to an array from the file of the path
                                                                 * provided.*/
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Please enter a valid file path or insure the path is pointing to the correct file.\n" + ex.Message);
                    return("");
                }
                break;
            }

            try
            {
                //Stores the key provided as Ascii values.
                desObj.Key = Encoding.ASCII.GetBytes(k);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(chipherBytes); //creates a memory stream to store the result.
                using (CryptoStream cs = new CryptoStream(ms, desObj.CreateDecryptor(), CryptoStreamMode.Read))

                {
                    cs.Read(chipherBytes, 0, chipherBytes.Length);

                    plainbytes = ms.ToArray();
                    cs.Close();
                    ms.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("ln:181" + e.ToString());
            }

            //Switch used to check the type of data being decrypted, data can be a text string or a path to a file.
            switch (dataTypeForEncrypt)
            {
            case Data_Type.TEXT:
                s = Encoding.ASCII.GetString(plainbytes);     //Converts the bytes result to a string and returns it as the result.
                break;

            case Data_Type.FILE:
                File.WriteAllBytes(path, plainbytes);
                s = getFileNameFromPath(path) + " File decrypted.\n";     //shows to the user that there file has been decrypted.
                break;
            }

            return(s);
        }
        /// <summary>
        /// Update a classifier.
        ///
        /// Update a custom classifier by adding new positive or negative classes or by adding new images to existing
        /// classes. You must supply at least one set of positive or negative examples. For details, see [Updating
        /// custom
        /// classifiers](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-customizing#updating-custom-classifiers).
        ///
        /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier
        /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters.
        ///
        /// **Tips about retraining:**
        ///
        /// - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header parameter was set to `true`
        /// when the classifier was created. Training images are not stored in that case. Instead, create another
        /// classifier. For more information, see [Data collection](#data-collection).
        ///
        /// - Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests
        /// in parallel, the last request overwrites the previous requests. The `retrained` property shows the last time
        /// the classifier retraining finished.
        /// </summary>
        /// <param name="classifierId">The ID of the classifier.</param>
        /// <param name="positiveExamples">A dictionary that contains the value for each classname. The value is a .zip
        /// file of images that depict the visual subject of a class in the classifier. The positive examples create or
        /// update classes in the classifier. You can include more than one positive example file in a call.
        ///
        /// Specify the parameter name by appending `_positive_examples` to the class name. For example,
        /// `goldenretriever_positive_examples` creates the class `goldenretriever`.
        ///
        /// Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels.
        /// The maximum number of images is 10,000 images or 100 MB per .zip file.
        ///
        /// Encode special characters in the file name in UTF-8. (optional)</param>
        /// <param name="negativeExamples">A .zip file of images that do not depict the visual subject of any of the
        /// classes of the new classifier. Must contain a minimum of 10 images.
        ///
        /// Encode special characters in the file name in UTF-8. (optional)</param>
        /// <param name="negativeExamplesFilename">The filename for negativeExamples. (optional)</param>
        /// <returns><see cref="Classifier" />Classifier</returns>
        public DetailedResponse <Classifier> UpdateClassifier(string classifierId, Dictionary <string, System.IO.MemoryStream> positiveExamples = null, System.IO.MemoryStream negativeExamples = null, string negativeExamplesFilename = null)
        {
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("`classifierId` is required for `UpdateClassifier`");
            }
            else
            {
                classifierId = Uri.EscapeDataString(classifierId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <Classifier> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (positiveExamples != null && positiveExamples.Count > 0)
                {
                    foreach (KeyValuePair <string, System.IO.MemoryStream> entry in positiveExamples)
                    {
                        var partName    = string.Format("{0}_positive_examples", entry.Key);
                        var partContent = new ByteArrayContent(entry.Value.ToArray());
                        System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                        System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                        partContent.Headers.ContentType = contentType;
                        formData.Add(partContent, partName, entry.Key + ".zip");
                    }
                }

                if (negativeExamples != null)
                {
                    var negativeExamplesContent = new ByteArrayContent(negativeExamples.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                    negativeExamplesContent.Headers.ContentType = contentType;
                    formData.Add(negativeExamplesContent, "negative_examples", negativeExamplesFilename);
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/classifiers/{classifierId}");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("watson_vision_combined", "v3", "UpdateClassifier"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <Classifier>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <Classifier>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Classify images.
        ///
        /// Classify images with built-in or custom classifiers.
        /// </summary>
        /// <param name="imagesFile">An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size
        /// is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file
        /// names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters
        /// non-ASCII characters.
        ///
        /// You can also include an image with the **url** parameter. (optional)</param>
        /// <param name="imagesFilename">The filename for imagesFile. (optional)</param>
        /// <param name="imagesFileContentType">The content type of imagesFile. (optional)</param>
        /// <param name="url">The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel
        /// density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224
        /// pixels. The maximum image size is 10 MB.
        ///
        /// You can also include images with the **images_file** parameter. (optional)</param>
        /// <param name="threshold">The minimum score a class must have to be displayed in the response. Set the
        /// threshold to `0.0` to return all identified classes. (optional)</param>
        /// <param name="owners">The categories of classifiers to apply. The **classifier_ids** parameter overrides
        /// **owners**, so make sure that **classifier_ids** is empty.
        /// - Use `IBM` to classify against the `default` general classifier. You get the same result if both
        /// **classifier_ids** and **owners** parameters are empty.
        /// - Use `me` to classify against all your custom classifiers. However, for better performance use
        /// **classifier_ids** to specify the specific custom classifiers to apply.
        /// - Use both `IBM` and `me` to analyze the image against both classifier categories. (optional)</param>
        /// <param name="classifierIds">Which classifiers to apply. Overrides the **owners** parameter. You can specify
        /// both custom and built-in classifier IDs. The built-in `default` classifier is used if both
        /// **classifier_ids** and **owners** parameters are empty.
        ///
        /// The following built-in classifier IDs require no training:
        /// - `default`: Returns classes from thousands of general tags.
        /// - `food`: Enhances specificity and accuracy for images of food items.
        /// - `explicit`: Evaluates whether the image might be pornographic. (optional)</param>
        /// <param name="acceptLanguage">The desired language of parts of the response. See the response for details.
        /// (optional, default to en)</param>
        /// <returns><see cref="ClassifiedImages" />ClassifiedImages</returns>
        public DetailedResponse <ClassifiedImages> Classify(System.IO.MemoryStream imagesFile = null, string imagesFilename = null, string imagesFileContentType = null, string url = null, float?threshold = null, List <string> owners = null, List <string> classifierIds = null, string acceptLanguage = null)
        {
            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <ClassifiedImages> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (imagesFile != null)
                {
                    var imagesFileContent = new ByteArrayContent(imagesFile.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(imagesFileContentType, out contentType);
                    imagesFileContent.Headers.ContentType = contentType;
                    formData.Add(imagesFileContent, "images_file", imagesFilename);
                }

                if (url != null)
                {
                    var urlContent = new StringContent(url, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    urlContent.Headers.ContentType = null;
                    formData.Add(urlContent, "url");
                }

                if (threshold != null)
                {
                    var thresholdContent = new StringContent(threshold.ToString(), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    thresholdContent.Headers.ContentType = null;
                    formData.Add(thresholdContent, "threshold");
                }

                if (owners != null)
                {
                    var ownersContent = new StringContent(string.Join(", ", owners.ToArray()), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    ownersContent.Headers.ContentType = null;
                    formData.Add(ownersContent, "owners");
                }

                if (classifierIds != null)
                {
                    var classifierIdsContent = new StringContent(string.Join(", ", classifierIds.ToArray()), Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    classifierIdsContent.Headers.ContentType = null;
                    formData.Add(classifierIdsContent, "classifier_ids");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/classify");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                if (!string.IsNullOrEmpty(acceptLanguage))
                {
                    restRequest.WithHeader("Accept-Language", acceptLanguage);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("watson_vision_combined", "v3", "Classify"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <ClassifiedImages>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <ClassifiedImages>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
 public byte[] ImageToByteArray(Image image)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
     return(ms.ToArray());
 }
Пример #48
0
        /// <summary>
        /// Creates the file "etape.xml" and inserts the first step to it.
        /// </summary>
        /// <param name="expert">The object holding the data.</param>
        /// <returns></returns>
        private static bool FirstAdd(Etape etape)
        {
            try
            {
                XmlWriterSettings wSettings = new XmlWriterSettings();
                wSettings.Indent = true;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                XmlWriter xw = XmlWriter.Create(ms, wSettings);// Write Declaration
                xw.WriteStartDocument();

                // Write the root node
                xw.WriteStartElement("Etapes");

                xw.WriteStartElement("etape");

                xw.WriteStartAttribute("id");
                xw.WriteString("0");
                xw.WriteEndAttribute();
                //----------------
                xw.WriteStartElement("libelle");
                xw.WriteString(etape.getName());
                xw.WriteEndElement();
                //-----------------
                xw.WriteStartElement("description");
                xw.WriteString(etape.getDescription());
                xw.WriteEndElement();
                //-----------------
                xw.WriteStartElement("objets");
                //System.Windows.Forms.MessageBox.Show("Step.Objects.Count: " + etape.getObjectList().Count, "XMLStep.FirstAdd");
                for (int i = 0; i < etape.getObjectList().Count; i++)
                {
                    Object3d obj = etape.getObjectList()[i];

                    xw.WriteStartElement("objet");//<objet>
                    xw.WriteStartAttribute("id");
                    xw.WriteString(obj.getId().ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("nb");
                    xw.WriteString(i.ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartElement("position");//<position>
                    //Transform axis
                    float X, Y, Z;
                    X = obj.getPosition().X;
                    Y = obj.getPosition().Y;
                    Z = obj.getPosition().Z;

                    Helper.TransformAxis(ref X, ref Y, ref Z, Transformation.Translation, true);
                    xw.WriteStartAttribute("x");
                    xw.WriteString((X / translateFactor).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("y");
                    xw.WriteString((Y / translateFactor).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("z");
                    xw.WriteString((zFactor * Z / translateFactor).ToString());
                    xw.WriteEndAttribute();
                    xw.WriteEndElement();             //</position>

                    xw.WriteStartElement("rotation"); //<rotation>
                    //Transform axis
                    X = obj.getRotation().X;
                    Y = obj.getRotation().Y;
                    Z = obj.getRotation().Z;
                    Helper.TransformAxis(ref X, ref Y, ref Z, Transformation.Rotation, true);

                    float   angleRad = Helper.DegreesToRadians(Constante.stableAngle);
                    Vector3 v        = Vector3.Multiply(obj.getRotation(), 1 / angleRad);
                    Vector3 N        = Helper.Normalize(v);
                    //System.Windows.Forms.MessageBox.Show("obj/angle: " + v.ToString() + "\nNorm: " + v1.ToString());

                    angleRad = angleRad / (N.X / v.X);
                    //angle = Helper.RadiansToDegrees(angleRad);
                    angle = Constante.stableAngle;


                    xw.WriteStartAttribute("angle");
                    if (obj.getRotation().X + obj.getRotation().Y + obj.getRotation().Z == 0)
                    {
                        xw.WriteString((0).ToString());
                    }
                    else
                    {
                        xw.WriteString((angle).ToString());
                    }
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("x");
                    xw.WriteString((Helper.RadiansToDegrees(X) / angle).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("y");
                    xw.WriteString((Helper.RadiansToDegrees(Y) / angle).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("z");
                    xw.WriteString((Helper.RadiansToDegrees(Z) / angle).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteEndElement();          //</rotation>

                    xw.WriteStartElement("scale"); //<scale>

                    xw.WriteStartAttribute("x");
                    xw.WriteString((obj.getScale().X *scaleFactor).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("y");
                    xw.WriteString((obj.getScale().Y *scaleFactor).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteStartAttribute("z");
                    xw.WriteString((obj.getScale().Z *scaleFactor).ToString());
                    xw.WriteEndAttribute();

                    xw.WriteEndElement(); //</scale>

                    xw.WriteEndElement(); //</objet>
                }
                xw.WriteEndElement();

                xw.WriteStartElement("procedure");
                xw.WriteString(etape.getprocedure().getId().ToString());
                xw.WriteEndElement();
                //-----------------

                xw.WriteEndElement();

                xw.WriteStartElement("MaxID");
                xw.WriteString("0");
                xw.WriteEndElement();

                // Close the document
                xw.WriteEndDocument();

                // Flush the write
                xw.Flush();

                Byte[] buffer = new Byte[ms.Length];
                buffer = ms.ToArray();
                string xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);

                //File.WriteAllText((Stream)Helper.service.LoadFile("etape.xml", xmlOutput);
                Helper.service.CreateXmlFile("etape.xml", xmlOutput);
            }
            catch (System.IO.FileNotFoundException x) { }
            catch (Exception x) { System.Windows.Forms.MessageBox.Show(x.ToString()); }
            return(true);
        }
Пример #49
0
        public FileResult Export()
        {
            using (MemoryStream stream = new System.IO.MemoryStream())
            {
                var listaprod = SessionHelper.GetObjectFromJson <List <Producto> >(HttpContext.Session, "ProductList");

                //Initialize the PDF document object.
                using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
                {
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
                    pdfDoc.Open();

                    //Add the Image file to the PDF document object.
                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                    // Escribimos el encabezamiento en el documento
                    pdfDoc.Add(new Paragraph("Lista de Productos"));
                    pdfDoc.Add(Chunk.NEWLINE);

                    // Creamos una tabla que contendrá el nombre, apellido y país
                    // de nuestros visitante.
                    PdfPTable tblPrueba = new PdfPTable(7);
                    tblPrueba.WidthPercentage = 100;

                    // Configuramos el título de las columnas de la tabla
                    PdfPCell clId = new PdfPCell(new Phrase("Id", _standardFont));
                    clId.BorderWidth         = 0;
                    clId.BorderWidthBottom   = 0.75f;
                    clId.BackgroundColor     = BaseColor.CYAN;
                    clId.Border              = 1;
                    clId.HorizontalAlignment = 1;


                    PdfPCell clMarca = new PdfPCell(new Phrase("Marca", _standardFont));
                    clMarca.BorderWidth         = 0;
                    clMarca.BorderWidthBottom   = 0.75f;
                    clMarca.BackgroundColor     = BaseColor.CYAN;
                    clMarca.Border              = 1;
                    clMarca.HorizontalAlignment = 1;

                    PdfPCell clCantidad = new PdfPCell(new Phrase("Cantidad", _standardFont));
                    clCantidad.BorderWidth         = 0;
                    clCantidad.BorderWidthBottom   = 0.75f;
                    clCantidad.BackgroundColor     = BaseColor.CYAN;
                    clCantidad.Border              = 1;
                    clCantidad.HorizontalAlignment = 1;



                    PdfPCell clMedida = new PdfPCell(new Phrase("Medida", _standardFont));
                    clMedida.BorderWidth         = 0;
                    clMedida.BorderWidthBottom   = 0.75f;
                    clMedida.BackgroundColor     = BaseColor.CYAN;
                    clMedida.Border              = 1;
                    clMedida.HorizontalAlignment = 1;


                    PdfPCell clUnitario = new PdfPCell(new Phrase("Unitario", _standardFont));
                    clUnitario.BorderWidth         = 0;
                    clUnitario.BorderWidthBottom   = 0.75f;
                    clUnitario.BackgroundColor     = BaseColor.CYAN;
                    clUnitario.Border              = 1;
                    clUnitario.HorizontalAlignment = 1;


                    PdfPCell clBulto = new PdfPCell(new Phrase("Bulto", _standardFont));
                    clBulto.BorderWidth         = 0;
                    clBulto.BorderWidthBottom   = 0.75f;
                    clBulto.BackgroundColor     = BaseColor.CYAN;
                    clBulto.Border              = 0;
                    clBulto.HorizontalAlignment = 1;

                    PdfPCell clEtiqueta = new PdfPCell(new Phrase("Etiqueta", _standardFont));
                    clEtiqueta.BorderWidth         = 0;
                    clEtiqueta.BorderWidthBottom   = 0.75f;
                    clEtiqueta.BackgroundColor     = BaseColor.CYAN;
                    clEtiqueta.Border              = 0;
                    clEtiqueta.HorizontalAlignment = 1;

                    // Añadimos las celdas a la tabla
                    tblPrueba.AddCell(clId);
                    tblPrueba.AddCell(clMarca);
                    tblPrueba.AddCell(clCantidad);
                    tblPrueba.AddCell(clMedida);
                    tblPrueba.AddCell(clUnitario);
                    tblPrueba.AddCell(clBulto);
                    tblPrueba.AddCell(clEtiqueta);

                    // var listaprod = ViewBag.ProductosDB;

                    foreach (var item in listaprod)
                    {
                        // Llenamos la tabla con información
                        clId = new PdfPCell(new Phrase(item.ProdId.ToString(), _standardFont));
                        clId.HorizontalAlignment = 1;

                        clMarca = new PdfPCell(new Phrase(item.ProdMarca, _standardFont));
                        clMarca.HorizontalAlignment = 1;

                        clCantidad = new PdfPCell(new Phrase(item.ProdCantidad.ToString(), _standardFont));
                        clCantidad.HorizontalAlignment = 1;

                        clMedida = new PdfPCell(new Phrase(item.ProdMedida.ToString(), _standardFont));
                        clMedida.HorizontalAlignment = 1;

                        clUnitario = new PdfPCell(new Phrase(item.ProdUnitario.ToString(), _standardFont));
                        clUnitario.HorizontalAlignment = 1;

                        clBulto = new PdfPCell(new Phrase(item.PrdoBulto.ToString(), _standardFont));
                        clBulto.HorizontalAlignment = 1;

                        clEtiqueta = new PdfPCell(new Phrase(item.ProdEtiqueta.ToString(), _standardFont));
                        clEtiqueta.HorizontalAlignment = 1;


                        // Añadimos las celdas a la tabla
                        tblPrueba.AddCell(clId);
                        tblPrueba.AddCell(clMarca);
                        tblPrueba.AddCell(clCantidad);
                        tblPrueba.AddCell(clMedida);
                        tblPrueba.AddCell(clUnitario);
                        tblPrueba.AddCell(clBulto);
                        tblPrueba.AddCell(clEtiqueta);
                    }
                    pdfDoc.Add(tblPrueba);

                    pdfDoc.Close();
                    writer.Close();



                    //Download the PDF file.
                    return(File(stream.ToArray(), "application/pdf", "PdfExportList.pdf"));
                }
            }
        }
Пример #50
0
        /// <summary>
        /// Translate document.
        ///
        /// Submit a document for translation. You can submit the document contents in the `file` parameter, or you can
        /// reference a previously submitted document by document ID.
        /// </summary>
        /// <param name="file">The source file to translate.
        ///
        /// [Supported file
        /// types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats)
        ///
        /// Maximum file size: **20 MB**.</param>
        /// <param name="filename">The filename for file.</param>
        /// <param name="fileContentType">The content type of file. (optional)</param>
        /// <param name="modelId">The model to use for translation. `model_id` or both `source` and `target` are
        /// required. (optional)</param>
        /// <param name="source">Language code that specifies the language of the source document. (optional)</param>
        /// <param name="target">Language code that specifies the target language for translation. (optional)</param>
        /// <param name="documentId">To use a previously submitted document as the source for a new translation, enter
        /// the `document_id` of the document. (optional)</param>
        /// <returns><see cref="DocumentStatus" />DocumentStatus</returns>
        public DetailedResponse <DocumentStatus> TranslateDocument(System.IO.MemoryStream file, string filename, string fileContentType = null, string modelId = null, string source = null, string target = null, string documentId = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException("`file` is required for `TranslateDocument`");
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("`filename` is required for `TranslateDocument`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <DocumentStatus> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file != null)
                {
                    var fileContent = new ByteArrayContent(file.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(fileContentType, out contentType);
                    fileContent.Headers.ContentType = contentType;
                    formData.Add(fileContent, "file", filename);
                }

                if (modelId != null)
                {
                    var modelIdContent = new StringContent(modelId, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    modelIdContent.Headers.ContentType = null;
                    formData.Add(modelIdContent, "model_id");
                }

                if (source != null)
                {
                    var sourceContent = new StringContent(source, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    sourceContent.Headers.ContentType = null;
                    formData.Add(sourceContent, "source");
                }

                if (target != null)
                {
                    var targetContent = new StringContent(target, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    targetContent.Headers.ContentType = null;
                    formData.Add(targetContent, "target");
                }

                if (documentId != null)
                {
                    var documentIdContent = new StringContent(documentId, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    documentIdContent.Headers.ContentType = null;
                    formData.Add(documentIdContent, "document_id");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/documents");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "TranslateDocument"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <DocumentStatus>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <DocumentStatus>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #51
0
    protected void SetandoRel(string formato = null)
    {
        //Report da stimulsoft

        Stimulsoft.Report.StiReport Report = new Stimulsoft.Report.StiReport();
        //Stimulsoft.Report.Web.web.StiWebDesigner st1 = new Stimulsoft.Report.Web.StiWebDesigner();
        //Stimulsoft.Report.Web.StiWebDesigner st1 = new Stimulsoft.Report.Web.StiWebDesigner();
        //Stimulsoft.Report.Web.StiWebDesigner st1 = new Stimulsoft.Report.Web.StiWebDesigner();

        if (Convert.ToString(Request.QueryString["Rel"]) == "frmZurel")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/folhafrequencia.mrt"));
            Report.Compile();
            Report["DiasMes"]         = TotalDiasMes.ToString();
            Report["DiasCumpridos"]   = TotalDiasCumprido.ToString();
            Report["TotalHorasMes"]   = TotalHoraMes.ToString();
            Report["HorasCumpridas"]  = HorasCumpridas;
            Report["HorasRealizadas"] = HorasRealizadas;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmZuxa")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/EspelhoPonto.mrt"));
            Report.Compile();
            Report["DiasMes"]        = TotalDiasMes.ToString();
            Report["DiasCumpridos"]  = TotalDiasCumprido.ToString();
            Report["TotalHorasMes"]  = TotalHoraMes.ToString();
            Report["HorasCumpridas"] = HorasCumpridas.ToString();
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmsitu")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/situacaousuario.mrt"));
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmbco")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/totalhorasdiarias.mrt"));
            Report.Compile();
            //Report["Teste"] = 932;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmbcoHoraMes")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/bancoHoraMes.mrt"));
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmRelacDia")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/relacaopontoDia.mrt"));
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmLocalRegistro")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/LocalRegistro.mrt"));
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmMotivoFalta")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/RelacaoMotivoFalta.mrt"));
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmfca")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/FichaCadastral.mrt"));
            Report.Compile();
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmfi")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/FichaCadastral.mrt"));
            Report.Compile();
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmdesc")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/RelRelacaoRegistroPeriodo.mrt"));
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmfaltaInjust")
        {
            if (RelUtilizado == 0)
            {
                Report.Load(Server.MapPath(@"~/Relatorio/STF/RelDataInjustificada.mrt"));
            }
            else
            {
                Report.Load(Server.MapPath(@"~/Relatorio/STF/RelRegistroAusente.mrt"));
            }
            //o Outro Aqui
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }
        else if (Convert.ToString(Request.QueryString["Rel"]) == "frmAuditRel")
        {
            Report.Load(Server.MapPath(@"~/Relatorio/STF/RelatorioAuditoriaJustificativa.mrt"));
            Report.Compile();
            Report["DTInicio"] = INICIO;
            Report["DTFim"]    = FIM;
        }


        Report.RegData("DatasetPontoFrequencia", ds);

        Report.Render();

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

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/pdf";

        HttpContext.Current.Response.AddHeader("Pontoweb.pdf", "");

        Stimulsoft.Report.Export.StiPdfExportService Export = new Stimulsoft.Report.Export.StiPdfExportService();
        Export.ExportPdf(Report, memStream, Stimulsoft.Report.StiPagesRange.All, 100, 100, false, false, true, true,
                         "", "", Stimulsoft.Report.Export.StiUserAccessPrivileges.All, Stimulsoft.Report.Export.StiPdfEncryptionKeyLength.Bit40, false);

        Response.ContentType = "application/pdf";

        Response.AddHeader("content-disposition", "inline; filename=Pontoweb.pdf");

        Response.BinaryWrite(memStream.ToArray());
    }
Пример #52
0
        private void btnPDF_CiktiAl_Click(object sender, EventArgs e)
        {
            if (dgvOdaDemirbaslari.RowCount > 0)
            {
                using (SaveFileDialog sfd = new SaveFileDialog()
                {
                    Filter = "PDF file|*.pdf", ValidateNames = true
                })
                {
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4);
                        try
                        {
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
                            doc.Open();

                            BaseFont             text = BaseFont.CreateFont("Helvetica", "Cp1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                            iTextSharp.text.Font f    = new iTextSharp.text.Font(text, 16f, 1, BaseColor.RED);
                            Chunk c = new Chunk();
                            c.Font = f;
                            doc.Add(c);

                            Paragraph heading = new Paragraph("FLAMİNGO STOK TAKİP SİSTEMİ \n\n\n", f);
                            heading.Alignment = Element.ALIGN_CENTER;
                            doc.Add(heading);

                            BaseFont             text1 = BaseFont.CreateFont("Helvetica", "Cp1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                            iTextSharp.text.Font f1    = new iTextSharp.text.Font(text1, 12f, 0, BaseColor.BLACK);
                            Chunk c1 = new Chunk();
                            c1.Font = f1;
                            doc.Add(c1);

                            Paragraph p1 = new Paragraph(pdfBilgiGoster, f1);
                            doc.Add(p1);

                            Paragraph p2 = new Paragraph(" ");
                            doc.Add(p2);

                            BaseFont             text2 = BaseFont.CreateFont("Helvetica", "Cp1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                            iTextSharp.text.Font f2    = new iTextSharp.text.Font(text2, 10f, 1, BaseColor.BLACK);
                            Chunk c2 = new Chunk();
                            c2.Font = f2;
                            doc.Add(c2);

                            PdfPTable table = new PdfPTable(dgvOdaDemirbaslari.Columns.Count);

                            for (int j = 0; j < dgvOdaDemirbaslari.Columns.Count; j++)
                            {
                                table.AddCell(new Phrase(dgvOdaDemirbaslari.Columns[j].HeaderText, f2));
                            }

                            table.HeaderRows = 1;

                            BaseFont             text3 = BaseFont.CreateFont("Helvetica", "Cp1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                            iTextSharp.text.Font f3    = new iTextSharp.text.Font(text3, 10f, 0, BaseColor.BLACK);
                            Chunk c3 = new Chunk();
                            c3.Font = f3;
                            doc.Add(c3);

                            for (int i = 0; i < dgvOdaDemirbaslari.Rows.Count; i++)
                            {
                                for (int k = 0; k < dgvOdaDemirbaslari.Columns.Count; k++)
                                {
                                    if (dgvOdaDemirbaslari[k, i].Value != null)
                                    {
                                        table.AddCell(new Phrase(dgvOdaDemirbaslari[k, i].Value.ToString(), f3));
                                    }
                                }
                            }

                            doc.Add(table);

                            byte[]   belge          = ms.ToArray();
                            string[] belgeAdi       = sfd.FileName.Split('\\');
                            string   gercekBelgeAdi = belgeAdi[belgeAdi.Length - 1];
                            belgeAdi       = gercekBelgeAdi.Split('.');
                            gercekBelgeAdi = belgeAdi[0];

                            tblBelgeler Belge = new tblBelgeler();
                            Belge.BelgeAdi = gercekBelgeAdi;
                            Belge.BelgeOlusturulmaTarihi = DateTime.Now.Date;
                            Belge.KullaniciID            = FormGirisYap.kullaniciID;
                            Belge.BelgeYolu = sfd.FileName;
                            Entities.tblBelgeler.Add(Belge);
                            Entities.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Mesaj", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            doc.Close();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("PDF dökümanı oluşturmak için listeleme yapınız!", "Oda Arama", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        public void DownloadPDFFormat()
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("File");
            try
            {
                Document pdfReport = new Document(PageSize.A4, 25, 25, 40, 25);
                System.IO.MemoryStream msReport = new System.IO.MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
                pdfReport.Open();



                string datetime = string.Empty;
                datetime = Convert.ToString(System.DateTime.Now);

                string str = string.Empty;

                if (ddllocation.Text != "")
                {
                    str = ("   Location : " + ddllocation.Text);
                }


                //Create Heading
                Phrase headerPhrase = new Phrase("Monthly Roster Report                                                       ", FontFactory.GetFont("Garamond", 14));

                headerPhrase.Add("                                                     Generated On : ");
                headerPhrase.Add(datetime);
                headerPhrase.Add("                                                                           Searching Parameter  : ");
                headerPhrase.Add(str);



                //Create Heading
                // Phrase headerPhrase = new Phrase("Contractor Report", FontFactory.GetFont("TIMES_ROMAN", 16));
                HeaderFooter header = new HeaderFooter(headerPhrase, false);
                header.Border    = Rectangle.NO_BORDER;
                header.Alignment = Element.ALIGN_CENTER;
                header.Alignment = Element.ALIGN_BOTTOM;
                pdfReport.Header = header;
                pdfReport.Add(headerPhrase);



                // Creates the Table
                PdfPTable ptData = new PdfPTable(gvItemTable.Columns.Count);
                ptData.SpacingBefore       = 8;
                ptData.DefaultCell.Padding = 1;

                float[] headerwidths = new float[gvItemTable.Columns.Count]; // percentage


                headerwidths[0] = 4.2F;
                headerwidths[1] = 4.2F;
                headerwidths[2] = 4.2F;
                headerwidths[3] = 4.2F;
                //headerwidths[4] = 4.2F;
                //headerwidths[5] = 4.2F;
                //headerwidths[6] = 4.2F;
                //headerwidths[7] = 4.2F;
                ////headerwidths[8] = 3.2F;
                ////headerwidths[9] = 3.2F;

                ptData.SetWidths(headerwidths);
                ptData.WidthPercentage = 100;
                ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptData.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;

                //Insert the Table Headers
                for (int intK = 0; intK < gvItemTable.Columns.Count; intK++)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.BorderWidth     = 0.001f;
                    cell.BackgroundColor = new Color(200, 200, 200);
                    cell.BorderColor     = new Color(100, 100, 100);
                    cell.Phrase          = new Phrase(gvItemTable.Columns[intK].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD));
                    ptData.AddCell(cell);
                }

                ptData.HeaderRows = 1;  // this is the end of the table header

                //Insert the Table Data

                for (int intJ = 0; intJ < gvItemTable.Rows.Count; intJ++)
                {
                    for (int intK = 0; intK < gvItemTable.Columns.Count; intK++)
                    {
                        PdfPCell cell = new PdfPCell();
                        cell.BorderWidth     = 0.001f;
                        cell.BorderColor     = new Color(100, 100, 100);
                        cell.BackgroundColor = new Color(250, 250, 250);
                        if (gvItemTable.Rows[intJ].Cells[intK].Text.ToString() != "&nbsp;")
                        {
                            cell.Phrase = new Phrase(gvItemTable.Rows[intJ].Cells[intK].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                        }
                        else
                        {
                            cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                        }
                        ptData.AddCell(cell);
                    }
                }

                //Insert the Table

                pdfReport.Add(ptData);

                //Closes the Report and writes to Memory Stream

                pdfReport.Close();

                //Writes the Memory Stream Data to Response Object
                Response.Clear();
                // Response.AddHeader("content-disposition", string.Format("attachment;filename=" + ConfigurationManager.AppSettings["TxnInfoPdfFile"]));
                Response.AddHeader("content-disposition", string.Format("attachment;filename=testpfd.pdf"));
                Response.Charset     = "";
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(msReport.ToArray());
                Response.End();
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
            }
        }
Пример #54
0
        private FastString GetHtmlParagraph(HtmlTextRenderer renderer)
        {
            FastString sb = new FastString();

            foreach (HtmlTextRenderer.Paragraph paragraph in renderer.Paragraphs)
            {
                foreach (HtmlTextRenderer.Line line in paragraph.Lines)
                {
                    if (sb == null)
                    {
                        sb = new FastString();
                    }
                    sb.Append("<span style=\"");
                    sb.Append("display:block;");
                    if (line.Top + line.Height > renderer.DisplayRect.Bottom)
                    {
                        sb.Append("height:").Append(Math.Max(renderer.DisplayRect.Bottom - line.Top, 0).ToString(HtmlTextRenderer.CultureInfo)).Append("px;");
                    }
                    else
                    {
                        //sb.Append("height:").Append(line.Height.ToString(HtmlTextRenderer.CultureInfo)).Append("px;");
                        if (line.LineSpacing > 0)
                        {
                            sb.Append("margin-bottom:").Append(line.LineSpacing.ToString(HtmlTextRenderer.CultureInfo)).Append("px;");
                        }
                    }
                    sb.Append("overflow:hidden;");
                    sb.Append("line-height:").Append(line.Height.ToString(HtmlTextRenderer.CultureInfo)).Append("px;");
                    if (line.HorzAlign == HorzAlign.Justify)
                    {
                        sb.Append("text-align-last:justify;");
                    }
                    else
                    {
                        sb.Append("white-space:pre;");
                    }
                    sb.Append("\">");
                    HtmlTextRenderer.StyleDescriptor styleDesc = null;
                    foreach (HtmlTextRenderer.Word word in line.Words)
                    {
                        foreach (HtmlTextRenderer.Run run in word.Runs)
                        {
                            if (!run.Style.FullEquals(styleDesc))
                            {
                                if (styleDesc != null)
                                {
                                    styleDesc.ToHtml(sb, true);
                                }
                                styleDesc = run.Style;
                                styleDesc.ToHtml(sb, false);
                            }

                            if (run is HtmlTextRenderer.RunText)
                            {
                                HtmlTextRenderer.RunText runText = run as HtmlTextRenderer.RunText;

                                foreach (char ch in runText.Text)
                                {
                                    switch (ch)
                                    {
                                    case '"':
                                        sb.Append("&quot;");
                                        break;

                                    case '&':
                                        sb.Append("&amp;");
                                        break;

                                    case '<':
                                        sb.Append("&lt;");
                                        break;

                                    case '>':
                                        sb.Append("&gt;");
                                        break;

                                    case '\t':
                                        sb.Append("&Tab;");
                                        break;

                                    default:
                                        sb.Append(ch);
                                        break;
                                    }
                                }
                            }
                            else if (run is HtmlTextRenderer.RunImage)
                            {
                                HtmlTextRenderer.RunImage runImage = run as HtmlTextRenderer.RunImage;

                                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                                {
                                    try
                                    {
                                        float w, h;
                                        using (Bitmap bmp = runImage.GetBitmap(out w, out h))
                                        {
                                            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                                        }
                                        ms.Flush();
                                        sb.Append("<img src=\"data:image/png;base64,").Append(Convert.ToBase64String(ms.ToArray()))
                                        .Append("\" width=\"").Append(w.ToString(HtmlTextRenderer.CultureInfo)).Append("\" height=\"").Append(h.ToString(HtmlTextRenderer.CultureInfo)).Append("\"/>");
                                    }
                                    catch (Exception /*e*/)
                                    {
                                    }
                                }
                            }
                            //run.ToHtml(sb, true);
                        }
                    }
                    if (styleDesc != null)
                    {
                        styleDesc.ToHtml(sb, true);
                    }
                    else
                    {
                        sb.Append("<br/>");
                    }
                    sb.Append("</span>");
                }
            }
            return(sb);
        }
        public static byte[] GenerateExcel(this IEnumerable <Car> cars, string password, string imagePath)
        {
            int count = 0;
            int line  = 2;
            int col   = 0;


            FileInfo     fileInfo  = new FileInfo(@"C:\Excel.xlsx");
            ExcelPackage xlPackage = new ExcelPackage(fileInfo);

            xlPackage.Workbook.Protection.SetPassword(password);

            var sheet = xlPackage.Workbook.Worksheets[DateTime.Now.ToString("yyyyMMdd")];

            if (sheet == null)
            {
                sheet = xlPackage.Workbook.Worksheets.Add(DateTime.Now.ToString("yyyyMMdd"));
            }

            Bitmap bitmap = new Bitmap(imagePath);

            if (bitmap != null)
            {
                int          Height = 100;
                int          Width  = 50;
                ExcelPicture pic    = sheet.Drawings.AddPicture("Sample", bitmap);
                pic.SetPosition(0, 0, 0, 0);
                pic.SetSize(Height, Width);
            }
            var cells = sheet.Cells;

            //title
            cells[4, 1].Value = "Cars";

            #region WriteToExcel
            line = 6;

            foreach (Car car in cars)
            {
                count = 0;
                col   = 0;

                cells[line, ++col].Value = car.Brand;
                cells[line, ++col].Value = car.Model;
                cells[line, ++col].Value = car.VIN;
                cells[line, ++col].Value = car.Showroom?.Name;

                line++;
            }
            #endregion

            #region WriteHeaderToExcel
            count = 1;
            cells[5, count++].Value = "Brand";
            cells[5, count++].Value = "Name";
            cells[5, count++].Value = "VIN";
            cells[5, count++].Value = "Showroom";
            #endregion

            //style
            using (var range = cells[1, 1, 5, count])
            {
                range.Style.Font.Bold = true;
            }

            xlPackage.Encryption.Password = password;            //set password for Excel File

            System.IO.MemoryStream output = new System.IO.MemoryStream(xlPackage.GetAsByteArray());

            return(output.ToArray());
        }
Пример #56
0
        public static object ExportToExcel(string model, string data, string title)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                /* Create the worksheet. */

                SpreadsheetDocument spreadsheet = Excel.CreateWorkbook(stream);
                Excel.AddBasicStyles(spreadsheet);
                Excel.AddAdditionalStyles(spreadsheet);
                Excel.AddWorksheet(spreadsheet, title);
                Worksheet worksheet = spreadsheet.WorkbookPart.WorksheetParts.First().Worksheet;


                /* Get the information needed for the worksheet */

                var modelObject = JsonConvert.DeserializeObject <dynamic>(model);
                var dataObject  = JsonConvert.DeserializeObject <dynamic>(data);


                /* Add the column titles to the worksheet. */

                // For each column...
                for (int mdx = 0; mdx < modelObject.Count; mdx++)
                {
                    // If the column has a title, use it.  Otherwise, use the field name.
                    Excel.SetColumnHeadingValue(spreadsheet, worksheet, Convert.ToUInt32(mdx + 1),
                                                (modelObject[mdx].title == null || modelObject[mdx].title == "&nbsp;")
                            ? modelObject[mdx].field.ToString()
                            : modelObject[mdx].title.ToString(),
                                                false, false);

                    // Is there are column width defined?
                    Excel.SetColumnWidth(worksheet, mdx + 1, modelObject[mdx].width != null
                        ? int.Parse(LeadingInteger.Match(modelObject[mdx].width.ToString()).Value) / 4
                        : 25);
                }


                /* Add the data to the worksheet. */

                // For each row of data...
                for (int idx = 0; idx < dataObject.Count; idx++)
                {
                    // For each column...
                    for (int mdx = 0; mdx < modelObject.Count; mdx++)
                    {
                        // Set the field value in the spreadsheet for the current row and column.
                        Excel.SetCellValue(spreadsheet, worksheet, Convert.ToUInt32(mdx + 1), Convert.ToUInt32(idx + 2),
                                           dataObject[idx][modelObject[mdx].field.ToString()].ToString(),
                                           false, false);
                    }
                }


                /* Save the worksheet and store it in Session using the spreadsheet title. */

                worksheet.Save();
                spreadsheet.Close();
                byte[] file = stream.ToArray();
                HttpContext.Current.Session[title] = file;
            }

            return(new { success = true });
        }
Пример #57
0
        /// <summary>
        /// Use this method to write XMP data to a new PDF
        /// </summary>
        /// <param name="writer"></param>
        protected void CreateXmpMetadata(iTextSharp.text.pdf.PdfWriter writer, string title, List <string> subjects = null)
        {
            if (subjects == null)
            {
                subjects = new List <string>();
            }

            // Set up the buffer to hold the XMP metadata
            byte[] buffer             = new byte[65536];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, true);

            try
            {
                // XMP supports a number of different schemas, which are made available by iTextSharp.
                // Here, the Dublin Core schema is chosen.
                iTextSharp.text.xml.xmp.XmpSchema dc = new iTextSharp.text.xml.xmp.DublinCoreSchema();

                // Add Dublin Core attributes
                iTextSharp.text.xml.xmp.LangAlt ttl = new iTextSharp.text.xml.xmp.LangAlt();
                ttl.Add("x-default", title);
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.TITLE, ttl);

                // Dublin Core allows multiple authors, so we create an XmpArray to hold the values
                iTextSharp.text.xml.xmp.XmpArray author = new iTextSharp.text.xml.xmp.XmpArray(iTextSharp.text.xml.xmp.XmpArray.ORDERED);
                author.Add("Lietuva 2.0");
                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.CREATOR, author);

                // Multiple subjects are also possible, so another XmpArray is used
                iTextSharp.text.xml.xmp.XmpArray subject = new iTextSharp.text.xml.xmp.XmpArray(iTextSharp.text.xml.xmp.XmpArray.UNORDERED);
                foreach (var sbj in subjects)
                {
                    subject.Add(sbj);
                }

                dc.SetProperty(iTextSharp.text.xml.xmp.DublinCoreSchema.SUBJECT, subject);

                // Create an XmpWriter using the MemoryStream defined earlier
                iTextSharp.text.xml.xmp.XmpWriter xmp = new iTextSharp.text.xml.xmp.XmpWriter(ms);
                xmp.AddRdfDescription(dc); // Add the completed metadata definition to the XmpWriter
                xmp.Close();               // This flushes the XMP metadata into the buffer

                //---------------------------------------------------------------------------------
                // Shrink the buffer to the correct size (discard empty elements of the byte array)
                int bufsize  = buffer.Length;
                int bufcount = 0;
                foreach (byte b in buffer)
                {
                    if (b == 0)
                    {
                        break;
                    }
                    bufcount++;
                }
                System.IO.MemoryStream ms2 = new System.IO.MemoryStream(buffer, 0, bufcount);
                buffer = ms2.ToArray();
                //---------------------------------------------------------------------------------

                // Add all of the XMP metadata to the PDF doc that we're building
                writer.XmpMetadata = buffer;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
                ms.Dispose();
            }
        }
Пример #58
0
    private void CreateCheckCodeImage(string strCheckCode)
    {
        if (strCheckCode == null || strCheckCode.Trim() == String.Empty)
        {
            return;
        }

        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((strCheckCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //生成随机生成器



            Random random = new Random();

            //清空图片背景色



            g.Clear(Color.Azure);

            ////画图片的背景噪音线



            //for (int i = 0; i < 25; i++)
            //{
            //    int x1 = random.Next(image.Width);
            //    int x2 = random.Next(image.Width);
            //    int y1 = random.Next(image.Height);
            //    int y2 = random.Next(image.Height);

            //    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            //}

            Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(strCheckCode, font, brush, 2, 2);

            ////画图片的前景噪音点



            //for (int i = 0; i < 100; i++)
            //{
            //    int x = random.Next(image.Width);
            //    int y = random.Next(image.Height);

            //    image.SetPixel(x, y, Color.FromArgb(random.Next()));
            //}

            //画图片的边框线



            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
Пример #59
0
        void ExecuteWithAbi(string supportedAbis, string apkInputPath, string apkOutputPath)
        {
            ArchiveFileList files = new ArchiveFileList();

            if (apkInputPath != null)
            {
                File.Copy(apkInputPath, apkOutputPath + "new", overwrite: true);
            }
            using (var apk = new ZipArchiveEx(apkOutputPath + "new", apkInputPath != null ? FileMode.Open : FileMode.Create)) {
                apk.Archive.AddEntry("NOTICE",
                                     Assembly.GetExecutingAssembly().GetManifestResourceStream("NOTICE.txt"));

                // Add classes.dx
                apk.Archive.AddFiles(DalvikClasses, useFileDirectories: false);

                if (EmbedAssemblies && !BundleAssemblies)
                {
                    AddAssemblies(apk);
                }

                AddEnvironment(apk);
                AddRuntimeLibraries(apk, supportedAbis);
                apk.Flush();
                AddNativeLibraries(files, supportedAbis);
                apk.Flush();
                AddAdditionalNativeLibraries(files, supportedAbis);
                apk.Flush();
                AddNativeLibrariesFromAssemblies(apk, supportedAbis);
                apk.Flush();

                foreach (ITaskItem typemap in TypeMappings)
                {
                    apk.Archive.AddFile(typemap.ItemSpec, Path.GetFileName(typemap.ItemSpec), compressionMethod: CompressionMethod.Store);
                }

                int count = 0;
                foreach (var file in files)
                {
                    var item = Path.Combine(file.Item2, Path.GetFileName(file.Item1))
                               .Replace(Path.DirectorySeparatorChar, '/');
                    if (apk.Archive.ContainsEntry(item))
                    {
                        Log.LogWarning(null, "XA4301", null, file.Item1, 0, 0, 0, 0, "Apk already contains the item {0}; ignoring.", item);
                        continue;
                    }
                    apk.Archive.AddFile(file.Item1, item);
                    count++;
                    if (count == ZipArchiveEx.ZipFlushLimit)
                    {
                        apk.Flush();
                        count = 0;
                    }
                }
                if (_Debug)
                {
                    AddGdbservers(apk, files, supportedAbis, debugServer);
                }

                var jarFiles = (JavaSourceFiles != null) ? JavaSourceFiles.Where(f => f.ItemSpec.EndsWith(".jar")) : null;
                if (jarFiles != null && JavaLibraries != null)
                {
                    jarFiles = jarFiles.Concat(JavaLibraries);
                }
                else if (JavaLibraries != null)
                {
                    jarFiles = JavaLibraries;
                }

                var libraryProjectJars = MonoAndroidHelper.ExpandFiles(LibraryProjectJars)
                                         .Where(jar => !MonoAndroidHelper.IsEmbeddedReferenceJar(jar));

                var jarFilePaths = libraryProjectJars.Concat(jarFiles != null ? jarFiles.Select(j => j.ItemSpec) : Enumerable.Empty <string> ());
                jarFilePaths = MonoAndroidHelper.DistinctFilesByContent(jarFilePaths);

                count = 0;
                foreach (var jarFile in jarFilePaths)
                {
                    using (var jar = ZipArchive.Open(File.OpenRead(jarFile))) {
                        foreach (var jarItem in jar.Where(ze => !ze.IsDirectory && !ze.FullName.StartsWith("META-INF") && !ze.FullName.EndsWith(".class") && !ze.FullName.EndsWith(".java") && !ze.FullName.EndsWith("MANIFEST.MF")))
                        {
                            byte [] data;
                            using (var d = new System.IO.MemoryStream()) {
                                jarItem.Extract(d);
                                data = d.ToArray();
                            }
                            if (apk.Archive.Any(e => e.FullName == jarItem.FullName))
                            {
                                Log.LogMessage("Warning: failed to add jar entry {0} from {1}: the same file already exists in the apk", jarItem.FullName, Path.GetFileName(jarFile));
                            }
                            else
                            {
                                apk.Archive.AddEntry(data, jarItem.FullName);
                            }
                        }
                    }
                    count++;
                    if (count == ZipArchiveEx.ZipFlushLimit)
                    {
                        apk.Flush();
                        count = 0;
                    }
                }
                if (StubApplicationDataFile != null && File.Exists(StubApplicationDataFile))
                {
                    apk.Archive.AddFile(StubApplicationDataFile, Path.GetFileName(StubApplicationDataFile));
                }
            }
            MonoAndroidHelper.CopyIfZipChanged(apkOutputPath + "new", apkOutputPath);
            File.Delete(apkOutputPath + "new");
        }
        public static byte[] GenerateExcel(this IEnumerable <Showroom> showrooms, string password, string imagePath)
        {
            int count = 0;
            int line  = 2;
            int col   = 0;


            FileInfo     fileInfo  = new FileInfo(@"C:\Excel.xlsx");
            ExcelPackage xlPackage = new ExcelPackage(fileInfo);

            xlPackage.Workbook.Protection.SetPassword(password);

            var sheet = xlPackage.Workbook.Worksheets[DateTime.Now.ToString("yyyyMMdd")];

            if (sheet == null)
            {
                sheet = xlPackage.Workbook.Worksheets.Add(DateTime.Now.ToString("yyyyMMdd"));
            }

            Bitmap bitmap = new Bitmap(imagePath);

            if (bitmap != null)
            {
                int          Height = 100;
                int          Width  = 50;
                ExcelPicture pic    = sheet.Drawings.AddPicture("Sample", bitmap);
                pic.SetPosition(0, 0, 0, 0);
                pic.SetSize(Height, Width);
            }
            var cells = sheet.Cells;

            //title
            cells[4, 1].Value = "Showrooms";

            int maxCarsFinal = 0;

            #region SetMaxForFields
            foreach (Showroom showroom in showrooms)
            {
                int k = 0;

                if (showroom.Cars != null)
                {
                    if (maxCarsFinal < showroom.Cars.Count)
                    {
                        maxCarsFinal = showroom.Cars.Count;
                    }
                }
                k++;
            }
            #endregion

            #region WriteToExcel
            line = 6;

            foreach (Showroom showroom in showrooms)
            {
                col   = 0;
                count = 0;

                cells[line, ++col].Value = showroom.Name;

                if (showroom.Cars != null)
                {
                    foreach (var car in showroom.Cars)
                    {
                        count++;
                        string displayValue = "Brand: " + car.Brand + ", Model:" + car.Model + ", VIN: " + car.VIN;
                        cells[line, col + count].Value = displayValue;
                    }
                }

                line++;
            }
            #endregion

            count = 1;
            #region WriteHeaderToExcel
            cells[5, count++].Value = "Name";
            for (int j = 0; j < maxCarsFinal; j++)
            {
                cells[5, count++].Value = "Car " + (j + 1);
            }
            #endregion

            //style
            using (var range = cells[1, 1, 5, count])
            {
                range.Style.Font.Bold = true;
            }


            xlPackage.Encryption.Password = password;            //set password for Excel File

            System.IO.MemoryStream output = new System.IO.MemoryStream(xlPackage.GetAsByteArray());

            return(output.ToArray());
        }