예제 #1
1
파일: Crypto.cs 프로젝트: oozcitak/RebarPos
 public static string Encrypt(string plainText, string passPhrase)
 {
     // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
     // so that the same Salt and IV values can be used when decrypting.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
     var keyBytes = password.GetBytes(Keysize / 8);
     using (var symmetricKey = new RijndaelManaged())
     {
         symmetricKey.BlockSize = 256;
         symmetricKey.Mode = CipherMode.CBC;
         symmetricKey.Padding = PaddingMode.PKCS7;
         using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
         {
             using (var memoryStream = new MemoryStream())
             {
                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                     cryptoStream.FlushFinalBlock();
                     // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
예제 #2
1
파일: Crypto.cs 프로젝트: oozcitak/RebarPos
        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 256;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
예제 #3
1
 protected static string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
예제 #4
1
파일: Crypto.cs 프로젝트: ssaporta/reports
 public string Decrypt(string strEncryptedText)
 {
     if (strEncryptedText == null || strEncryptedText.Equals(""))
         return strEncryptedText;
     string strDecryptedText = null;
     RijndaelManaged rijndael = new RijndaelManaged();
     ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
     byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText);
     MemoryStream memStream = new MemoryStream(byteEncryptedText);
     CryptoStream decryptStream = null;
     try
     {
         decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
         byte[] byteDecryptedText = new byte[byteEncryptedText.Length];
         int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length);
         strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount);
     }
     finally
     {
         if (rijndael != null) rijndael.Clear();
         if (decryptor != null) decryptor.Dispose();
         if (memStream != null) memStream.Close();
         if (decryptStream != null) decryptStream.Close();
     }
     if (UseSalt)
         strDecryptedText = strDecryptedText.Substring(8);
     return strDecryptedText;
 }
예제 #5
1
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
예제 #6
1
파일: CryptHelper.cs 프로젝트: MrNor/WxMp
        public static string Encode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] bytes = Encoding.UTF8.GetBytes(str);

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            stream2.FlushFinalBlock();

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())
            {

                builder.AppendFormat("{0:X2}", num);

            }

            stream.Close();

            return builder.ToString();
        }
예제 #7
0
        /// <summary>
        ///     Gets the name of the first model on a CGFX file.
        ///     Returns null if the file doesn't contain any model.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string getName(MemoryStream data)
        {
            BinaryReader input = new BinaryReader(data);

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

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

            if (models.Count > 0)
            {
                data.Seek(models[0].dataOffset + 0xc, SeekOrigin.Begin);
                string name = IOUtils.readString(input, getRelativeOffset(input));
                data.Close();
                return name;
            }
            else
            {
                data.Close();
                return null;
            }
        }
예제 #8
0
        public static bool SaveSettingsFile(PluginSettingsBase settings, Type type, string filename)
        {
            MemoryStream ms = null;
            FileStream fs = null;
            XmlSerializer xs = null;
            try
            {
                ms = new MemoryStream();
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write);

                xs = new XmlSerializer(type);
                xs.Serialize(ms, settings);
                ms.Seek(0, SeekOrigin.Begin);
                fs.Write(ms.ToArray(), 0, (int)ms.Length);
                ms.Close();
                fs.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (ms != null) ms.Close();
                if (fs != null) fs.Close();
            }
        }
예제 #9
0
 /// <summary>
 /// Compresses an array of bytes and stores the result in a new array of bytes.
 /// </summary>
 /// <param name="uncompressed">The uncompressed buffer.</param>
 /// <param name="compressed">An array of bytes where the compressed input will be stored.</param>
 /// <remarks>
 /// The compressed input is passed back to the calling method as an <b>out</b>
 /// parameter. That means that the calling method doesn't need to initialize the
 /// compressed buffer.  
 /// </remarks>
 /// <exception cref="ArgumentNullException">
 /// Thrown if the uncompressed input buffer is empty or null.
 /// </exception>
 /// <exception cref="CWZipException">
 /// Thrown if a problem is encountered during the compression process.
 /// </exception>
 public static void CompressBuffer(byte[] uncompressed, out byte[] compressed)
 {
     if ((uncompressed == null) || (uncompressed.Length == 0))
     {
         throw new ArgumentNullException("uncompressed", "The uncompressed input buffer cannot be null or empty.");
     }
     MemoryStream ms = null;
     compressed = null;
     try
     {
         ms = new MemoryStream();
         ZipOutputStream zip = new ZipOutputStream(ms);
         zip.SetLevel(compressionLevel);
         ZipEntry entry = new ZipEntry("1");
         zip.PutNextEntry(entry);
         zip.Write(uncompressed, 0, uncompressed.Length);
         zip.Finish();
         ms.Position = 0;
         compressed = ms.ToArray();
         ms.Close();
     }
     catch (Exception e)
     {
         if (ms != null)
         {
             ms.Close();
         }
         throw new CWZipException(e.Message);
     }
     finally
     {
         ms = null;
         GC.Collect();
     }
 }
        protected static void LoadDataInToWorkSheet(MemoryStream stream, ExcelFile sheet, DataFileFormat fileFormat)
        {
            if (fileFormat == DataFileFormat.excel)
            {
                sheet.LoadXls(stream);
                stream.Close();
                return;
            }

            File.WriteAllBytes(@"C:\Test.csv", stream.ToArray());
            sheet.LoadCsv(stream, CsvType.CommaDelimited);
            stream.Close();
        }
예제 #11
0
        public static void SendFileInfo()
        {

            // Получаем тип и расширение файла
            fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);

            // Получаем длину файла
            fileDet.FILESIZE = fs.Length;

            XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
            MemoryStream stream = new MemoryStream();

            // Сериализуем объект
            fileSerializer.Serialize(stream, fileDet);

            // Считываем поток в байты
            stream.Position = 0;
            Byte[] bytes = new Byte[stream.Length];
            stream.Read(bytes, 0, Convert.ToInt32(stream.Length));

            Console.WriteLine("Отправка деталей файла...");

            // Отправляем информацию о файле
            sender.Send(bytes, bytes.Length, endPoint);
            stream.Close();

        }
예제 #12
0
 public static byte[] Desencriptar(byte[] mensajeEncriptado,
     SymmetricAlgorithm algoritmo)
 {
     int numeroBytesDesencriptados = 0;
     // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos
     // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa.
     // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor.
     byte[] mensajeDesencriptado = new
     byte[mensajeEncriptado.Length];
     // Crear una ICryptoTransform que puede ser usada para desencriptar datos
     ICryptoTransform desencriptador =
         algoritmo.CreateDecryptor();
     // Procedemos a descifrar el mensaje
     MemoryStream memoryStream = new
     MemoryStream(mensajeEncriptado);
     // Creamos el CryptoStream
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         desencriptador, CryptoStreamMode.Read);
     // Decrypting data and get the count of plain text bytes.
     numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length);
     // Liberamos recursos.
     memoryStream.Close();
     cryptoStream.Close();
     return mensajeDesencriptado;
 }
        public static void Run()
        {
            // ExStart:ConvertPageRegionToDOM         
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document document = new Document( dataDir + "AddImage.pdf");
            // Get rectangle of particular page region
            Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125);
            // Set CropBox value as per rectangle of desired page region
            document.Pages[1].CropBox = pageRect;
            // Save cropped document into stream
            MemoryStream ms = new MemoryStream();
            document.Save(ms);
            // Open cropped PDF document and convert to image
            document = new Document(ms);
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create PNG device with specified attributes
            PngDevice pngDevice = new PngDevice(resolution);
            dataDir = dataDir + "ConvertPageRegionToDOM_out.png";
            // Convert a particular page and save the image to stream
            pngDevice.Process(document.Pages[1], dataDir);
            ms.Close();
            // ExEnd:ConvertPageRegionToDOM   
            Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); 
        }
 public void Read(byte[] aBuffer, uint aSize)
 {
   MemoryStream ms = new MemoryStream(aBuffer,true);
   ms.Write(iBuffer,(int)iOffset,(int)aSize);
   iOffset+=aSize;
   ms.Close();
 }
예제 #15
0
		private void WriteTagContainer(TagContainer tagContainer)
		{
			Stream dataStream = null;
			Stream tagStream = null;
			try
			{
				dataStream = new MemoryStream(m_AudioData);
				tagStream = new MemoryStream(64000);

				// Write the content to a byte stream.
				m_Controller.Write(tagContainer, dataStream, tagStream);
			}
			finally
			{
				if (dataStream != null)
				{
					dataStream.Close();
					dataStream.Dispose();
				}

				if (tagStream != null)
				{
					tagStream.Close();
					tagStream.Dispose();
				}
			}
		}
예제 #16
0
 public override byte[] CreateImage(out string validataCode)
 {
     Bitmap bitmap;
     string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
     GetRandom(formatString, this.ValidataCodeLength, out validataCode);
     MemoryStream stream = new MemoryStream();
     AnimatedGifEncoder encoder = new AnimatedGifEncoder();
     encoder.Start();
     encoder.SetDelay(1);
     encoder.SetRepeat(0);
     for (int i = 0; i < 3; i++)
     {
         this.SplitCode(validataCode);
         this.ImageBmp(out bitmap, validataCode);
         bitmap.Save(stream, ImageFormat.Png);
         encoder.AddFrame(Image.FromStream(stream));
         stream = new MemoryStream();
         bitmap.Dispose();
     }
     encoder.OutPut(ref stream);
     bitmap = null;
     stream.Close();
     stream.Dispose();
     return stream.GetBuffer();
 }
		public Constants.LoginStatus logon(User user)
		{
			Constants.LoginStatus retval = Constants.LoginStatus.STATUS_SERVERNOTREACHED;
			byte[] message = new byte[Constants.WRITEBUFFSIZE];
			byte[] reply;
			MemoryStream stream = new MemoryStream(message);

			try
			{
				//Serialize data in memory so you can send them as a continuous stream
				BinaryFormatter serializer = new BinaryFormatter();
				
				NetLib.insertEntropyHeader(serializer, stream);

				serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGIN);
				serializer.Serialize(stream, user.ringsInfo[0].ring.ringID);
				serializer.Serialize(stream, user.ringsInfo[0].userName);
				serializer.Serialize(stream, user.ringsInfo[0].password);
				serializer.Serialize(stream, user.node.syncCommunicationPoint);
				reply = NetLib.communicate(Constants.SERVER2,message, true);
				stream.Close();
				stream = new MemoryStream(reply);
				NetLib.bypassEntropyHeader(serializer, stream);
				Constants.MessageTypes replyMsg = (Constants.MessageTypes)serializer.Deserialize(stream);

				switch(replyMsg)
				{
					case Constants.MessageTypes.MSG_OK:
						ulong sessionID = (ulong)serializer.Deserialize(stream);
						uint numRings = (uint)serializer.Deserialize(stream);
						uint ringID;
						Ring ring;
						for(uint ringCounter = 0; ringCounter < numRings; ringCounter++)
						{
							LordInfo lordInfo = (LordInfo)serializer.Deserialize(stream);
							ring = RingInfo.findRingByID(user.ringsInfo, lordInfo.ringID);
							ring.lords = lordInfo.lords;
						}
						
						user.loggedIn = true;
						retval = Constants.LoginStatus.STATUS_LOGGEDIN;
						break;
					case Constants.MessageTypes.MSG_NOTAMEMBER:
						retval = Constants.LoginStatus.STATUS_NOTAMEMBER;
						break;
					case Constants.MessageTypes.MSG_ALREADYSIGNEDIN:
						retval = Constants.LoginStatus.STATUS_ALREADYSIGNEDIN;
						break;
					default:
						break;
				}
			}
			catch (Exception e)
			{
				
				int x = 2;
			}

			return retval;
		}
예제 #18
0
        public override void LaunchEditor(FileSystem fs, File file)
        {
            var data = file.GetData();

            var ms = new MemoryStream(data);
            var modelFile = new ModelFile();
            try
            {
                modelFile.Open(ms);
            }
            finally
            {
                ms.Close();
            }

            if (modelFile.EmbeddedTextureFile != null)
            {
                ShowForm(file, modelFile.EmbeddedTextureFile);
            }
            else
            {
                MessageBox.Show("There are no embedded textures in the selected model file to edit.", "Edit",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        public static void Run()
        {
            // ExStart:ConvertMemoryStreamImageToPdf
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_TechnicalArticles();

            // Instantiate Pdf instance by calling its empty constructor
            Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
            // Add a section into the pdf document
            Aspose.Pdf.Generator.Section sec = pdf1.Sections.Add();

            // Create a FileStream object to read the imag file
            FileStream fs = File.OpenRead(dataDir + "aspose-logo.jpg");
            // Read the image into Byte array
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);

            // Create a MemoryStream object from image Byte array
            MemoryStream ms = new MemoryStream(data);
            // Create an image object in the section 
            Aspose.Pdf.Generator.Image imageht = new Aspose.Pdf.Generator.Image(sec);
            // Set the type of image using ImageFileType enumeration
            imageht.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg;

            // Specify the image source as MemoryStream
            imageht.ImageInfo.ImageStream = ms;
            // Add image object into the Paragraphs collection of the section
            sec.Paragraphs.Add(imageht);

            // Save the Pdf
            pdf1.Save(dataDir + "ConvertMemoryStreamImageToPdf_out.pdf");
            // Close the MemoryStream Object
            ms.Close();
            // ExEnd:ConvertMemoryStreamImageToPdf           
        }
예제 #20
0
파일: ImageUpload.cs 프로젝트: aj-hc/SY
 /// <summary>  
 /// 是否允许  
 /// </summary>  
 public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx)
 {
     int fileLen = oFile.ContentLength;
     byte[] imgArray = new byte[fileLen];
     oFile.InputStream.Read(imgArray, 0, fileLen);
     MemoryStream ms = new MemoryStream(imgArray);
     System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
     string fileclass = "";
     byte buffer;
     try
     {
         buffer = br.ReadByte();
         fileclass = buffer.ToString();
         buffer = br.ReadByte();
         fileclass += buffer.ToString();
     }
     catch { }
     br.Close();
     ms.Close();
     foreach (FileExtension fe in fileEx)
     {
         if (Int32.Parse(fileclass) == (int)fe) return true;
     }
     return false;
 }
        public static string Decrypt(string TextToBeDecrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            string Password = "******";
            string DecryptedData;

            try
            {
                byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

                byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

                MemoryStream memoryStream = new MemoryStream(EncryptedData);
                //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

                byte[] PlainText = new byte[EncryptedData.Length];
                int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            }
            catch
            {
                DecryptedData = TextToBeDecrypted;
            }
            return DecryptedData;
        }
예제 #22
0
        public MFTestResults ObjectDisposed()
        {
            MemoryStream ms = new MemoryStream();
            ms.Close();

            MFTestResults result = MFTestResults.Pass;
            try
            {
                try
                {
                    long position = ms.Position;
                    result = MFTestResults.Fail;
                    Log.Exception("Expected ObjectDisposedException, but got position " + position);
                }
                catch (ObjectDisposedException) { /*Pass Case */ }

                try
                {
                    ms.Position = 0;
                    result = MFTestResults.Fail;
                    Log.Exception("Expected ObjectDisposedException, but set position");
                }
                catch (ObjectDisposedException) { /*Pass Case */ }
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected exception: " + ex.Message);
                result = MFTestResults.Fail;
            }

            return result;
        }
예제 #23
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherText">Text to be decrypted</param>
        /// <param name="Password">Password to decrypt with</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string CipherText, string Password,
            string Salt = "Kosher", string HashAlgorithm = "SHA1",
            int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
            int KeySize = 256)
        {
            if (string.IsNullOrEmpty(CipherText))
                return "";
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
            byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int ByteCount = 0;
            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {

                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
예제 #24
0
        private static IEnumerable<byte> MakeWaveHeader(WaveProcessor Wave)
        {
            MemoryStream fs = new MemoryStream();

            BinaryWriter bw = new BinaryWriter(fs);

            fs.Position = 0;
            bw.Write(new[] { 'R', 'I', 'F', 'F' });

            bw.Write(Wave.Length);

            bw.Write(new[] { 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ' });

            bw.Write(16);

            bw.Write((short)1);
            bw.Write(Wave.Channels);

            bw.Write(Wave.SampleRate);

            bw.Write((Wave.SampleRate * ((Wave.BitsPerSample * Wave.Channels) / 8)));

            bw.Write((short)((Wave.BitsPerSample * Wave.Channels) / 8));

            bw.Write(Wave.BitsPerSample);

            bw.Write(new[] { 'd', 'a', 't', 'a' });
            bw.Write(Wave.DataLength);

            bw.Close();
            Byte[] Result = fs.ToArray();
            fs.Close();

            return Result;
        }
예제 #25
0
        public ManufacturersForm(GXManufacturerCollection manufacturers, string selectedManufacturer)
        {
            InitializeComponent();
            NameCH.Width = -2;
            UpdateValues();
            InactivityModeTB.Enabled = StartProtocolTB.Enabled = NameTB.Enabled = ManufacturerIdTB.Enabled = UseLNCB.Enabled = UseIEC47CB.Enabled = false;
            ManufacturersOriginal = manufacturers;

            //Create clone from original items.
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, manufacturers);
            ms.Position = 0;
            Manufacturers = (GXManufacturerCollection)bf.Deserialize(ms);
            ms.Close();
            bool bSelected = false;
            foreach (GXManufacturer it in Manufacturers)
            {
                if (!it.Removed)
                {
                    ListViewItem item = AddManufacturer(it);
                    if (it.Identification == selectedManufacturer)
                    {
                        bSelected = item.Selected = true;
                    }
                }
            }
            //Select first item
            if (ManufacturersList.Items.Count != 0 && !bSelected)
            {
                ManufacturersList.Items[0].Selected = true;
            }
        }
예제 #26
0
파일: CryptHelper.cs 프로젝트: MrNor/WxMp
        public static string Decode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] buffer = new byte[str.Length / 2];

            for (int i = 0; i < (str.Length / 2); i++)
            {

                int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);

                buffer[i] = (byte)num2;

            }

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);

            stream2.Write(buffer, 0, buffer.Length);

            stream2.FlushFinalBlock();

            stream.Close();

            return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBox3.Text = "";

            try
            {
                object result = context.Execute(textBox1.Text);

                using (MemoryStream ms = new MemoryStream())
                {
                    TextWriter writer = new StreamWriter(ms);
                    writer.WriteLine(result);
                    writer.Flush();
                    ms.Position = 0;

                    StreamReader reader = new StreamReader(ms);
                    if (textBox3.Text.Length > 0)
                        textBox3.Text += "\n";

                    textBox3.Text += reader.ReadToEnd();
                    ms.Close();
                }
            }
            catch (Exception ex)
            {
                Kernel.Error.WriteLine(ex);
            }
        }
예제 #28
0
 public static void Main()
 {
     // The path to the documents directory.
     string dataDir = Path.GetFullPath("../../../Data/");
     // instantiate PdfPageEditor class to get particular page region
     Aspose.Pdf.Facades.PdfPageEditor editor = new Aspose.Pdf.Facades.PdfPageEditor();
     // bind the source PDF file
     editor.BindPdf(dataDir + "SampleInput.pdf");
     // move the origin of PDF file to particular point
     editor.MovePosition(0, 700);
     // create a memory stream object
     MemoryStream ms = new MemoryStream();
     // save the updated document to stream object
     editor.Save(ms);
     //create PdfConverter object
     PdfConverter objConverter = new PdfConverter();
     //bind input pdf file
     objConverter.BindPdf(ms);
     //set StartPage and EndPage properties to the page number to
     //you want to convert images from
     objConverter.StartPage = 1;
     objConverter.EndPage = 1;
     //Counter
     int page = 1;
     //initialize the converting process
     objConverter.DoConvert();
     //check if pages exist and then convert to image one by one
     while (objConverter.HasNextImage())
         objConverter.GetNextImage(dataDir+ "Specific_Region-Image" + page++ + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
     //close the PdfConverter object
     objConverter.Close();
     // close MemoryStream object holding the updated document
     ms.Close();
 }
예제 #29
0
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            AesManaged aes = null;
            MemoryStream memoryStream = null;
            CryptoStream cryptoStream = null;

            try
            {
                aes = new AesManaged();
                aes.Key = readKeyFromFile(partition);

                memoryStream = new MemoryStream();
                cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

                byte[] buf = Encoding.UTF8.GetBytes(data);
                cryptoStream.Write(buf, 0, buf.Length);
                cryptoStream.FlushFinalBlock();

                dataOut = Convert.ToBase64String(memoryStream.ToArray());
            }
            finally
            {
                if (cryptoStream != null)
                    cryptoStream.Close();

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

                if (aes != null)
                    aes.Clear();
            }

            return getErrorCode() == 0 ? 1 : 0;
        }
예제 #30
0
    //***********************************************************************************************EXPORTACION******************************

    #region ExportacionListados

    //protected void btnImprimirInforme_Click(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        InformeDepartamento inf = new InformeDepartamento();
    //        Document doc = inf.genera();

    //        System.IO.MemoryStream ms = new System.IO.MemoryStream();
    //        //iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f);
    //        //iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);



    //        //Response.Clear();
    //        //Response.ContentType = "application/pdf";
    //        //Response.AddHeader("Content-Disposition",
    //        //    "attachment;filename=\"Plan_de_Gobierno.pdf\"");
    //        //Response.Cache.SetCacheability(HttpCacheability.NoCache);

    //        //Response.BinaryWrite(ms.ToArray());

    //        //Response.Flush();

    //        //Response.End();



    //        using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
    //        {
    //            /*doc.Open();
    //            document.Add(new Paragraph("Hello World"));
    //            document.Close();*/
    //            writer.Close();
    //            ms.Close();
    //            Response.ContentType = "pdf/application";
    //            Response.AddHeader("content-disposition", "attachment;filename=First_PDF_document.pdf");
    //            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    //        }

    //    }
    //    catch (Exception ex)
    //    {
    //        //TODO*************
    //    }
    //}


    protected void InformeExcel(int iDptoId)
    {
        try
        {
            System.IO.MemoryStream stream;

            //using (Entities c = new Entities())
            {
                //DEPARTAMENTO dep = c.DEPARTAMENTO.Find(iDptoId);

                //DataTable tabla = Utils.ToDataTable<CONTENIDO>(dep.CONTENIDO.ToList());

                stream = new System.IO.MemoryStream();

                using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
                {
                    WorkbookPart workbookPart = document.AddWorkbookPart();
                    workbookPart.Workbook = new Workbook();

                    WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
                    MergeCells    mergeCells;

                    var sheetData = InformesExcel.HojaExcelInforme(iDptoId, null, false, out mergeCells);

                    //Añadimos ahora las columnas para poder asignarles el ancho personalizado:
                    Columns columns = InformesExcel.SizesInformeDepartamento(sheetData);

                    worksheetPart.Worksheet = new Worksheet();
                    worksheetPart.Worksheet.Append(columns);
                    worksheetPart.Worksheet.Append(sheetData);

                    Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                    Sheet  sheet  = new Sheet()
                    {
                        Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Plan de Gobierno - " + DateTime.Now.ToShortDateString().Replace("/", "-")
                    };
                    //añadimos las celdas combinadas
                    worksheetPart.Worksheet.InsertAfter(mergeCells, worksheetPart.Worksheet.Elements <SheetData>().First());
                    sheets.Append(sheet);


                    //Añadimos la pestaña con cambios pendientes de validar
                    MergeCells mergeCellsPV;
                    SheetData  sheetDataPV = InformesExcel.HojaExcelInforme(iDptoId, null, true, out mergeCellsPV);

                    WorksheetPart worksheetPartPV = workbookPart.AddNewPart <WorksheetPart>();
                    Worksheet     workSheetPV     = new Worksheet();

                    //Añadimos ahora las columnas para poder asignarles el ancho personalizado:
                    Columns columnsPV = InformesExcel.SizesInformeDepartamento(sheetDataPV);

                    worksheetPartPV.Worksheet = new Worksheet();
                    worksheetPartPV.Worksheet.Append(columnsPV);
                    worksheetPartPV.Worksheet.Append(sheetDataPV);

                    Sheet sheetPV = new Sheet()
                    {
                        Id = workbookPart.GetIdOfPart(worksheetPartPV), SheetId = 2, Name = "P.G. (sin validar) - " + DateTime.Now.ToShortDateString().Replace("/", "-")
                    };
                    //añadimos las celdas combinadas
                    worksheetPartPV.Worksheet.InsertAfter(mergeCellsPV, worksheetPartPV.Worksheet.Elements <SheetData>().First());
                    sheets.Append(sheetPV);

                    //fin pestaña de cambios pendientes de validar


                    WorkbookStylesPart stylesPart = document.WorkbookPart.AddNewPart <WorkbookStylesPart>();
                    stylesPart.Stylesheet = InformesExcel.GenerateStyleSheet();
                    stylesPart.Stylesheet.Save();
                    worksheetPart.Worksheet.Save();
                    //fin nuevo

                    workbookPart.Workbook.Save();
                }
            }


            stream.Flush();
            stream.Position = 0;

            Response.ClearContent();
            Response.Clear();
            Response.Buffer  = true;
            Response.Charset = "";

            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.AddHeader("content-disposition", "attachment; filename=Plan_de_Gobierno_" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            byte[] data1 = new byte[stream.Length];
            stream.Read(data1, 0, data1.Length);
            stream.Close();
            Response.BinaryWrite(data1);
            //Response.Flush();

            //  Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.SuppressContent = true;
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
            //Response.End();
        }
        catch (Exception ex)
        {
            logger.Error("Error al imprimir informe excel departamento (InformeExcel). Dpto: " + iDptoId + " Error: " + ex.Message + " " + ex.InnerException);
            Notificaciones.NotifySystemOps(ex, "Error al imprimir informe excel departamento (InformeExcel). Dpto: " + iDptoId);

            ErrorMessage         = "Error al crear el informe.";
            errorMessage.Visible = true;
        }
    }
예제 #31
0
        public virtual void  TestIndexAndMerge()
        {
            System.IO.MemoryStream sw          = new System.IO.MemoryStream();
            System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(sw);

            Directory   directory = FSDirectory.Open(indexDir);
            IndexWriter writer    = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

            SegmentInfo si1 = IndexDoc(writer, "test.txt");

            PrintSegment(out_Renamed, si1);

            SegmentInfo si2 = IndexDoc(writer, "test2.txt");

            PrintSegment(out_Renamed, si2);
            writer.Close();

            SegmentInfo siMerge = Merge(si1, si2, "merge", false);

            PrintSegment(out_Renamed, siMerge);

            SegmentInfo siMerge2 = Merge(si1, si2, "merge2", false);

            PrintSegment(out_Renamed, siMerge2);

            SegmentInfo siMerge3 = Merge(siMerge, siMerge2, "merge3", false);

            PrintSegment(out_Renamed, siMerge3);

            directory.Close();
            out_Renamed.Close();
            sw.Close();
            System.String multiFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray());
            //System.out.println(multiFileOutput);

            sw          = new System.IO.MemoryStream();
            out_Renamed = new System.IO.StreamWriter(sw);

            directory = FSDirectory.Open(indexDir);
            writer    = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

            si1 = IndexDoc(writer, "test.txt");
            PrintSegment(out_Renamed, si1);

            si2 = IndexDoc(writer, "test2.txt");
            PrintSegment(out_Renamed, si2);
            writer.Close();

            siMerge = Merge(si1, si2, "merge", true);
            PrintSegment(out_Renamed, siMerge);

            siMerge2 = Merge(si1, si2, "merge2", true);
            PrintSegment(out_Renamed, siMerge2);

            siMerge3 = Merge(siMerge, siMerge2, "merge3", true);
            PrintSegment(out_Renamed, siMerge3);

            directory.Close();
            out_Renamed.Close();
            sw.Close();
            System.String singleFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray());

            Assert.AreEqual(multiFileOutput, singleFileOutput);
        }
예제 #32
0
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="savepath">导出文件完整路径(包括文件名)</param>
        /// <param name="dt">数据源</param>
        /// <param name="widths">列宽集合</param>
        public static void ExportExcel(string savePath, DataTable dt, string title, List <int> widths = null)
        {
            IWorkbook book = null;

            book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ISheet sheet = book.CreateSheet("数据清单");

            var headerIndex = 0;

            if (title.Length > 0)
            {
                //第1行添加标题
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Rows[0].ItemArray.Length - 1));
                headerIndex = 1;
            }
            //设置行高   Height的单位是1/20个点。例:设置高度为30个点
            IRow row = sheet.CreateRow(0);

            row.Height = 30 * 20;


            ICell titleCell = row.CreateCell(0);

            titleCell.SetCellValue(title);
            titleCell.CellStyle.Alignment         = HorizontalAlignment.Left;
            titleCell.CellStyle.VerticalAlignment = VerticalAlignment.Center;
            IFont titleFont = book.CreateFont();

            titleFont.FontHeightInPoints = 11;
            titleCell.CellStyle.SetFont(titleFont);

            if (widths != null)
            {
                //设置列宽
                for (int i = 0; i < widths.Count; i++)
                {
                    sheet.SetColumnWidth(i, widths[i] * 256); //列宽单位为 1/256个字符
                }
            }

            int index = 0;

            // 添加表头
            row = sheet.CreateRow(headerIndex);
            foreach (DataColumn item in dt.Columns)
            {
                ICell cell = row.CreateCell(index);
                cell.SetCellType(CellType.String);
                cell.SetCellValue(item.Caption);
                index++;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                index = 0;
                row   = sheet.CreateRow(i + headerIndex + 1); // 添加数据  从第3行开始
                foreach (DataColumn item in dt.Columns)
                {
                    ICell cell = row.CreateCell(index);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(dt.Rows[i][item.ColumnName].ToString());
                    index++;
                }
            }

            // 写入
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            book = null;

            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }
            ms.Close();
            ms.Dispose();
        }
    public byte[] Doctor_PrintOPDPrescriptionReport(string reportId, string appointmentToken,
                                                    string doctorName, string appointmentDate, string appointmentTime, string patientId,
                                                    string patientName, List <Doctor_OPDTreatmentMedicineBO> objOPDTreatmentMedicineBOList, string treatmentDiagnosis)
    {
        Document document   = new Document(PageSize.A3);
        Font     NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);

        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer    = PdfWriter.GetInstance(document, memoryStream);
            PdfPTable table     = null;
            Phrase    phrase    = null;
            PdfPCell  cell      = null;
            Paragraph paragraph = null;
            Color     color     = null;

            document.Open();

            table = new PdfPTable(2);
            float[] widths = new float[] { 5f, 10f };
            table.SetWidths(widths);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("../images/logo.png"));
            image.ScaleAbsolute(80, 80);
            cell        = new PdfPCell(image);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("ABC Hospital\n\n", FontFactory.GetFont("Arial", 18, Font.BOLD, Color.RED)));
            phrase.Add(new Chunk("123, Bodakdev\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ahmedabad 380015\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("INDIA\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ph:- 9543289345\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Website:- http://www.abchospital.com\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));

            cell        = new PdfPCell(phrase);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            color = new Color(System.Drawing.ColorTranslator.FromHtml("#000000"));
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);

            phrase = new Phrase();
            phrase.Add(new Chunk("OPD PRESCRIPTION REPORT\n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.BLACK)));

            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment     = Element.ALIGN_CENTER;
            paragraph.SpacingBefore = 50;
            paragraph.SpacingAfter  = 30;

            document.Add(table);
            document.Add(paragraph);

            table = new PdfPTable(2);

            phrase = new Phrase();
            phrase.Add(new Chunk("Report ID", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(reportId, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Report Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(DateTime.Now.ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Token", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentToken, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Doctor", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(doctorName, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentDate, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Time", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentTime, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell      = new PdfPCell(phrase);
            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            table.HorizontalAlignment = Element.ALIGN_CENTER;

            document.Add(table);

            paragraph = new Paragraph();
            paragraph.Add(new Chunk("\n"));
            document.Add(paragraph);
            paragraph = new Paragraph();
            paragraph.Add(new Chunk("\n"));
            document.Add(paragraph);

            table  = new PdfPTable(9);
            widths = new float[] { 1.5f, 4f, 4f, 2.3f, 2.3f, 4f, 2.2f, 3f, 5f };
            table.SetWidths(widths);

            phrase = new Phrase();
            phrase.Add(new Chunk("No.", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Medicine Type", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Medicine Name", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Strength", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Quantity", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Start Date", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("# Refills", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Quantity on Refill", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("Instructions", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            paragraph          = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            cell.AddElement(paragraph);
            table.AddCell(cell);

            for (int i = 0; i < objOPDTreatmentMedicineBOList.Count; i++)
            {
                phrase = new Phrase();
                phrase.Add(new Chunk((i + 1).ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineType, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineName, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineStrength, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineQuantity, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineStartDate, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk((objOPDTreatmentMedicineBOList[i].numberOfRefills).ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].quantityOnRefills, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);

                phrase = new Phrase();
                phrase.Add(new Chunk(objOPDTreatmentMedicineBOList[i].medicineInstructions, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
                cell = new PdfPCell(phrase);
                cell.PaddingBottom = 20;
                paragraph          = new Paragraph();
                paragraph.Add(phrase);
                paragraph.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(paragraph);
                table.AddCell(cell);
            }

            table.HorizontalAlignment = Element.ALIGN_CENTER;

            document.Add(table);

            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);
            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);

            document.Close();
            byte[] bytes = memoryStream.ToArray();
            using (FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath("../Reports/OPDPrescription/" + reportId + ".pdf")))
            {
                fs.Write(bytes, 0, (int)bytes.Length);
            }
            memoryStream.Close();
            return(bytes);
        }
    }
예제 #34
0
        private object Deserialize()
        {
            object val = null;

            //////////////////////////////////////////////
            /// Step 1: Try creating from Serailized value
            if (SerializedValue != null)
            {
                try {
                    if (SerializedValue is string)
                    {
                        val = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)SerializedValue);
                    }
                    else
                    {
                        MemoryStream ms = new System.IO.MemoryStream((byte[])SerializedValue);
                        try {
                            val = (new BinaryFormatter()).Deserialize(ms);
                        } finally {
                            ms.Close();
                        }
                    }
                }
                catch (Exception exception) {
                    try {
                        if (IsHostedInAspnet())
                        {
                            object[] args = new object[] { Property, this, exception };

                            const string webBaseEventTypeName = "System.Web.Management.WebBaseEvent, " + AssemblyRef.SystemWeb;

                            Type type = Type.GetType(webBaseEventTypeName, true);

                            type.InvokeMember("RaisePropertyDeserializationWebErrorEvent",
                                              BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod,
                                              null, null, args, CultureInfo.InvariantCulture);
                        }
                    }
                    catch {
                    }
                }

                if (val != null && !Property.PropertyType.IsAssignableFrom(val.GetType())) // is it the correct type
                {
                    val = null;
                }
            }

            //////////////////////////////////////////////
            /// Step 2: Try creating from default value
            if (val == null)
            {
                _UsingDefaultValue = true;
                if (Property.DefaultValue == null || Property.DefaultValue.ToString() == "[null]")
                {
                    if (Property.PropertyType.IsValueType)
                    {
                        return(SecurityUtils.SecureCreateInstance(Property.PropertyType));
                    }
                    else
                    {
                        return(null);
                    }
                }
                if (!(Property.DefaultValue is string))
                {
                    val = Property.DefaultValue;
                }
                else
                {
                    try {
                        val = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)Property.DefaultValue);
                    } catch (Exception e) {
                        throw new ArgumentException(SR.GetString(SR.Could_not_create_from_default_value, Property.Name, e.Message));
                    }
                }
                if (val != null && !Property.PropertyType.IsAssignableFrom(val.GetType())) // is it the correct type
                {
                    throw new ArgumentException(SR.GetString(SR.Could_not_create_from_default_value_2, Property.Name));
                }
            }

            //////////////////////////////////////////////
            /// Step 3: Create a new one by calling the parameterless constructor
            if (val == null)
            {
                if (Property.PropertyType == typeof(string))
                {
                    val = "";
                }
                else
                {
                    try {
                        val = SecurityUtils.SecureCreateInstance(Property.PropertyType);
                    } catch {}
                }
            }

            return(val);
        }
예제 #35
0
        public WebResponse UploadFile(string pathInfo, FileInfo fileInfo)
        {
            //long length = 0;
            string boundary = "----------------------------" +
                              DateTime.Now.Ticks.ToString("x");

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(base.ServiceClientBaseUri + pathInfo);

            httpWebRequest.ContentType       = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Accept            = MimeTypes.Json;
            httpWebRequest.Method            = "POST";
            httpWebRequest.AllowAutoRedirect = false;
            httpWebRequest.KeepAlive         = false;

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

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary);


            string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";



            string header = string.Format(headerTemplate, "upload", fileInfo.Name, MimeTypes.GetMimeType(fileInfo.Name));



            byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);

            memStream.Write(headerbytes, 0, headerbytes.Length);


            //Image img = null;
            //img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true);
            //img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);

            using (var fs = fileInfo.OpenRead())
            {
                fs.WriteTo(memStream);
            }

            memStream.Write(boundarybytes, 0, boundarybytes.Length);


            //string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            //string formitem = string.Format(formdataTemplate, "headline", "Sunset");
            //byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            //memStream.Write(formitembytes, 0, formitembytes.Length);

            //memStream.Write(boundarybytes, 0, boundarybytes.Length);


            httpWebRequest.ContentLength = memStream.Length;

            var requestStream = httpWebRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];

            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            return(httpWebRequest.GetResponse());
        }
예제 #36
0
        public void InvokeUploadService(string authtoken, bool isServerMig, string filePath, string mimebuffer,
                                        string theDisposition, string theType, int mode, out string rsp)
        {
            using (LogBlock logblock = Log.NotTracing() ? null : new LogBlock(GetType() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name))
            {
                // --------------------------------------------------
                // Is the data in file, or in string mimebuffer?
                // --------------------------------------------------
                bool bIsBuffer = false;
                if (mimebuffer.Length > 0)
                {
                    bIsBuffer = true;
                }

                // --------------------------------------------------
                // Cert callback
                // --------------------------------------------------
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate(object sender2, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); });

                // --------------------------------------------------
                // Create the request
                // --------------------------------------------------
                HttpWebRequest webReq = this.CreateWebRequestRaw(authtoken, isServerMig);

                // -------------------------------
                // Get preamble for the request
                // -------------------------------
                string ct;
                if (theType.Length == 0)
                {
                    ct = "Content-Type: " + "application/octet-stream";
                }
                else
                {
                    ct = "Content-Type: " + theType;
                }

                string boundary            = "--B-00=_" + DateTime.Now.Ticks.ToString("x");
                string endBoundary         = Environment.NewLine + "--" + boundary + "--" + Environment.NewLine; // FBS bug 73727 -- 5/29/12 -- removed extra "Environment.NewLine +"
                string contentDisposition1 = "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"requestId\"" + Environment.NewLine + Environment.NewLine + "lsrpc32-client-id" + Environment.NewLine;
                string cd2 = (theDisposition.Length > 0) ? theDisposition : "Content-Disposition : form-data; name=\"lslib32\"; filename=\"lslib32.bin\"";
                string contentDisposition2 = "--" + boundary + Environment.NewLine + cd2;
                string contentType         = Environment.NewLine + ct + Environment.NewLine;
                string contentTransfer     = "Content-Transfer-Encoding: binary" + Environment.NewLine + Environment.NewLine;

                // -------------------------------
                // Write data into webReq's stream
                // -------------------------------
                webReq.ContentType = "multipart/form-data; boundary=" + boundary;

                if (mode == ZimbraAPI.STRING_MODE)  // easier -- all text in the request
                {
                    try
                    {
                        if (bIsBuffer)
                        {
                            // =============================================================================================
                            // STREAM FROM BUFFER
                            // =============================================================================================
                            string sDataToUpload = mimebuffer;
                            int    nDataLen      = sDataToUpload.Length; // for view in debugger

                            // --------------------------------------------------
                            // Build the request stream
                            // --------------------------------------------------
                            using (Stream stm = webReq.GetRequestStream())
                            {
                                using (StreamWriter stmw = new StreamWriter(stm, System.Text.Encoding.Default))
                                {
                                    stmw.Write(contentDisposition1);
                                    stmw.Write(contentDisposition2);
                                    stmw.Write(contentType);
                                    stmw.Write(contentTransfer);
                                    stmw.Write(sDataToUpload);
                                    stmw.Write(endBoundary);
                                    stmw.Close();
                                }
                            }
                        }
                        else
                        {
                            // =============================================================================================
                            // STREAM FROM FILE
                            // =============================================================================================


                            // -------------------------------
                            // Build the request stream
                            // -------------------------------
                            long lFileSize = new System.IO.FileInfo(filePath).Length;
                            using (FileStream fileStream = File.OpenRead(filePath))
                            {
                                // Send it off in chunks of 5MB
                                int    bufferSize = 5 * 1024 * 1024;
                                byte[] buffer     = new byte[bufferSize];


                                UTF8Encoding encoding         = new UTF8Encoding();
                                byte[]       bytecd1          = encoding.GetBytes(contentDisposition1);
                                byte[]       bytecd2          = encoding.GetBytes(contentDisposition2);
                                byte[]       byteContType     = encoding.GetBytes(contentType);
                                byte[]       byteContTransfer = encoding.GetBytes(contentTransfer);
                                byte[]       byteEndBoundary  = encoding.GetBytes(endBoundary);

                                long lContentLength = bytecd1.Length
                                                      + bytecd2.Length
                                                      + byteContType.Length
                                                      + byteContTransfer.Length
                                                      + lFileSize
                                                      + byteEndBoundary.Length;
                                Log.trace("Bytes to upload:" + lContentLength);

                                webReq.AllowWriteStreamBuffering = false; // Without this, the call to GetRequestStream will allocate ContentLength bytes   "Setting AllowWriteStreamBuffering to true might cause performance problems when uploading large datasets because the data buffer could use all available memory."    YES!

                                // If the AllowWriteStreamBuffering property of HttpWebRequest is set to false,the contentlength has to be set to length of data to be posted else Exception(411) is raised.
                                webReq.ContentLength = lContentLength;

                                using (Stream RqstStrm = webReq.GetRequestStream())
                                {
                                    // Write preamble
                                    RqstStrm.Write(bytecd1, 0, bytecd1.Length);
                                    RqstStrm.Write(bytecd2, 0, bytecd2.Length);
                                    RqstStrm.Write(byteContType, 0, byteContType.Length);
                                    RqstStrm.Write(byteContTransfer, 0, byteContTransfer.Length);


                                    // Write file contents
                                    long nDone  = 0;
                                    int  nBytes = 1;
                                    while (nBytes != 0)
                                    {
                                        nBytes = fileStream.Read(buffer, 0, bufferSize);
                                        if (nBytes > 0)
                                        {
                                            RqstStrm.Write(buffer, 0, nBytes);
                                            nDone += nBytes;
                                            Log.trace((100 * nDone / lContentLength) + "% uploaded " + nDone + " bytes");
                                        }
                                    }

                                    // Write end boundary
                                    RqstStrm.Write(byteEndBoundary, 0, byteEndBoundary.Length);

                                    // All done
                                    RqstStrm.Close();
                                }
                            }
                        }
                    }
                    catch (System.Net.WebException wex)
                    {
                        // catch (Exception ex)
                        Log.err(wex);
                        setErrors(wex);
                        rsp = "";
                        return;
                    }
                }
                else // CONTACT, APPT_VALUE, or APPT_EMB.  Not distinguishing yet, but we might later.
                {
                    try
                    {
                        // ----------------------------------------------------------------
                        // first get the bytes from the file -- this is the attachment data
                        // ----------------------------------------------------------------
                        byte[] buf     = null;
                        long   datalen = 0;
                        if (bIsBuffer)
                        {
                            datalen = mimebuffer.Length;
                            buf     = Encoding.ASCII.GetBytes(mimebuffer);
                        }
                        else
                        {
                            System.IO.FileStream   fileStream   = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream);

                            datalen = new System.IO.FileInfo(filePath).Length;

                            buf = binaryReader.ReadBytes((Int32)datalen);
                            fileStream.Close();
                            fileStream.Dispose();
                            binaryReader.Close();
                        }

                        // ----------------------------------------------------------------
                        // now use a memory stream since we have mixed data
                        // ----------------------------------------------------------------
                        using (Stream memStream = new System.IO.MemoryStream())
                        {
                            // write the request data
                            byte[] cd1Bytes = System.Text.Encoding.UTF8.GetBytes(contentDisposition1);
                            memStream.Write(cd1Bytes, 0, cd1Bytes.Length);

                            byte[] cd2Bytes = System.Text.Encoding.UTF8.GetBytes(contentDisposition2);
                            memStream.Write(cd2Bytes, 0, cd2Bytes.Length);

                            byte[] cTypeBytes = System.Text.Encoding.UTF8.GetBytes(contentType);
                            memStream.Write(cTypeBytes, 0, cTypeBytes.Length);

                            byte[] cTransferBytes = System.Text.Encoding.UTF8.GetBytes(contentTransfer);
                            memStream.Write(cTransferBytes, 0, cTransferBytes.Length);
                            memStream.Write(buf, 0, (int)datalen);

                            byte[] cEndBoundaryBytes = System.Text.Encoding.UTF8.GetBytes(endBoundary);
                            memStream.Write(cEndBoundaryBytes, 0, cEndBoundaryBytes.Length);

                            // set up the web request to use our memory stream
                            webReq.ContentLength = memStream.Length;

                            memStream.Position = 0;
                            byte[] tempBuffer = new byte[memStream.Length];
                            memStream.Read(tempBuffer, 0, tempBuffer.Length);
                            memStream.Close();


                            // ----------------------------------------------------------------
                            // Send it to server
                            // ----------------------------------------------------------------
                            Stream requestStream = webReq.GetRequestStream();
                            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                            requestStream.Close();
                        }
                    }
                    catch (System.Net.WebException wex)
                    {
                        // catch (Exception ex)
                        setErrors(wex);
                        rsp = "";
                        return;
                    }
                }

                // =======================================================================
                // Get the response from the web service
                // =======================================================================
                WebResponse response = null;
                try
                {
                    Log.verbose(">GetResponse");
                    response = webReq.GetResponse();
                    Log.verbose("<GetResponse");
                }
                catch (System.Net.WebException wex)
                {
                    // catch (Exception ex)
                    setErrors(wex);
                    rsp = "";
                    return;
                }

                Stream       str = response.GetResponseStream();
                StreamReader sr  = new StreamReader(str);
                rsp    = sr.ReadToEnd();
                status = 0;
            }
        }
예제 #37
0
        /// <summary>
        /// 上传文件到远程服务器
        /// </summary>
        /// <param name="url">上传路径</param>
        /// <param name="files">文件路径数组</param>
        /// <param name="nvc">同文件一同上传的表单文本域及值</param>
        public static string UploadFilesToRemoteUrl(string url, string file)
        {
            try
            {
                StringBuilder sb       = new StringBuilder();
                string        boundary = "----------------" + DateTime.Now.Ticks.ToString("x");

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                httpWebRequest.Method      = "POST";
                httpWebRequest.KeepAlive   = true;
                httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

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

                string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                /*foreach (string key in nvc.Keys)
                 * {
                 *  string formitem = string.Format(formdataTemplate, key, nvc[key]);
                 *  sb.Append(formitem);
                 *  byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                 *  memStream.Write(formitembytes, 0, formitembytes.Length);
                 * }*/

                string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

                // 逐个将文件内容写入流

                FileInfo fi = new FileInfo(file);

                // 写入文件开始标记
                string header = string.Format(headerTemplate, "file", fi.Name);
                sb.Append(header);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);

                FileStream fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);



                byte[] buffer = new byte[1024 * 1024 * 8];//每次上传10M

                int bytesRead = 0;
                // 写入文件内容
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                sb.Append("\r\n--" + boundary + "--\r\n");
                // 将结束标记写入内存流
                byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                httpWebRequest.ContentLength = memStream.Length;//流总大小

                Stream requestStream = httpWebRequest.GetRequestStream();

                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                WebResponse  webResponse = httpWebRequest.GetResponse();
                Stream       stream      = webResponse.GetResponseStream();
                StreamReader reader      = new StreamReader(stream);
                string       ret         = reader.ReadToEnd();

                return(ret);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return("");
        }
예제 #38
0
        //接続ボタン
        void ClientMode()
        {
            m_ActiveRecv           = true;
            timerReconnect.Enabled = false;

            string strSrcIP = textBoxSrcIp.Text;
            int    sSrcPort = Int32.Parse(textBoxSrcPort.Text);
            string strDstIP = textBoxDstIp.Text;
            int    sDstPort = Int32.Parse(textBoxDstPort.Text);

            try
            {
                localSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                localSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                var local = new System.Net.IPEndPoint(IPAddress.Parse(strSrcIP), sSrcPort);
                localSocket.Bind(local);

                //TcpClientを作成し、サーバーと接続する
                m_tcp        = new System.Net.Sockets.TcpClient();
                m_tcp.Client = localSocket;
                m_tcp.Connect(strDstIP, sDstPort);
                listBox1.Items.Add("接続成功");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.TopIndex      = listBox1.SelectedIndex;

                //NetworkStreamを取得する
                m_ns = m_tcp.GetStream();
                //読み取り、書き込みのタイムアウトを10秒にする
                m_ns.ReadTimeout  = 1000;
                m_ns.WriteTimeout = 1000;

                m_thread = new Thread(new ThreadStart(() =>
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    byte[] resBytes           = new byte[65536];
                    int resSize = 0;
                    do
                    {
                        try
                        {
                            //データの一部を受信する
                            resSize = m_ns.Read(resBytes, 0, resBytes.Length);
                            //Readが0を返した時はサーバーが切断したと判断
                            if (resSize != 0)
                            {
                                //受信したデータを蓄積する
                                ms.Write(resBytes, 0, resSize);
                                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                                // 受信を続ける
                                Invoke(new ListAddDelegate(OutputLogRecv));
                            }
                            else
                            {
                                //切断
                                break;
                            }
                        }
                        catch (ArgumentNullException e1)
                        {
                        }
                        catch (ArgumentOutOfRangeException e2)
                        {
                        }
                        catch (InvalidOperationException e3)
                        {
                            //切断
                            break;
                        }
                        catch (IOException e4)
                        {
                        }
                    } while (m_ActiveRecv);
                    //受信したデータを文字列に変換
                    ms.Close();
                    m_ns.Close();
                    m_ns = null;
                    m_tcp.Close();
                    m_tcp = null;
                    localSocket.Close();
                    localSocket = null;
                    try
                    {
                        Invoke(new ListAddDelegate(ErrDiscconect));
                    }
                    catch (Exception)
                    {
                    }
                }));

                m_thread.Start();

                buttonConnect.Enabled    = false;
                buttonSend.Enabled       = true;
                buttonDisconnect.Enabled = true;

                //連続送信する場合タイマきどう
                if (checkBoxReSend.Checked == true)
                {
                    timerResend.Interval = Int32.Parse(textBox1.Text);
                    timerResend.Enabled  = true;
                }
            }
            catch (Exception)
            {
                listBox1.Items.Add("接続失敗");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.TopIndex      = listBox1.SelectedIndex;
                if (m_ns != null)
                {
                    m_ns.Close();
                }
                if (m_tcp != null)
                {
                    m_tcp.Close();
                }
                if (localSocket != null)
                {
                    localSocket.Close();
                }
            }
            //再接続時間が設定されている場合、再接続
            if (checkBoxReconnect.Checked)
            {
                timerReconnect.Interval = Int32.Parse(textBoxReconnectTime.Text);
                timerReconnect.Enabled  = true;

                buttonConnect.Enabled    = false;
                buttonDisconnect.Enabled = true;
            }
        }
예제 #39
0
        private void SaveExcelToSharePath(DataTable dtExport)
        {
            MemoryStream TemplateStream = new System.IO.MemoryStream();

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

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

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

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

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

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

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

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

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

                    report.Dispose();
                    report = null;
                }
            }
            catch (Exception ex)
            {
                ErrorDetail = ex.ToString();
                Console.WriteLine(ErrorDetail);
            }
            finally
            {
                TemplateStream.Close();
                TemplateStream = null;
            }
        }
예제 #40
0
        protected void printReport(List <Entities.AcademicOffer> pListAcademicOffer)
        {
            try
            {
                List <Entities.AcademicOffer> listAcademicOffer = pListAcademicOffer;
                System.IO.MemoryStream        memoryStream      = new System.IO.MemoryStream();
                text::Document pdfDoc = new text::Document(text::PageSize.A4, 10, 10, 10, 10);
                pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();

                String imagepath           = Server.MapPath("../../images/page-icons");
                iTextSharp.text.Image deas = iTextSharp.text.Image.GetInstance(imagepath + "/DEAS-logo.jpg");
                deas.ScaleToFit(140f, 120f);
                //Give space before image
                deas.SpacingBefore = 10f;
                //Give some space after the image
                deas.SpacingAfter = 1f;
                deas.Alignment    = text::Element.ALIGN_LEFT;
                pdfDoc.Add(deas);

                text::Paragraph title = new text::Paragraph();
                title.Font      = text::FontFactory.GetFont("dax-black", 32, new text::BaseColor(0, 51, 102));
                title.Alignment = text::Element.ALIGN_CENTER;
                title.Add("\n\n Reporte de Profesores \n\n\n\n");
                pdfDoc.Add(title);

                PdfPTable oPTable = new PdfPTable(5);
                oPTable.TotalWidth    = 100;
                oPTable.SpacingBefore = 20f;
                oPTable.SpacingAfter  = 30f;
                oPTable.AddCell("Nombre Completo");
                oPTable.AddCell("Días");
                oPTable.AddCell("Hora de Inicio - Final");
                oPTable.AddCell("Cant. Horas");
                oPTable.AddCell("Estado");

                if (listAcademicOffer.Count > 0)
                {
                    foreach (Entities.AcademicOffer pAcademicOffer in listAcademicOffer)
                    {
                        oPTable.AddCell(pAcademicOffer.oteacher.name + " " + pAcademicOffer.oteacher.lastName);
                        oPTable.AddCell(pAcademicOffer.oSchedule.name);
                        oPTable.AddCell(pAcademicOffer.oSchedule.startTime.ToShortTimeString() + " " + pAcademicOffer.oSchedule.endTime.ToShortTimeString());
                        oPTable.AddCell(pAcademicOffer.hours.ToString());
                        oPTable.AddCell((pAcademicOffer.oteacher.state == 1 ? "Activo" : "Inactivo"));
                    }
                }
                else
                {
                    PdfPCell cell = new PdfPCell(new text::Phrase("No existen profesores registrados."));
                    cell.Colspan             = 5;
                    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    oPTable.AddCell(cell);
                }

                pdfDoc.Add(oPTable);
                pdfDoc.Close();

                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=Profesores.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
        public ActionResult Save(ORDER_TASK_INFORMATION entity)
        {
            Common.ClientResult.OrderTaskGong result = new Common.ClientResult.OrderTaskGong();
            try
            {
                Common.Account account = GetCurrentAccount();
                if (string.IsNullOrWhiteSpace(entity.ID))
                {
                    List <COMPANY> companylist  = m_BLL2.GetByParam(null, "asc", "ID", "COMPANYNAME&" + entity.INSPECTION_ENTERPRISE + "");
                    List <COMPANY> companylist2 = m_BLL2.GetByParam(null, "asc", "ID", "COMPANYNAME&" + entity.CERTIFICATE_ENTERPRISE + "");


                    foreach (var item in companylist)
                    {
                        if (item.COMPANY2 != null)
                        {
                            entity.INSPECTION_ENTERPRISEHELLD = item.COMPANY2.COMPANYNAME;
                            break;
                        }
                    }
                    foreach (var item in companylist2)
                    {
                        if (item.COMPANY2 != null)
                        {
                            entity.CERTIFICATE_ENTERPRISEHELLD = item.COMPANY2.COMPANYNAME;
                            break;
                        }
                    }
                    string ORDER_NUMBER = m_BLL.GetORDER_NUMBER(ref validationErrors);
                    var    order        = ORDER_NUMBER.Split('*');// DC2016001 * 1 * 2016
                    entity.ORDER_STATUS = Common.ORDER_STATUS_INFORMATION.保存.ToString();
                    var ms = new System.IO.MemoryStream();
                    entity.CREATETIME   = DateTime.Now;
                    entity.CREATEPERSON = account.PersonName;
                    entity.ID           = Result.GetNewId();

                    entity.ORDER_NUMBER   = order[0].ToString();
                    entity.ORSERIALNUMBER = Convert.ToDecimal(order[1]);
                    entity.ORYEARS        = order[2].ToString();

                    entity.ORDER_STATUS = Common.ORDER_STATUS_INFORMATION.保存.ToString();

                    string path = Server.MapPath("~/up/ErWeiMa/");
                    foreach (var item in entity.APPLIANCE_DETAIL_INFORMATION)
                    {
                        item.ID           = Result.GetNewId();
                        item.CREATETIME   = DateTime.Now;
                        item.CREATEPERSON = account.PersonName;
                        item.BAR_CODE_NUM = item.ID;
                        //二维码生成
                        ErrorCorrectionLevel Ecl    = ErrorCorrectionLevel.M; //误差校正水平
                        string           Content    = item.ID;                //待编码内容
                        QuietZoneModules QuietZones = QuietZoneModules.Two;   //空白区域
                        int    ModuleSize           = 3;                      //大小
                        var    encoder = new QrEncoder(Ecl);
                        QrCode qr;
                        if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
                        {
                            Renderer r = new Renderer(ModuleSize);
                            r.QuietZoneModules = QuietZones;
                            r.WriteToStream(qr.Matrix, ms, ImageFormat.Png);
                        }
                        //QRCodeHelper.GetQRCode(item.ID, ms);
                        var pathErWeiMa = path + item.ID + ".png";

                        //System.IO.FileStream fs = new System.IO.FileStream(pathErWeiMa, System.IO.FileMode.OpenOrCreate);


                        //System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs);
                        #region 二维码加字
                        System.IO.FileStream fss = new System.IO.FileStream(Server.MapPath("~/up/moban.png"), System.IO.FileMode.OpenOrCreate);
                        int filelength           = 0;
                        filelength = (int)fss.Length;        //获得文件长度
                        Byte[] image = new Byte[filelength]; //建立一个字节数组
                        fss.Read(image, 0, filelength);      //按字节流读取
                        System.Drawing.Image imag = System.Drawing.Image.FromStream(fss);
                        //System.Drawing.Image Image = System.Drawing.Image.FromStream(ms);
                        Graphics g = null;
                        g = Graphics.FromImage(imag);
                        string xinghao = item.VERSION;//需要写入的字
                        //string xinghao = "123456789abcd";//需要写入的字
                        int w = imag.Width;
                        int h = imag.Height;
                        int y = 0;
                        int x = 380;
                        for (int i = 0; i < xinghao.Length; i++)
                        {
                            if (x > w)
                            {
                                result.Code    = Common.ClientCode.Fail;
                                result.Message = "内容太多二维码生成失败!";
                                return(Json(result));
                            }
                            else
                            {
                                if (i % 6 == 0)
                                {
                                    x = x + 50;
                                    y = 0;
                                    y = y + 45;
                                    g.DrawString(xinghao[i].ToString(), new Font("宋体", 14), Brushes.Red, new PointF(x, y));//x:值越大越靠右;y:值越小越靠上
                                }
                                else
                                {
                                    y = y + 45;
                                    g.DrawString(xinghao[i].ToString(), new Font("宋体", 14), Brushes.Red, new PointF(x, y));//x:值越大越靠右;y:值越小越靠上
                                }
                            }
                        }
                        System.Drawing.Image ig = CombinImage(imag, ms);
                        fss.Close();
                        TuPanBaoCun(ig, pathErWeiMa);
                        //生成pdf
                        //图片
                        //Image image = Image.GetInstance(imagePath);
                        //cell = new PdfPCell(image, true);
                        //table.AddCell(cell);
                        PDF.Create(path + item.ID);
                        #endregion

                        //w.Write(ms.ToArray());
                        //fs.Close();
                        //器具明细信息_承接实验室表添加数据
                        foreach (var it in item.UNDERTAKE_LABORATORYID.TrimEnd(',').Split(','))
                        {
                            item.APPLIANCE_LABORATORY.Add(new APPLIANCE_LABORATORY()
                            {
                                ID = Result.GetNewId(),
                                UNDERTAKE_LABORATORYID   = it,
                                ORDER_STATUS             = Common.ORDER_STATUS.保存.ToString(),
                                EQUIPMENT_STATUS_VALUUMN = Common.ORDER_STATUS.保存.GetHashCode().ToString(),
                                DISTRIBUTIONPERSON       = account.PersonName,
                                DISTRIBUTIONTIME         = DateTime.Now,
                                CREATEPERSON             = account.PersonName,
                                CREATETIME = DateTime.Now,
                                ISRECEIVE  = Common.ISRECEIVE.是.ToString(),
                                RECYCLING  = entity.RECYCLING
                            });
                        }
                    }
                    ms.Close();

                    string returnValue = string.Empty;
                    if (m_BLL.Create(ref validationErrors, entity))
                    {
                        LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + ",委托单信息的信息的Id为" + entity.ID, "委托单信息"
                                                       );//写入日志
                        result.Code    = Common.ClientCode.Succeed;
                        result.Message = Suggestion.InsertSucceed;
                        result.Id      = entity.ID;
                        return(Json(result)); //提示创建成功
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return(true);
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.InsertFail + ",委托单信息的信息," + returnValue, "委托单信息"
                                                       );//写入日志
                        result.Code    = Common.ClientCode.Fail;
                        result.Message = Suggestion.InsertFail + returnValue;
                        return(Json(result)); //提示插入失败
                    }
                }
                else
                {
                }


                result.Code    = Common.ClientCode.FindNull;
                result.Message = Suggestion.InsertFail + ",请核对输入的数据的格式"; //提示输入的数据的格式不对
            }
            catch (Exception lastError)
            {
                // fss.Close();
                ExceptionsHander.WriteExceptions(lastError);//将异常写入数据库
            }
            return(Json(result));
        }
예제 #42
0
        public static Dictionary <string, string> UploadFile(string hpf, UploadImageInfo model)
        {
            string filePath = System.Configuration.ConfigurationManager.AppSettings[BaseDictType.TempFileUploadPath];

            Dictionary <string, string> data = new Dictionary <string, string>();

            string saveUrl = System.Web.HttpContext.Current.Server.MapPath(filePath);

            if (!System.IO.Directory.Exists(saveUrl))
            {
                System.IO.Directory.CreateDirectory(saveUrl);
            }

            //将文件流写到byte数组中
            byte[]       arr = Convert.FromBase64String(hpf);
            MemoryStream ms  = new MemoryStream(arr);
            Bitmap       bmp = new Bitmap(ms);

            var filename = Util.RPCNow.Ticks.ToString() + Util.RPCNow.Millisecond + ".jpg";

            try
            {
                var saveurl = saveUrl + filename;
                bmp.Save(saveurl, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
                //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
                //bmp.Save(txtFileName + ".png", ImageFormat.Png);
                bmp.Dispose();
                ms.Close();

                string strDescription = model.DateTimeOriginal + "\r\n";
                strDescription += model.StoreAddr + "\r\n";                 // + " 精度(" + model.SignPoint + ")";
                strDescription += model.StoreCode + " " + model.StoreName + "\r\n";
                strDescription += model.EmpCode + " " + model.EmpName + "(" + model.EmpDuty + ")\r\n";
                //strDescription += "纬度:" + GetGPSLatitude(GPSLatitude) + "\r\n";
                //strDescription += "经度:" + GetGPSLatitude(GPSLongitude) + "\r\n";
                //strDescription += GetDistance(GPSLatitude, GPSLongitude, storeGPSLat, storeGPSLng) ;
                //strDescription += "拍摄地址:" + GetAddrName(GetGPSLatitude(model.GPSLatitude) + "," + GetGPSLatitude(model.GPSLongitude));

                ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(saveurl));
                System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                Graphics             g     = Graphics.FromImage(image);
                //Brush drawBrush = new SolidBrush(System.Drawing.Color.FromArgb(((System.Byte)(222)), ((System.Byte)(243)), ((System.Byte)(255)))); //自定义字体颜色
                Font       font    = new Font("宋体", 10);
                SizeF      sizeF   = g.MeasureString(" " + strDescription + " ", font);
                Color      Mycolor = System.Drawing.Color.FromArgb(0, 0, 0, 0);           //说明:1-(128/255)=1-0.5=0.5 透明度为0.5,即50%
                SolidBrush sb1     = new System.Drawing.SolidBrush(Mycolor);
                g.FillRectangle(sb1, new RectangleF(new PointF(0, image.Height - 100), sizeF));
                //FillRoundRectangle(g, sb1, new Rectangle(15, 20, (int)sizeF.Width+20, (int)sizeF.Height), 8);
                //DrawRoundRectangle(g, Pens.Transparent, new Rectangle(15, 20, (int)sizeF.Width +20, (int)sizeF.Height), 8);
                g.DrawString(strDescription, new Font("宋体", 10), Brushes.White, new PointF(2, image.Height - 94));

                System.IO.File.Delete(saveurl);
                image.Save(saveurl);

                var url = filePath + filename;

                data.Add("status", "1");
                data.Add("content", "上传成功");
                data.Add("url", url);
                data.Add("filename", filename);
            }
            catch (Exception ex)
            {
                data.Add("status", "0");
                data.Add("content", "上传失败");
                data.Add("url", "");
                data.Add("filename", "");
            }
            finally
            {
                bmp.Dispose();
                ms.Close();
            }

            //string returnstring=PostApply(hpf, DateTimeOriginal, GPSLatitude, GPSLongitude);


            return(data);
        }
예제 #43
0
        public static void TestUpload()
        {
            string boundary = "----FILEBOUNDARY----";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/files");

            request.ContentType = "multipart/form-data; boundary=" + boundary;

            request.Method = "POST";

            request.Headers["Authorization"] = "Zoho-oauthtoken 1.xxxx.xxxx";

            request.KeepAlive = true;

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

            var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";

            StreamWrapper streamWrapper = new StreamWrapper("/Users/Desktop/test.html");

            StreamWrapper streamWrapper1 = new StreamWrapper("/Users/Desktop/test.html");

            List <StreamWrapper> streamWrapperList = new List <StreamWrapper>()
            {
                streamWrapper, streamWrapper1
            };

            for (int i = 0; i < streamWrapperList.Count; i++)
            {
                StreamWrapper streamWrapperInstance = streamWrapperList[i];

                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                var header = string.Format(headerTemplate, "file", streamWrapperInstance.Name);

                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                memStream.Write(headerbytes, 0, headerbytes.Length);

                var buffer = new byte[1024];

                var bytesRead = 0;

                while ((bytesRead = streamWrapperInstance.Stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
            }

            memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

            request.ContentLength = memStream.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                memStream.Position = 0;

                byte[] tempBuffer = new byte[memStream.Length];

                memStream.Read(tempBuffer, 0, tempBuffer.Length);

                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw;
                }

                response = (HttpWebResponse)e.Response;
            }

            HttpWebResponse responseEntity = response;

            string responsestring = new StreamReader(responseEntity.GetResponseStream()).ReadToEnd();

            responseEntity.Close();

            Console.WriteLine(responsestring);
        }
예제 #44
0
        private void buttonReport_Click(object sender, EventArgs e)
        {
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                // Pending orders header - para1
                Paragraph para1 = new Paragraph("Zamówienia w trakcie realizacji:");
                para1.Font = FontFactory.GetFont(FontFactory.TIMES_BOLD, 12f, BaseColor.BLACK);
                document.Add(para1);

                // Pending orders list - para2
                Paragraph para2 = new Paragraph();
                para2.Font = FontFactory.GetFont(FontFactory.TIMES, 9f, BaseColor.BLACK);

                foreach (object order in listBoxCurrentOrders.Items)
                {
                    para2.Add(order.ToString() + "\n");
                }
                document.Add(para2);

                // Pending orders sum - para3
                Paragraph para3 = new Paragraph();
                para3.Font          = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9f, BaseColor.BLACK);
                para3.SpacingBefore = 5;
                para3.SpacingAfter  = 10;
                int pendingSum = listBoxCurrentOrders.Items.Count;
                para3.Add("Suma zamówien w trakcie realizacji: " + pendingSum.ToString());
                document.Add(para3);

                // Completed orders header - para4
                Paragraph para4 = new Paragraph("Zamówienia zrealizowane:");
                para4.Font = FontFactory.GetFont(FontFactory.TIMES_BOLD, 12f, BaseColor.BLACK);
                document.Add(para4);

                // Completed orders list - para5
                Paragraph para5 = new Paragraph();
                para5.Font = FontFactory.GetFont(FontFactory.TIMES, 9f, BaseColor.BLACK);

                foreach (object order in listBoxCompletedOrders.Items)
                {
                    para5.Add(order.ToString() + "\n");
                }
                document.Add(para5);

                // Completed orders sum - para6
                Paragraph para6 = new Paragraph();
                para6.Font          = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9f, BaseColor.BLACK);
                para6.SpacingBefore = 5;
                para6.SpacingAfter  = 10;
                int completedSum = listBoxCompletedOrders.Items.Count;
                para6.Add("Suma zrealizowanych zamówien: " + completedSum.ToString());
                document.Add(para6);

                // Orders count in each showroom
                var orders    = databaseContext.Set <Orders>().Include(o => o.Car);
                var showrooms = databaseContext.Set <CarShowrooms>().Include(cs => cs.Cars);

                Paragraph para = new Paragraph();
                foreach (CarShowrooms showroom in showrooms)
                {
                    int countSum      = 0;
                    int countComplete = 0;
                    int countPrices   = 0;
                    foreach (Orders order in orders)
                    {
                        if (showroom.Cars.Contains(order.Car))
                        {
                            countSum++;
                            countPrices += order.Price;
                            if (order.RealizationDate < DateTime.Now)
                            {
                                countComplete++;
                            }
                        }
                    }
                    para.Clear();
                    para.Font          = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9f, BaseColor.BLACK);
                    para.SpacingBefore = 5;
                    para.SpacingAfter  = 5;
                    para.Add(showroom.Name + ", " + showroom.Address + "\n");
                    para.Font = FontFactory.GetFont(FontFactory.TIMES, 9f, BaseColor.BLACK);
                    para.Add("Zrealizowanych zamówien: " + countComplete.ToString() + "\n");
                    para.Add("Zamówien w sumie: " + countSum.ToString() + "\n");
                    para.Add("Kwota sumaryczna zamówien: " + countPrices.ToString() + "\n");
                    document.Add(para);
                }

                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();

                // Save PDF to file in device memory
                string fileName = "Sales_Report.pdf";
                using (FileStream fs = File.Create(fileName))
                {
                    fs.Write(bytes, 0, (int)bytes.Length);
                }

                MessageBox.Show("Pomyślnie wygenerowano raport do pliku " + fileName);
            }
        }
예제 #45
0
        public static Dictionary <string, string> WXUploadFile(string ServerID, UploadImageInfo model)
        {
            //string gps= map_tx2bd(double.Parse(model.GPSLatitude), double.Parse(model.GPSLongitude));

            string filePath    = System.Configuration.ConfigurationManager.AppSettings[BaseDictType.TempFileUploadPath];
            var    filename    = Util.RPCNow.Ticks.ToString() + Util.RPCNow.Millisecond + ".jpg";
            var    saveURl     = System.Web.HttpContext.Current.Server.MapPath(filePath) + filename;
            var    accessToken = WeixinCache.GetCorpAccessToken();

            using (MemoryStream stream = new MemoryStream())
            {
                MediaApi.Get(accessToken, ServerID, stream);

                if (!System.IO.Directory.Exists(saveURl))
                {
                    System.IO.Directory.CreateDirectory(saveURl.Replace(filename, ""));
                }
                using (var fs = new FileStream(saveURl, FileMode.CreateNew))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(fs);
                    fs.Flush();
                }
            }

            Dictionary <string, string> data = new Dictionary <string, string>();

            MemoryStream ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(saveURl));

            try
            {
                string strDescription = model.DateTimeOriginal + "\r\n";
                strDescription += model.StoreAddr + "\r\n";                 // + " 精度(" + model.SignPoint + ")" ;
                strDescription += model.StoreCode + " " + model.StoreName + "\r\n";
                strDescription += model.EmpCode + " " + model.EmpName + "(" + model.EmpDuty + ")\r\n";

                System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                Graphics             g     = Graphics.FromImage(image);
                //Brush drawBrush = new SolidBrush(System.Drawing.Color.FromArgb(((System.Byte)(222)), ((System.Byte)(243)), ((System.Byte)(255)))); //自定义字体颜色
                Font       font    = new Font("宋体", 10);
                SizeF      sizeF   = g.MeasureString(" " + strDescription + " ", font);
                Color      Mycolor = System.Drawing.Color.FromArgb(0, 0, 0, 0);           //说明:1-(128/255)=1-0.5=0.5 透明度为0.5,即50%
                SolidBrush sb1     = new System.Drawing.SolidBrush(Mycolor);
                g.FillRectangle(sb1, new RectangleF(new PointF(0, image.Height - 100), sizeF));
                //FillRoundRectangle(g, sb1, new Rectangle(15, 20, (int)sizeF.Width+20, (int)sizeF.Height), 8);
                //DrawRoundRectangle(g, Pens.Transparent, new Rectangle(15, 20, (int)sizeF.Width +20, (int)sizeF.Height), 8);
                g.DrawString(strDescription, new Font("宋体", 10), Brushes.White, new PointF(2, image.Height - 94));

                System.IO.File.Delete(saveURl);
                image.Save(saveURl);

                var url = filePath + filename;

                data.Add("status", "1");
                data.Add("content", "上传成功");
                data.Add("url", url);
                data.Add("filename", filename);
            }
            catch (Exception ex)
            {
                data.Add("status", "0");
                data.Add("content", "上传失败");
                data.Add("url", "");
                data.Add("filename", "");
            }
            finally
            {
                ms.Close();
            }

            //string returnstring=PostApply(hpf, DateTimeOriginal, GPSLatitude, GPSLongitude);


            return(data);
        }
예제 #46
0
        /// <summary>
        /// 本地文件上传到远程服务器
        /// </summary>
        /// <param name="localFile">本地文件路径</param>
        /// <param name="remoteUrl">远程图片服务器上传地址</param>
        /// <param name="dic">携带的上传参数</param>
        /// <returns></returns>
        public static string UploadFileToRemote(string localFile, string remoteUrl, Dictionary <string, string> dic)
        {
            if (!File.Exists(localFile))
            {
                Logger.WriteLog(string.Format("本地文件不存在。"));
                return(string.Empty);
            }

            FileStream fileStream = new FileStream(localFile, FileMode.Open);

            string         boundary       = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);

            httpWebRequest.ContentType = "multipart/form-data; boundary=" +
                                         boundary;
            httpWebRequest.Method      = "POST";
            httpWebRequest.KeepAlive   = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;



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

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            foreach (string key in dic.Keys)
            {
                string formitem      = string.Format(formdataTemplate, key, dic[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }


            memStream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

            var    fileExtension = Path.GetExtension(localFile).ToLower();
            string header        = string.Format(headerTemplate, "uploadfile", DateTime.Now.Ticks.ToString("x") + fileExtension);

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            byte[] buffer = new byte[1024];

            int bytesRead = 0;

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            memStream.Write(boundarybytes, 0, boundarybytes.Length);

            fileStream.Close();


            httpWebRequest.ContentLength = memStream.Length;
            Stream requestStream = httpWebRequest.GetRequestStream();

            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();


            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            string responseContent = string.Empty;

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            return(responseContent);
        }
예제 #47
0
        protected virtual void Export()
        {
            if (this.bTabControl1.SelectedIndex == 0)
            {
                string file     = "";
                bool   bProtect = this.bsprData.ActiveSheet.Protect;

                this.bsprData.ActiveSheet.Protect = false;

                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.Filter          = "Excel Files (*.xls)|*.xls";
                openDlg.FileName        = "";
                openDlg.DefaultExt      = ".xls";
                openDlg.CheckFileExists = false;
                openDlg.CheckPathExists = true;

                DialogResult res = openDlg.ShowDialog();

                if (res != DialogResult.OK)
                {
                    return;
                }

                file = openDlg.FileName;

                FarPoint.Win.Spread.SheetView spread_Sheet1 = new FarPoint.Win.Spread.SheetView();
                spread_Sheet1.SheetName = "_ExcelExportSheet";

                FarPoint.Win.Spread.FpSpread spread = new FarPoint.Win.Spread.FpSpread();

                spread.Sheets.Add(spread_Sheet1);
                spread_Sheet1.Visible = true;
                spread.ActiveSheet    = spread_Sheet1;

                byte[] buffer = null;
                System.IO.MemoryStream stream = null;
                this.bsprData.SetFilterVisible(false);

                try
                {
                    stream = new System.IO.MemoryStream();
                    this.bsprData.Save(stream, false);
                    buffer = stream.ToArray();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                        stream = null;
                    }
                }

                stream = new System.IO.MemoryStream(buffer);
                spread.Open(stream);

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                for (int i = spread.ActiveSheet.Columns.Count - 1; i >= 0; i--)
                {
                    if (!spread.ActiveSheet.Columns[i].Visible)
                    {
                        spread.ActiveSheet.Columns[i].Remove();
                    }
                }

                spread.SaveExcel(file, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);
                this.bsprData.ActiveSheet.Protect = bProtect;

                string strMessage = "It was saved successfully. Do you open saved file?";

                DialogResult result = MessageBox.Show(strMessage, "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Applications\EXCEL.EXE");

                    if (key == null)
                    {
                        MSGHandler.DisplayMessage(MSGType.Error, "SPC_INFO_NEED_MS_OFFICE", null, null);
                    }
                    else
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = file;
                        process.Start();
                    }
                }
            }
            else
            {
                string file     = "";
                bool   bProtect = this.bsprRawData.ActiveSheet.Protect;

                this.bsprRawData.ActiveSheet.Protect = false;

                SaveFileDialog openDlg = new SaveFileDialog();
                openDlg.Filter          = "Excel Files (*.xls)|*.xls";
                openDlg.FileName        = "";
                openDlg.DefaultExt      = ".xls";
                openDlg.CheckFileExists = false;
                openDlg.CheckPathExists = true;

                DialogResult res = openDlg.ShowDialog();

                if (res != DialogResult.OK)
                {
                    return;
                }

                file = openDlg.FileName;

                FarPoint.Win.Spread.SheetView spread_Sheet1 = new FarPoint.Win.Spread.SheetView();
                spread_Sheet1.SheetName = "_ExcelExportSheet";

                FarPoint.Win.Spread.FpSpread spread = new FarPoint.Win.Spread.FpSpread();

                spread.Sheets.Add(spread_Sheet1);
                spread_Sheet1.Visible = true;
                spread.ActiveSheet    = spread_Sheet1;

                byte[] buffer = null;
                System.IO.MemoryStream stream = null;
                this.bsprRawData.SetFilterVisible(false);

                try
                {
                    stream = new System.IO.MemoryStream();
                    this.bsprRawData.Save(stream, false);
                    buffer = stream.ToArray();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                        stream = null;
                    }
                }

                stream = new System.IO.MemoryStream(buffer);
                spread.Open(stream);

                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                for (int i = spread.ActiveSheet.Columns.Count - 1; i >= 0; i--)
                {
                    if (!spread.ActiveSheet.Columns[i].Visible)
                    {
                        spread.ActiveSheet.Columns[i].Remove();
                    }
                }

                spread.SaveExcel(file, FarPoint.Win.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);
                this.bsprRawData.ActiveSheet.Protect = bProtect;

                string strMessage = "It was saved successfully. Do you open saved file?";

                DialogResult result = MessageBox.Show(strMessage, "Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Applications\EXCEL.EXE");

                    if (key == null)
                    {
                        MSGHandler.DisplayMessage(MSGType.Error, "SPC_INFO_NEED_MS_OFFICE", null, null);
                    }
                    else
                    {
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = file;
                        process.Start();
                    }
                }
            }
        }
예제 #48
0
        private void explort()
        {
            SaveFileDialog sflg = new SaveFileDialog();

            sflg.Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx";
            if (sflg.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            //this.gridView1.ExportToXls(sflg.FileName);
            //NPOI.xs book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.IWorkbook book = null;
            if (sflg.FilterIndex == 1)
            {
                book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            }
            else
            {
                book = new NPOI.XSSF.UserModel.XSSFWorkbook();
            }

            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("test_001");

            // 添加表头
            NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
            int index = 0;

            foreach (DataGridViewColumn item in this.dataGridView2.Columns)
            {
                if (item.Visible)
                {
                    NPOI.SS.UserModel.ICell cell = row.CreateCell(index);
                    cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                    cell.SetCellValue(item.HeaderText);
                    index++;
                }
            }

            // 添加数据

            for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
            {
                index = 0;
                row   = sheet.CreateRow(i + 1);
                foreach (DataGridViewColumn item in this.dataGridView2.Columns)
                {
                    if (item.Visible)
                    {
                        if (dataGridView2.Rows[i].Cells[item.HeaderText].Value != null)
                        {
                            NPOI.SS.UserModel.ICell cell = row.CreateCell(index);
                            cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                            cell.SetCellValue(dataGridView2.Rows[i].Cells[item.HeaderText].Value.ToString().Trim());
                        }
                        index++;
                    }
                }
            }
            // 写入
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            book = null;

            using (FileStream fs = new FileStream(sflg.FileName, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }

            ms.Close();
            ms.Dispose();
        }
예제 #49
0
        private static byte[] GetMultipartFormData(Dictionary <string, object> postParameters, string boundary)
        {
            Stream formDataStream = new System.IO.MemoryStream();
            bool   needsCLRF      = false;

            if (postParameters.Count > 1)
            {
                foreach (var param in postParameters)
                {
                    // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
                    // Skip it on the first parameter, add it to subsequent parameters.
                    if (needsCLRF)
                    {
                        formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
                    }

                    needsCLRF = true;
                    var fileInfo = (FileInfo)param.Value;
                    if (param.Value is FileInfo)
                    {
                        string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
                                                        boundary,
                                                        param.Key,
                                                        fileInfo.MimeType);
                        formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));

                        // Write the file data directly to the Stream, rather than serializing it to a string.
                        formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
                    }
                    else
                    {
                        string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                                                        boundary,
                                                        param.Key,
                                                        fileInfo.file);
                        formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
                    }
                }
                // Add the end of the request.  Start with a newline
                string footer = "\r\n--" + boundary + "--\r\n";
                formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
            }
            else
            {
                foreach (var param in postParameters)
                {
                    var fileInfo = (FileInfo)param.Value;
                    if (param.Value is FileInfo)
                    {
                        // Write the file data directly to the Stream, rather than serializing it to a string.
                        formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length);
                    }
                    else
                    {
                        string postData = (string)param.Value;
                        formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
                    }
                }
            }

            // Dump the Stream into a byte[]
            formDataStream.Position = 0;
            byte[] formData = new byte[formDataStream.Length];
            formDataStream.Read(formData, 0, formData.Length);
            formDataStream.Close();

            return(formData);
        }
예제 #50
0
파일: upload.cs 프로젝트: tyriankid/WFX
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (base.Request.QueryString["delimg"] != null)
            {
                string path = base.Server.HtmlEncode(base.Request.QueryString["delimg"]);
                path = base.Server.MapPath(path);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                base.Response.Write("0");
                base.Response.End();
            }
            Image    image    = null;
            Image    image2   = null;
            Bitmap   bitmap   = null;
            Graphics graphics = null;

            System.IO.MemoryStream stream = null;
            int num = int.Parse(base.Request.QueryString["imgurl"]);

            try
            {
                if (num < 9)
                {
                    System.Web.HttpPostedFile file = base.Request.Files["Filedata"];
                    string str2 = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    string str3 = "/Storage/data/FriendExtension/";
                    string str4 = str2 + System.IO.Path.GetExtension(file.FileName);
                    file.SaveAs(Globals.MapPath(str3 + str4));
                    base.Response.StatusCode = 200;
                    base.Response.Write(str2 + "|/Storage/data/FriendExtension/" + str4);
                }
                else
                {
                    base.Response.Write("0");
                }
            }
            catch (System.Exception)
            {
                base.Response.StatusCode = 500;
                base.Response.Write("服务器错误");
                base.Response.End();
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (graphics != null)
                {
                    graphics.Dispose();
                }
                if (image2 != null)
                {
                    image2.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                base.Response.End();
            }
        }
예제 #51
0
        protected void getReport(List <Entities.WaitingList> pListWaitingList)
        {
            try
            {
                List <Entities.WaitingList> listWaitingList = pListWaitingList;

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                text::Document         pdfDoc       = new text::Document(text::PageSize.A4, 10, 10, 10, 10);
                pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();

                String imagepath           = Server.MapPath("../../images/page-icons");
                iTextSharp.text.Image deas = iTextSharp.text.Image.GetInstance(imagepath + "/DEAS-logo.jpg");
                deas.ScaleToFit(140f, 120f);
                //Give space before image
                deas.SpacingBefore = 10f;
                //Give some space after the image
                deas.SpacingAfter = 1f;
                deas.Alignment    = text::Element.ALIGN_LEFT;
                pdfDoc.Add(deas);

                text::Paragraph title = new text::Paragraph();
                title.Font      = text::FontFactory.GetFont("dax-black", 32, new text::BaseColor(0, 51, 102));
                title.Alignment = text::Element.ALIGN_CENTER;
                title.Add("\n\n Reporte de lista de espera\n\n");
                pdfDoc.Add(title);

                PdfPTable oPTable = new PdfPTable(6);
                oPTable.TotalWidth    = 100;
                oPTable.SpacingBefore = 20f;
                oPTable.SpacingAfter  = 30f;
                oPTable.AddCell("Nombre completo");
                oPTable.AddCell("# Residencial");
                oPTable.AddCell("# Celular");
                oPTable.AddCell("Correo electrónico");
                oPTable.AddCell("Curso");
                oPTable.AddCell("Día");

                if (listWaitingList.Count > 0)
                {
                    foreach (Entities.WaitingList pWaitingList in listWaitingList)
                    {
                        oPTable.AddCell(pWaitingList.name + " " + pWaitingList.lastName);
                        oPTable.AddCell(pWaitingList.homePhone);
                        oPTable.AddCell(pWaitingList.cellPhone);
                        oPTable.AddCell(pWaitingList.email);
                        oPTable.AddCell(pWaitingList.course_name);
                        oPTable.AddCell(pWaitingList.day);
                    }
                }
                else
                {
                    PdfPCell cell = new PdfPCell(new text::Phrase("No existen datos registrados."));
                    cell.Colspan             = 6;
                    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    oPTable.AddCell(cell);
                }

                pdfDoc.Add(oPTable);
                pdfDoc.Close();

                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=waitingreportmain.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
예제 #52
0
        private void sb_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog sflg = new SaveFileDialog();

            sflg.Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx";
            if (sflg.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            int aa = 0;

            NPOI.SS.UserModel.IWorkbook book = null;
            if (sflg.FilterIndex == 1)
            {
                book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            }
            else
            {
                book = new NPOI.XSSF.UserModel.XSSFWorkbook();
            }
            foreach (XtraTabPage trp in this.xtraTabControl1.TabPages)
            {
                XtraTabPage xinka = trp;
                try
                {
                    this.active_nepCalaTable = xinka.Controls[0] as NepCalaTable;
                }
                catch (Exception err)
                {
                    MessageBox.Show("出现了错误: " + err.Message);
                }
                aa += 1;

                //this.gridView1.ExportToXls(sflg.FileName);
                //NPOI.xs book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(string.Format("test_{0}", aa));
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(xinka.Text);
                // 添加表头
                NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
                int      index             = 0;
                GridView ac    = this.active_nepCalaTable.GC;
                int      count = ac.Columns.Count;
                for (int i = 0; i < count; i++)
                {
                    string Caption = ac.Columns[i].Caption;
                    NPOI.SS.UserModel.ICell cell = row.CreateCell(index);
                    cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                    cell.SetCellValue(Caption);
                    index++;
                }

                // 添加数据

                DataTable dt = this.active_nepCalaTable.DDT;
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    index = 0;
                    row   = sheet.CreateRow(j + 1);
                    for (int k = 0; k < count; k++)
                    {
                        NPOI.SS.UserModel.ICell cell = row.CreateCell(index);
                        cell.SetCellType(NPOI.SS.UserModel.CellType.String);
                        //cell.SetCellValue(this.gridView1.GetRowCellValue(i, item).ToString());
                        cell.SetCellValue(dt.Rows[j][k].ToString());
                        index++;
                    }
                }
                NPOI.SS.UserModel.IRow r1 = sheet.GetRow(0);
                // 第一排
                NPOI.SS.UserModel.ICell cell1 = r1.CreateCell(12);
                cell1.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell1.SetCellValue("激发点距");
                NPOI.SS.UserModel.ICell cell11 = r1.CreateCell(13);
                cell11.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell11.SetCellValue(this.active_nepCalaTable.jifa_dianju.Text);

                // 第二排
                r1 = sheet.GetRow(1);
                NPOI.SS.UserModel.ICell cell2 = r1.CreateCell(12);
                cell2.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell2.SetCellValue("接收点距");
                NPOI.SS.UserModel.ICell cell21 = r1.CreateCell(13);
                cell21.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell21.SetCellValue(this.active_nepCalaTable.jieshou_dianju.Text);



                // 第三排
                r1 = sheet.GetRow(2);
                NPOI.SS.UserModel.ICell cell3 = r1.CreateCell(12);
                cell3.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell3.SetCellValue("接收点数");
                NPOI.SS.UserModel.ICell cell31 = r1.CreateCell(13);
                cell31.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell31.SetCellValue(this.active_nepCalaTable.jieshou_dianshu.Text);



                // 第四排
                r1 = sheet.GetRow(3);
                NPOI.SS.UserModel.ICell cell4 = r1.CreateCell(12);
                cell4.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell4.SetCellValue("激发线距");
                NPOI.SS.UserModel.ICell cell41 = r1.CreateCell(13);
                cell41.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell41.SetCellValue(this.active_nepCalaTable.jifa_xianju.Text);



                // 第五排
                r1 = sheet.GetRow(4);
                NPOI.SS.UserModel.ICell cell5 = r1.CreateCell(12);
                cell5.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell5.SetCellValue("接受线距");
                NPOI.SS.UserModel.ICell cell51 = r1.CreateCell(13);
                cell51.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell51.SetCellValue(this.active_nepCalaTable.jieshou_xianju.Text);

                // 第六排
                r1 = sheet.GetRow(5);
                NPOI.SS.UserModel.ICell cell6 = r1.CreateCell(12);
                cell6.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell6.SetCellValue("纵向滚动距离");
                NPOI.SS.UserModel.ICell cell61 = r1.CreateCell(13);
                cell61.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell61.SetCellValue(this.active_nepCalaTable.muban_zong.Text);

                // 第7排
                r1 = sheet.GetRow(6);
                NPOI.SS.UserModel.ICell cell7 = r1.CreateCell(12);
                cell7.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell7.SetCellValue("模板炮");
                NPOI.SS.UserModel.ICell cell71 = r1.CreateCell(13);
                cell71.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell71.SetCellValue(this.active_nepCalaTable.mobanpao.Text);


                // 第8排
                r1 = sheet.GetRow(7);
                NPOI.SS.UserModel.ICell cell8 = r1.CreateCell(12);
                cell8.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell8.SetCellValue("接收线数");
                NPOI.SS.UserModel.ICell cell81 = r1.CreateCell(13);
                cell81.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell81.SetCellValue(this.active_nepCalaTable.jieshou_xianshu.Text);



                // 第9排
                r1 = sheet.GetRow(8);
                NPOI.SS.UserModel.ICell cell9 = r1.CreateCell(12);
                cell9.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell9.SetCellValue("横向滚动距离");
                NPOI.SS.UserModel.ICell cell91 = r1.CreateCell(13);
                cell91.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell91.SetCellValue(this.active_nepCalaTable.muban_heng.Text);



                // 第10排
                r1 = sheet.GetRow(9);
                NPOI.SS.UserModel.ICell cell10 = r1.CreateCell(12);
                cell10.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell10.SetCellValue("布设接受线数");
                NPOI.SS.UserModel.ICell cell101 = r1.CreateCell(13);
                cell101.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell101.SetCellValue(this.active_nepCalaTable.bushe_jieshouxianshu.Text);



                // 第11排
                r1 = sheet.GetRow(10);
                NPOI.SS.UserModel.ICell cell1_1 = r1.CreateCell(12);
                cell1_1.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell1_1.SetCellValue("布设激发线数");
                NPOI.SS.UserModel.ICell cell111 = r1.CreateCell(13);
                cell111.SetCellType(NPOI.SS.UserModel.CellType.String);
                cell111.SetCellValue(this.active_nepCalaTable.bushe_jifaxianshu.Text);


                // 写入
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                book.Write(ms);
                //book = null;

                using (FileStream fs = new FileStream(sflg.FileName, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }

                ms.Close();
                ms.Dispose();
            }
            book = null;
            MessageBox.Show("保存成功了");
        }
예제 #53
0
        /// <summary>
        /// 取得データの正常受信時のイベント
        /// </summary>
        /// <param name="message"></param>
        public override void OnReceivedResponseData(CommunicationObject message)
        {
            var       data = message.GetResultData();
            DataTable tbl  = (data is DataTable) ? (data as DataTable) : null;

            switch (message.GetMessageName())
            {
            //ログイン
            case SEARCH_LOGIN:
                byte[] bin = tbl.Rows[0]["設定項目"] as byte[];
                if (bin == null)
                {
                    usercfg = new UserConfig();
                }
                else
                {
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(UserConfig));
                    var strm = new System.IO.MemoryStream(bin);
                    var val  = serializer.Deserialize(strm);
                    strm.Close();
                    usercfg = val as UserConfig;
                    if (usercfg == null)
                    {
                        usercfg = new UserConfig();
                    }
                }
                AppCommon.SetupConfig(this, usercfg);
                ccfg = (CommonConfig)usercfg.GetConfigValue(typeof(CommonConfig));
                if (ccfg == null)
                {
                    ccfg = new CommonConfig();
                }
                ccfg.ログイン時刻  = DateTime.Now;
                ccfg.ユーザID   = AppCommon.IntParse(UserID);
                ccfg.ユーザ名    = tbl.Rows[0]["担当者名"].ToString();
                ccfg.自社コード   = AppCommon.IntParse(tbl.Rows[0]["自社コード"].ToString());
                ccfg.自社販社区分  = AppCommon.IntParse(tbl.Rows[0]["自社販社区分"].ToString());
                ccfg.ライセンスID = LicenseID;
                // 変更
                ccfg.権限       = (int)tbl.Rows[0]["グループ権限ID"];
                ccfg.タブグループ番号 = (int?[])tbl.Rows[0]["タブグループ番号"];
                ccfg.プログラムID  = (string[])tbl.Rows[0]["プログラムID"];
                ccfg.使用可能FLG  = (Boolean[])tbl.Rows[0]["使用可能FLG"];
                ccfg.データ更新FLG = (Boolean[])tbl.Rows[0]["データ更新FLG"];

                usercfg.SetConfigValue(ccfg);

                lcfg = (LOGINConfig)usercfg.GetConfigValue(typeof(LOGINConfig));
                if (lcfg == null)
                {
                    lcfg      = new LOGINConfig();
                    lcfg.Top  = this.Top;
                    lcfg.Left = this.Left;
                    usercfg.SetConfigValue(lcfg);
                }
                this.Top  = lcfg.Top;
                this.Left = lcfg.Left;

                string pUserID   = tbl.Rows[0]["担当者ID"].ToString();
                string pPassword = tbl.Rows[0]["パスワード"].ToString();


                //【ログイン】UserID && Passwordが一致する場合 かつ【999999】エラーデータではない場合
                if (UserID == pUserID && Password == pPassword && pUserID != "999999")
                {
                    try
                    {
                        IsLoggedIn = true;
                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        //例外エラー表示
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    //【※ログイン失敗※】
                    SetFocusToTopControl();
                    this.ErrorMessage = "該当するデータが見つかりません";
                }
                break;

            //ログアウト
            case USER_LOGOUT:
                //this.Close();
                Environment.Exit(0);
                break;
            }
        }
예제 #54
0
        public void SetDataOld(List <ResourceLocationData> locations, List <string> labels)
        {
            var           tmpEntries             = new List <Entry>(locations.Count);
            var           providers              = new List <string>(10);
            var           providerIndices        = new Dictionary <string, int>(10);
            var           countEstimate          = locations.Count * 2 + labels.Count;
            var           internalIdToEntryIndex = new Dictionary <string, int>(countEstimate);
            var           internalIdList         = new List <string>(countEstimate);
            List <object> keys = new List <object>(countEstimate);

            var keyToIndex = new Dictionary <object, int>(countEstimate);
            var tmpBuckets = new Dictionary <int, List <int> >(countEstimate);

            for (int i = 0; i < locations.Count; i++)
            {
                var rld           = locations[i];
                int providerIndex = 0;
                if (!providerIndices.TryGetValue(rld.m_provider, out providerIndex))
                {
                    providerIndices.Add(rld.m_provider, providerIndex = providers.Count);
                    providers.Add(rld.m_provider);
                }

                int internalIdIndex = 0;
                if (!internalIdToEntryIndex.TryGetValue(rld.m_internalId, out internalIdIndex))
                {
                    internalIdToEntryIndex.Add(rld.m_internalId, internalIdIndex = internalIdList.Count);
                    internalIdList.Add(rld.m_internalId);
                }

                var e = new Entry()
                {
                    internalId = internalIdIndex, providerIndex = (byte)providerIndex, dependency = -1
                };
                if (rld.m_type == ResourceLocationData.LocationType.Int)
                {
                    AddToBucket(tmpBuckets, keyToIndex, keys, int.Parse(rld.m_address), tmpEntries.Count, 1);
                }
                else if (rld.m_type == ResourceLocationData.LocationType.String)
                {
                    AddToBucket(tmpBuckets, keyToIndex, keys, rld.m_address, tmpEntries.Count, 1);
                }
                if (!string.IsNullOrEmpty(rld.m_guid))
                {
                    AddToBucket(tmpBuckets, keyToIndex, keys, Hash128.Parse(rld.m_guid), tmpEntries.Count, 1);
                }
                if (rld.m_labelMask != 0)
                {
                    for (int t = 0; t < labels.Count; t++)
                    {
                        if ((rld.m_labelMask & (1 << t)) != 0)
                        {
                            AddToBucket(tmpBuckets, keyToIndex, keys, labels[t], tmpEntries.Count, 100);
                        }
                    }
                }

                tmpEntries.Add(e);
            }

            for (int i = 0; i < locations.Count; i++)
            {
                var rld        = locations[i];
                int dependency = -1;
                if (rld.m_dependencies != null && rld.m_dependencies.Length > 0)
                {
                    if (rld.m_dependencies.Length == 1)
                    {
                        dependency = keyToIndex[rld.m_dependencies[0]];
                    }
                    else
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (var d in rld.m_dependencies)
                        {
                            sb.Append(d);
                        }
                        var key      = sb.ToString().GetHashCode();
                        int keyIndex = -1;
                        foreach (var d in rld.m_dependencies)
                        {
                            var ki        = keyToIndex[d];
                            var depBucket = tmpBuckets[ki];
                            keyIndex = AddToBucket(tmpBuckets, keyToIndex, keys, key, depBucket[0], 10);
                        }
                        dependency = keyIndex;
                    }
                    var e = tmpEntries[i];
                    e.dependency  = dependency;
                    tmpEntries[i] = e;
                }
            }

            m_internalIds = internalIdList.ToArray();
            m_providerIds = providers.ToArray();
            var entryData = new byte[tmpEntries.Count * 4 * 3 + 4];
            var offset    = Serialize(entryData, tmpEntries.Count, 0);

            for (int i = 0; i < tmpEntries.Count; i++)
            {
                var e = tmpEntries[i];
                offset = Serialize(entryData, e.internalId, offset);
                offset = Serialize(entryData, e.providerIndex, offset);
                offset = Serialize(entryData, e.dependency, offset);
            }
            m_entryDataString = Convert.ToBase64String(entryData);

            int bucketEntryCount = 0;
            var bucketList       = new List <Bucket>(keys.Count);

            for (int i = 0; i < keys.Count; i++)
            {
                var        bucketIndex = keyToIndex[keys[i]];
                List <int> entries     = tmpBuckets[bucketIndex];
                bucketList.Add(new Bucket()
                {
                    entries = entries.ToArray()
                });
                bucketEntryCount += entries.Count;
            }

            var keyData = new List <byte>(bucketList.Count * 10);

            keyData.AddRange(BitConverter.GetBytes(bucketList.Count));
            int dataOffset = 4;

            for (int i = 0; i < bucketList.Count; i++)
            {
                var bucket = bucketList[i];
                bucket.dataOffset = dataOffset;
                bucketList[i]     = bucket;
                var key = keys[i];
                var kt  = key.GetType();
                if (kt == typeof(string))
                {
                    string str  = key as string;
                    byte[] tmp  = System.Text.Encoding.Unicode.GetBytes(str);
                    byte[] tmp2 = System.Text.Encoding.ASCII.GetBytes(str);
                    if (System.Text.Encoding.Unicode.GetString(tmp) == System.Text.Encoding.ASCII.GetString(tmp2))
                    {
                        keyData.Add((byte)KeyType.ASCIIString);
                        keyData.AddRange(tmp2);
                        dataOffset += tmp2.Length + 1;
                    }
                    else
                    {
                        keyData.Add((byte)KeyType.UnicodeString);
                        keyData.AddRange(tmp);
                        dataOffset += tmp.Length + 1;
                    }
                }
                else if (kt == typeof(UInt32))
                {
                    byte[] tmp = BitConverter.GetBytes((UInt32)key);
                    keyData.Add((byte)KeyType.UInt32);
                    keyData.AddRange(tmp);
                    dataOffset += tmp.Length + 1;
                }
                else if (kt == typeof(UInt16))
                {
                    byte[] tmp = BitConverter.GetBytes((UInt16)key);
                    keyData.Add((byte)KeyType.UInt16);
                    keyData.AddRange(tmp);
                    dataOffset += tmp.Length + 1;
                }
                else if (kt == typeof(Int32))
                {
                    byte[] tmp = BitConverter.GetBytes((Int32)key);
                    keyData.Add((byte)KeyType.Int32);
                    keyData.AddRange(tmp);
                    dataOffset += tmp.Length + 1;
                }
                else if (kt == typeof(int))
                {
                    byte[] tmp = BitConverter.GetBytes((UInt32)key);
                    keyData.Add((byte)KeyType.UInt32);
                    keyData.AddRange(tmp);
                    dataOffset += tmp.Length + 1;
                }
                else if (kt == typeof(Hash128))
                {
                    var    guid = (Hash128)key;
                    byte[] tmp  = System.Text.Encoding.ASCII.GetBytes(guid.ToString());
                    keyData.Add((byte)KeyType.Hash128);
                    keyData.AddRange(tmp);
                    dataOffset += tmp.Length + 1;
                }
            }
            m_keyDataString = Convert.ToBase64String(keyData.ToArray());

            var bucketData = new byte[4 + bucketList.Count * 8 + bucketEntryCount * 4];

            offset = Serialize(bucketData, bucketList.Count, 0);
            for (int i = 0; i < bucketList.Count; i++)
            {
                offset = Serialize(bucketData, bucketList[i].dataOffset, offset);
                offset = Serialize(bucketData, bucketList[i].entries.Length, offset);
                foreach (var e in bucketList[i].entries)
                {
                    offset = Serialize(bucketData, e, offset);
                }
            }
            m_bucketDataString = Convert.ToBase64String(bucketData);

#if SERIALIZE_CATALOG_AS_BINARY
            //TODO: investigate saving catalog as binary - roughly 20% size decrease, still needs a provider implementation
            var stream = new System.IO.MemoryStream();
            var bw     = new System.IO.BinaryWriter(stream);
            foreach (var i in m_internalIds)
            {
                bw.Write(i);
            }
            foreach (var p in m_providerIds)
            {
                bw.Write(p);
            }
            bw.Write(entryData);
            bw.Write(keyData.ToArray());
            bw.Write(bucketData);
            bw.Flush();
            bw.Close();
            stream.Flush();
            System.IO.File.WriteAllBytes("Library/catalog_binary.bytes", stream.ToArray());
            System.IO.File.WriteAllText("Library/catalog_binary.txt", Convert.ToBase64String(stream.ToArray()));
            stream.Close();
#endif
        }
예제 #55
0
        private byte[] SettingsSerialize()
        {
            var ms = new System.IO.MemoryStream();

            //4 byte - length of mask
            var mask_string = string.Empty;

            for (var i = 0; i < Masks.Length - 1; i++)
            {
                mask_string = mask_string + Masks[i] + ";";
            }
            mask_string = mask_string + Masks[Masks.Length - 1];
            var mask_len       = Encoding.Unicode.GetByteCount(mask_string);
            var mask_len_bytes = BitConverter.GetBytes(mask_len);

            ms.Write(mask_len_bytes, 0, 4);

            //mask_len bytes - mask
            var mask_bytes = Encoding.Unicode.GetBytes(mask_string);

            ms.Write(mask_bytes, 0, mask_len);

            //ignore attributes
            var ignore_attr_bytes = BitConverter.GetBytes(IgnoreFileAttributes);

            ms.Write(ignore_attr_bytes, 0, 1);

            //attributes
            //FileAttributes fa = (int)flagBoxFileAttributes.FlagValue;
            var fa_uint  = (uint)FileAttributes;
            var fa_bytes = BitConverter.GetBytes(fa_uint);

            ms.Write(fa_bytes, 0, 4);

            //ignore size
            var ignore_size_bytes = BitConverter.GetBytes(IgnoreSize);

            ms.Write(ignore_size_bytes, 0, 1);

            //size criteria
            var size_criteria_bytes = BitConverter.GetBytes((int)FilterSizeCriteria);

            ms.Write(size_criteria_bytes, 0, 4);

            //size minimum
            var size_min       = SizeMinimum;
            var size_min_bytes = BitConverter.GetBytes(size_min);

            ms.Write(size_min_bytes, 0, 8);

            //size maximum
            var size_max       = SizeMaximum;
            var size_max_bytes = BitConverter.GetBytes(size_max);

            ms.Write(size_max_bytes, 0, 8);

            //ignore create time
            var ignore_create_bytes = BitConverter.GetBytes(IgnoreTimeCreate);

            ms.Write(ignore_create_bytes, 0, 1);

            //create begin
            var create_begin_bytes = BitConverter.GetBytes(CreateBegin.ToFileTime());

            ms.Write(create_begin_bytes, 0, 8);

            //create end
            var create_end_bytes = BitConverter.GetBytes(CreateEnd.ToFileTime());

            ms.Write(create_end_bytes, 0, 8);

            //ignore modification
            var ignore_modif_bytes = BitConverter.GetBytes(IgnoreTimeModification);

            ms.Write(ignore_modif_bytes, 0, 1);

            //modification begin
            var modif_begin_bytes = BitConverter.GetBytes(ModificationBegin.ToFileTime());

            ms.Write(modif_begin_bytes, 0, 8);

            //modification end
            var modif_end_bytes = BitConverter.GetBytes(ModificationEnd.ToFileTime());

            ms.Write(modif_end_bytes, 0, 8);

            //ignore access
            var ignore_access_bytes = BitConverter.GetBytes(IgnoreTimeAccess);

            ms.Write(ignore_access_bytes, 0, 1);

            //access begin
            var access_begin_bytes = BitConverter.GetBytes(AccessBegin.ToFileTime());

            ms.Write(access_begin_bytes, 0, 8);

            //access end
            var access_end_bytes = BitConverter.GetBytes(AccessEnd.ToFileTime());

            ms.Write(access_end_bytes, 0, 8);

            //current directory only
            var current_dir_only_bytes = BitConverter.GetBytes(InCurrentDirectory);

            ms.Write(current_dir_only_bytes, 0, 1);

            //include subdirs
            var include_subdirs_bytes = BitConverter.GetBytes(InCurrentDirectoryWithSubdirs);

            ms.Write(include_subdirs_bytes, 0, 1);

            //current drive
            var current_drive_bytes = BitConverter.GetBytes(InCurrentDrive);

            ms.Write(current_dir_only_bytes, 0, 1);

            //all drives
            //byte[] all_drives_bytes = BitConverter.GetBytes(radioButtonLocalDrives.Checked);
            var all_drives_bytes = new byte[] { 0 };

            ms.Write(all_drives_bytes, 0, 1);

            //fixed drives
            var fixed_drives_bytes = BitConverter.GetBytes(InFixedDrives);

            ms.Write(fixed_drives_bytes, 0, 1);

            //removable drives
            var removable_drives_bytes = BitConverter.GetBytes(InRemovableDrives);

            ms.Write(removable_drives_bytes, 0, 1);

            //network drives
            var network_drives_bytes = BitConverter.GetBytes(InNetworkDrives);

            ms.Write(network_drives_bytes, 0, 1);

            ms.Position = 0;
            var ms_len = (int)ms.Length;
            var ret    = new byte[ms_len];

            ms.Read(ret, 0, ms_len);

            ms.Close();

            return(ret);
        }
예제 #56
0
        public ActionResult DownloadBreakdownPDF()
        {
            string url = ConfigurationManager.AppSettings["EndPointURL"].ToString();
            string userAuthenticationURI = url + "api/TMPUS/GetBreakdownReport";

            ASCIIEncoding encoder          = new ASCIIEncoding();
            var           token            = Request["token"];
            var           fromDate         = Request["FromDate"];
            var           toDate           = Request["ToDate"];
            string        serializedObject = "{'FeatureID':1,'FromDate':'" + fromDate + "','ToDate':'" + toDate + "'}";

            byte[] data = encoder.GetBytes(serializedObject);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Headers.Add("token", token);
            request.ContentLength = data.Length;
            //WebResponse response = request.GetResponse();
            request.GetRequestStream().Write(data, 0, data.Length);

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            List <BreakedownMasterModel> lstBreakedownMasterModel = new List <BreakedownMasterModel>();

            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var ApiStatus = reader.ReadToEnd();

                JsonData   dataaaa       = JsonMapper.ToObject(ApiStatus);
                JsonData[] jsonDataArray = dataaaa["ResponseData"].OfType <JsonData>().ToArray();

                for (int i = 0; i < jsonDataArray.Length - 1; i++)
                {
                    BreakedownMasterModel objBreakedownMasterModel = new BreakedownMasterModel();
                    JsonData BreakdownMaster = jsonDataArray[i]["breakedownMaster"];

                    objBreakedownMasterModel.ID = Convert.ToInt64(BreakdownMaster["ID"].ToString());
                    objBreakedownMasterModel.BreakdownIssueID    = BreakdownMaster["BreakdownIssueID"].ToString();
                    objBreakedownMasterModel.IssueDescription    = BreakdownMaster["IssueDescription"] == null ? string.Empty : BreakdownMaster["IssueDescription"].ToString();
                    objBreakedownMasterModel.ToolID              = Convert.ToInt64(BreakdownMaster["ToolID"].ToString());
                    objBreakedownMasterModel.IssueRaisedDateTime = Convert.ToDateTime(BreakdownMaster["IssueRaisedDateTime"].ToString());
                    objBreakedownMasterModel.Issuestatus         = BreakdownMaster["Issuestatus"].ToString();
                    lstBreakedownMasterModel.Add(objBreakedownMasterModel);
                }
            }

            string path = "";

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);
                BreakdownMaintenance_ITextSharpEvents itextSharpEvents = new BreakdownMaintenance_ITextSharpEvents();
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                writer.PageEvent = itextSharpEvents;
                document.Open();

                PdfPTable Info     = new PdfPTable(1);
                Paragraph paraData = new Paragraph("Data From: " + fromDate + "To: " + toDate);
                Info.AddCell(new PdfPCell(paraData));
                document.Add(Info);


                PdfPTable table = new PdfPTable(5);
                table.AddCell("ID");
                table.AddCell("Description");
                table.AddCell("Tool ID");
                table.AddCell("Date");
                table.AddCell("Status");
                foreach (BreakedownMasterModel item in lstBreakedownMasterModel)
                {
                    table.AddCell(item.BreakdownIssueID.ToString());
                    table.AddCell(item.IssueDescription.ToString());
                    table.AddCell(item.ToolID.ToString());
                    table.AddCell(item.IssueRaisedDateTime.ToString());
                    table.AddCell(item.Issuestatus.ToString());
                }

                document.Add(table);
                //Phrase phrase = new Phrase("This is from Phrase.");
                //document.Add(phrase);

                //Paragraph para = new Paragraph("This is from paragraph.");
                //document.Add(para);

                //string text = @"you are successfully created PDF file.";
                //Paragraph paragraph = new Paragraph();
                //paragraph.SpacingBefore = 10;
                //paragraph.SpacingAfter = 10;
                //paragraph.Alignment = Element.ALIGN_LEFT;
                //paragraph.Font = FontFactory.GetFont(FontFactory.HELVETICA, 12f, BaseColor.GREEN);
                //paragraph.Add(text);
                //document.Add(paragraph);

                Random r        = new Random(121);
                string fileName = Convert.ToDateTime(fromDate).ToString("MMddyyyy") + "-" + Convert.ToDateTime(toDate).ToString("MMddyyyy") + "-Preventive Maintenance" + r.Next() + ".pdf";
                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                var testFile = Path.Combine(Server.MapPath("~/Download"), fileName);
                System.IO.File.WriteAllBytes(testFile, bytes);
                path = "/Download/" + fileName;
            }
            TempData["path"] = path;
            return(RedirectToAction("PreventiveReport"));
        }
예제 #57
0
        protected void Save_Click(object sender, EventArgs e)
        {
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                String logo = "pic/logo_back.png";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(logo);
                img.Alignment = Element.ALIGN_RIGHT;
                img.ScaleToFit(205f, 205f);
                document.Add(img);
                document.Add(new Paragraph(" "));

                Paragraph title = new Paragraph("نموذج الاقرار الضريبي من الفترة: " + home.firstDate.Date + "الى " + home.lastDate.Date);
                title.Alignment = Element.ALIGN_CENTER;
                document.Add(title);
                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                PdfPTable table = new PdfPTable(5);


                //set width of the table
                table.TotalWidth  = (float)((PageSize.A4.Width / 2) * 1.7);
                table.LockedWidth = true;
                //set table alignment
                table.HorizontalAlignment = Element.ALIGN_CENTER;
                table.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;

                //create a cell objects and set their properties
                PdfPCell cell1 = new PdfPCell(new Phrase(" "));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BackgroundColor     = BaseColor.LIGHT_GRAY;


                PdfPCell amount = new PdfPCell(new Phrase("المبلغ (ريال)"));
                amount.HorizontalAlignment = Element.ALIGN_CENTER;
                amount.BackgroundColor     = BaseColor.LIGHT_GRAY;
                amount.Padding             = 5;
                amount.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell adjusment = new PdfPCell(new Phrase("مبلغ التعديل (ريال)"));
                adjusment.HorizontalAlignment = Element.ALIGN_CENTER;
                adjusment.BackgroundColor     = BaseColor.LIGHT_GRAY;
                adjusment.Padding             = 5;
                adjusment.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell vat = new PdfPCell(new Phrase("مبلغ ضريبة القيمة المضافة (ريال)"));
                vat.HorizontalAlignment = Element.ALIGN_CENTER;
                vat.BackgroundColor     = BaseColor.LIGHT_GRAY;
                vat.Padding             = 5;
                vat.HorizontalAlignment = Element.ALIGN_CENTER;


                //add cells to the tables

                table.AddCell(cell1);
                table.AddCell(cell1);
                table.AddCell(amount);
                table.AddCell(adjusment);
                table.AddCell(vat);

                PdfPCell sales = new PdfPCell(new Phrase("ضريبة القيمة المضافة على المبيعات"));
                sales.HorizontalAlignment = Element.ALIGN_CENTER;
                sales.BackgroundColor     = BaseColor.LIGHT_GRAY;
                sales.Rowspan             = 6;
                sales.Rotation            = 90;
                table.AddCell(sales);

                cell1 = new PdfPCell(new Phrase("1- المبيعات الخاضعة للنسبة الاساسية"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmount5.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdj5.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(s5.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("2- المبيعات للمواطنين( الخدمات الصحية الخاصة/التعليم الاهلي الخاص)"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountCitizens.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjCitizens.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("3- المبيعات المحلية الخاضعة للنسبة الصفرية"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmount0.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdj0.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("4- الصادرات"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountExport.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjExports.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("5- المبيعات المعفاه"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountExempt.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjExempt.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("6- اجمالي المبيعات"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sTotalAmount.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sTotalAdj.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalSale.Text));
                table.AddCell(vat);


                ////// purchase

                PdfPCell purchases = new PdfPCell(new Phrase("ضريبة القيمة المضافة على المشتريات"));
                purchases.HorizontalAlignment = Element.ALIGN_CENTER;
                purchases.BackgroundColor     = BaseColor.LIGHT_GRAY;
                purchases.Rowspan             = 6;
                purchases.Rotation            = 90;

                table.AddCell(purchases);


                cell1 = new PdfPCell(new Phrase("7- المشتريات الخاضعة للنسبة الاساسية"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmount5.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdj5.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(p5.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("8- الاستيرادات الخاضعة لضريبة القيمة المضافة بالنسبة الاساسية والتي تدفع في الجمارك"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountImports.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjImports.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(pImports.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("9- الاستيرادات الخاضعة لضريبة القيمة المضافة التي تطبق عليها الية الاحتساب العكسي"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountRCM.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjRCM.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(pRCM.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("10- المشتريات الخاضعة للنسبة الصفرية"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmount0.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAmount0.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("11- المشتريات المعفاه"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountExempt.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjExempt.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("12- اجمالي المشتريات"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pTotalAmount.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pTotalAdj.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalPurchases.Text));
                table.AddCell(vat);
                //

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("13- اجمالي ضريبة القيمة المضافة المستحقه عن الفترة الضريبية الحالية"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalVAT.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("14- تصحيحات من الفترات السابقة (بين +-5000 ريال)"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(correction.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("15- ضريبة القيمة المضافة التي تم ترحيلها من الفترة/الفترات السابقة"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(carried.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("صافي الضريبة المستحقة"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(net.Text));
                table.AddCell(vat);


                document.Add(table);
                document.Close();

                byte[] bytes = memoryStream.ToArray();

                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";

                Response.AddHeader("Content-Disposition", "attachment; filename=" + "من: " + home.firstDate.GetDateTimeFormats('d')[0] + " الى " + home.lastDate.GetDateTimeFormats('d')[0] + ".pdf");
                Response.Buffer = true;
                Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
        }
예제 #58
0
파일: NPOIHelper.cs 프로젝트: wpp1/Utils
        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int    i     = 0;
            int    j     = 0;
            int    count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
            {
                workbook = new XSSFWorkbook();
            }
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
            {
                workbook = new HSSFWorkbook();
            }

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return(-1);
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel

                #region excel下载
                // 写入到客户端
                MemoryStream ms = new System.IO.MemoryStream();
                workbook.Write(ms);
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.Charset     = "UTF8";
                //根据不同的浏览器设置对应的文件名
                string attachFilename = "";
                {
                    string enCodeFilename = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                    string userAgent      = HttpContext.Current.Request.Browser.Browser;
                    userAgent = userAgent.ToLower();
                    //IE浏览器
                    if (userAgent.IndexOf("ie") != -1 || userAgent.IndexOf("mozilla") != -1)
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                    //Opera浏览器只能采用filename*
                    else if (userAgent.IndexOf("opera") != -1)
                    {
                        attachFilename = @"filename*=UTF-8''" + enCodeFilename;
                    }
                    //FireFox浏览器
                    else if (userAgent.IndexOf("firefox") != -1)
                    {
                        attachFilename = @"filename*=" + enCodeFilename;
                    }
                    //遨游
                    else if (userAgent.IndexOf("chrome") != -1)
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                    else
                    {
                        attachFilename = @"filename=" + enCodeFilename;
                    }
                }
                HttpContext.Current.Response.AddHeader("Content-Disposition",
                                                       string.Format("attachment;{0}.xls", attachFilename));
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.End();
                workbook = null;
                ms.Close();
                ms.Dispose();
                #endregion

                return(count);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return(-1);
            }
        }
예제 #59
0
        protected void btnReport_Click(object sender, EventArgs e)
        {
            try
            {
                List <Entities.Location> listLocation = LocationBLL.getInstance().getAll();
                System.IO.MemoryStream   memoryStream = new System.IO.MemoryStream();
                text::Document           pdfDoc       = new text::Document(text::PageSize.A4, 10, 10, 10, 10);
                pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
                PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();

                String imagepath           = Server.MapPath("../../images/page-icons");
                iTextSharp.text.Image deas = iTextSharp.text.Image.GetInstance(imagepath + "/DEAS-logo.jpg");
                deas.ScaleToFit(140f, 120f);
                //Give space before image
                deas.SpacingBefore = 10f;
                //Give some space after the image
                deas.SpacingAfter = 1f;
                deas.Alignment    = text::Element.ALIGN_LEFT;
                pdfDoc.Add(deas);

                text::Paragraph title = new text::Paragraph();
                title.Font      = text::FontFactory.GetFont("dax-black", 32, new text::BaseColor(0, 51, 102));
                title.Alignment = text::Element.ALIGN_CENTER;
                title.Add("\n\n Reporte de Localizaciones\n\n");
                pdfDoc.Add(title);

                PdfPTable oPTable = new PdfPTable(4);
                oPTable.TotalWidth    = 100;
                oPTable.SpacingBefore = 20f;
                oPTable.SpacingAfter  = 30f;
                oPTable.AddCell("Sede");
                oPTable.AddCell("Edificio");
                oPTable.AddCell("Modulo");
                oPTable.AddCell("Estado");

                if (listLocation.Count > 0)
                {
                    foreach (Entities.Location pLocation in listLocation)
                    {
                        oPTable.AddCell(pLocation.oHeadquarters.description);
                        oPTable.AddCell(pLocation.building);
                        oPTable.AddCell(pLocation.module);
                        oPTable.AddCell((pLocation.State == 1 ? "Activo" : "Inactivo"));
                    }
                }
                else
                {
                    PdfPCell cell = new PdfPCell(new text::Phrase("No existen localizaciones registradas."));
                    cell.Colspan             = 5;
                    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    oPTable.AddCell(cell);
                }

                pdfDoc.Add(oPTable);
                pdfDoc.Close();

                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=Localizacion.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
예제 #60
-1
        public static void exportToExcel(DataTable table, string tableName, string workSheetName, string fileName)
        {
            // Create the excel file and add worksheet
            XLWorkbook workBook = new XLWorkbook();
            IXLWorksheet workSheet = workBook.Worksheets.Add(workSheetName);

            // Hardcode title and contents locations
            IXLCell titleCell = workSheet.Cell(2, 2);
            IXLCell contentsCell = workSheet.Cell(3, 2);

            //Pretty-up the title
            titleCell.Value = tableName;
            titleCell.Style.Font.Bold = true;
            titleCell.Style.Fill.BackgroundColor = XLColor.CornflowerBlue;
            titleCell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

            // Merge cells for title
            workSheet.Range(titleCell, workSheet.Cell(2, table.Columns.Count + 1)).Merge();

            // Insert table contents, and adjust for content width
            contentsCell.InsertTable(table);
            workSheet.Columns().AdjustToContents(1, 75);

            // Create a new response and flush it to a memory stream
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx;");
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.SaveAs(stream);
                stream.WriteTo(response.OutputStream);
                stream.Close();
            }
            response.End();
        }