Ejemplo n.º 1
1
 private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
     ref Stream responseStream, ref StreamReader reader)
 {
     if (request != null)
     {
         request = null;
     }
     if (response != null)
     {
         response.Close();
         response = null;
     }
     if (responseStream != null)
     {
         responseStream.Close();
         responseStream.Dispose();
         responseStream = null;
     }
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
Ejemplo n.º 2
0
        private static void CopyAsync(byte[] buffer, FileStream inputStream, Stream outputStream, TaskCompletionSource<object> tcs)
        {
            inputStream.ReadAsync(buffer).Then(read =>
            {
                if (read > 0)
                {
                    outputStream.WriteAsync(buffer, 0, read)
                                .Then(() => CopyAsync(buffer, inputStream, outputStream, tcs))
                                .Catch(ex =>
                                {
                                    inputStream.Close();
                                    outputStream.Close();
                                    tcs.SetException(ex);
                                });
                }
                else
                {
                    inputStream.Close();
                    outputStream.Close();

                    tcs.SetResult(null);
                }
            })
            .Catch(ex =>
            {
                inputStream.Close();
                outputStream.Close();

                tcs.SetException(ex);
            });
        }
Ejemplo n.º 3
0
 public Sims3Pack(string FileName)
     : this()
 {
     IsEncrypted = false;
     DataStore = File.Open(FileName, FileMode.Open, FileAccess.Read,FileShare.Read);
     try
     {
         Import();
     }
     catch (InvalidDataException e)
     {
         DataStore.Close();
         if (e.Message == "DBPP Not Supported") IsEncrypted = true;
         //throw e;
     }
     catch (XmlException)
     {
         DataStore.Close();
         IsCorrupt = true;
         // throw e;
     }
     catch (EndOfStreamException)
     {
         DataStore.Close();
         IsCorrupt = true;
         //throw e;
     }
 }
Ejemplo n.º 4
0
		public PckFile(Stream pckFile, Stream tabFile,int bpp,Palette pal,int imgHeight,int imgWidth)
		{
			if(tabFile!=null)
				tabFile.Position=0;

			pckFile.Position=0;

			byte[] info = new byte[pckFile.Length];
			pckFile.Read(info,0,info.Length);
			pckFile.Close();

			this.bpp=bpp;

			Pal=pal;

			uint[] offsets;
			
			if(tabFile!=null)
			{
				offsets= new uint[(tabFile.Length/bpp)+1];
				BinaryReader br = new BinaryReader(tabFile);

				if(bpp==2)
					for(int i=0;i<tabFile.Length/bpp;i++)
						offsets[i] = br.ReadUInt16();
				else
					for(int i=0;i<tabFile.Length/bpp;i++)
						offsets[i] = br.ReadUInt32();
				br.Close();
			}
			else
			{
				offsets = new uint[2];
				offsets[0]=0;
			}

			offsets[offsets.Length-1] = (uint)info.Length;

			for(int i=0;i<offsets.Length-1;i++)
			{
				byte[] imgDat = new byte[offsets[i+1]-offsets[i]];
				for(int j=0;j<imgDat.Length;j++)			
					imgDat[j] = info[offsets[i]+j];

				Add(new PckImage(i,imgDat,pal,this,imgHeight,imgWidth));
			}

			pckFile.Close();
			if(tabFile!=null)
				tabFile.Close();
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the file hash from a file stream.
        /// </summary>
        /// <returns>The file hash.</returns>
        /// <param name="fileStream">File stream.</param>
        public static string GetFileHash(Stream fileStream)
        {
			if (fileStream != null)
			{
				try
				{
					using (MD5 md5 = MD5.Create())
					{
						//calculate the hash of the stream.
						string resultString = BitConverter.ToString(md5.ComputeHash(fileStream)).Replace("-", "");

						return resultString;
					}
				}
				catch (IOException ioex)
				{
					Console.WriteLine ("IOException in GetFileHash(): " + ioex.Message);

					return String.Empty;
				}
				finally
				{
					//release the file (if we had one)
					fileStream.Close();
				}
			}     
			else
			{ 
				return String.Empty;
			}
        }
Ejemplo n.º 6
0
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var video = new MemoryStream(this.videoData))
                {
                    var length = (int)video.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
Ejemplo n.º 7
0
            public EasyWebRequest(string method, string userName, string password, string authID, string masterKey, string baseURL, string contraint)
            {
                request = WebRequest.Create(baseURL);
                request.ContentType = "text/xml";
                request.Credentials = new NetworkCredential(userName, password);
                request.Headers.Add("X-Parse-Application-Id: " + authID);
                request.Headers.Add("X-Parse-Master-Key: " + masterKey);

                if (method.Equals("GET") || method.Equals("POST"))
                    request.Method = method;
                else
                    throw new Exception("Invalid Method Type");

                string postData = contraint;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                request.ContentType = "application/x-www-form-urlencoded";

                request.ContentLength = byteArray.Length;

                dataStream = request.GetRequestStream();

                dataStream.Write(byteArray, 0, byteArray.Length);

                dataStream.Close();
 
            }
Ejemplo n.º 8
0
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {

              var channelBinding=   context.GetChannelBinding(ChannelBindingKind.Endpoint);

                var buffer = new byte[65536];
                using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)video.Length;
                    var bytesRead = 1;
                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpResponseException ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
            finally
            {
                outputStream.Close();
            }
        }
        private Task ConvertStream(HttpContent httpContent, Stream outputStream)
        {
            Task convertTask = new Task(() => {

                var convertSettings = new ConvertSettings {
                    CustomOutputArgs = "-map 0",
                    CustomInputArgs = "-vcodec h264"
                };

                var ffMpeg = new FFMpegConverter();
                ffMpeg.ConvertProgress += FfMpeg_ConvertProgress;
                ffMpeg.LogReceived += FfMpeg_LogReceived;

                //var task = ffMpeg.ConvertLiveMedia(Format.h264, "C:\\Work\\Test\\converted.avi", Format.avi, convertSettings);
                var task = ffMpeg.ConvertLiveMedia(Format.h264, outputStream, Format.mpeg, convertSettings);

                task.Start();

                var ffmpegStream = new FFMPegStream(task);
                var copyTask = httpContent.CopyToAsync(ffmpegStream);
                copyTask.Wait();
                ffmpegStream.Close();

                task.Wait();

                //                ffMpeg.ConvertMedia(@"C:\Work\Test\MyHomeSecureNode\devices\test\video.h264", "C:\\Work\\Test\\converted.avi", Format.avi);

                outputStream.Close();
            });

            convertTask.Start();
            return convertTask;
        }
Ejemplo n.º 10
0
 public void Close(Stream stream)
 {
     if (stream != null)
     {
         stream.Close();
     }
 }
Ejemplo n.º 11
0
 public Stream Decode(Stream stream)
 {
     const int bufsize = 32768;
     BinaryReader breader = new BinaryReader(stream);
     byte[] bbuffer = breader.ReadBytes(2);
     stream.Position = 0;
     if ((bbuffer[0] == 31) && (bbuffer[1] == 139)) {
         using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress)) {
             MemoryStream ms = new MemoryStream();
             using (BinaryReader zipreader = new BinaryReader(zipStream)) {
                 while (true) {
                     bbuffer = zipreader.ReadBytes(bufsize);
                     ms.Write(bbuffer, 0, bbuffer.Length);
                     if (bbuffer.Length < bufsize) {
                         break;
                     }
                 }
             }
             stream.Close();
             ms.Position = 0;
             return ms;
         }
     }
     return stream;
 }
Ejemplo n.º 12
0
 /// <summary>Creates a new AudioReader that can read the specified soundstream.</summary>
 /// <param name="s">The System.IO.Stream to read from.</param>
 /// <returns>A new OpenTK.Audio.AudioReader, which can be used to read from the specified sound stream.</returns>
 public AudioReader(Stream s)
 {
     try
     {
         lock (reader_lock)
         {
             foreach (AudioReader reader in readers)
             {
                 long pos = s.Position;
                 if (reader.Supports(s))
                 {
                     s.Position = pos;
                     implementation = (AudioReader)
                         reader.GetType().GetConstructor(
                             System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public |
                             System.Reflection.BindingFlags.Instance,
                             null,
                             new Type[] { typeof(Stream) },
                             null)
                         .Invoke(new object[] { s });
                     return;
                 }
                 s.Position = pos;
             }
         }
     }
     catch (Exception)
     {
         s.Close();
         throw;
     }
     throw new NotSupportedException("Could not find a decoder for the specified sound stream.");
 }
 public static IEnumerable<AzureSubscription> ImportAzureSubscription(Stream stream, ProfileClient azureProfileClient, string environment)
 {
     var publishData = DeserializePublishData(stream);
     PublishDataPublishProfile profile = publishData.Items.Single();
     stream.Close();
     return profile.Subscription.Select(s => PublishSubscriptionToAzureSubscription(azureProfileClient, profile, s, environment));
 }
Ejemplo n.º 14
0
        public static string UploadDocument(Stream stream, string filePath, string fileName)
        {
            int pos = fileName.LastIndexOf('.');
            string extFile = string.Empty;
            extFile = fileName.Substring(pos);
            string uploadFilename = Guid.NewGuid().ToString();
            try
            {
                stream.Seek(0, SeekOrigin.Begin);

                using (FileStream fileStream = new FileStream(filePath + uploadFilename + extFile, FileMode.Create, FileAccess.Write))
                {
                    byte[] buffer = new byte[Constants.BUFFER_SIZE];
                    int bufferSize = 0;
                    do
                    {
                        bufferSize = stream.Read(buffer, 0, buffer.Length);
                        fileStream.Write(buffer, 0, bufferSize);
                    } while (bufferSize > 0);
                    stream.Close();
                    fileStream.Close();
                }
            }
            catch (ApplicationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                log4net.Util.LogLog.Error(ex.Message, ex);
            }
            return uploadFilename + extFile;
        }
Ejemplo n.º 15
0
        async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[_chunkSize];
                using (var inputStream = OpenInputStream())
                {
                    var length = (int)inputStream.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = inputStream.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException)
            {
            }
            finally
            {
                outputStream.Close();
                outputStream.Dispose();
            }
        }
Ejemplo n.º 16
0
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var media = File.Open(_filename, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)media.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = media.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new BlogException(ex.Message, ex);
            }
            finally
            {
                outputStream.Close();
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Копирование из потока в поток
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        public static void CopyStream(Stream input, Stream output)
        {
            try
            {
                int bufferSize = 4096;

                byte[] buffer = new byte[bufferSize];

                while (true)
                {
                    int read = input.Read(buffer, 0, buffer.Length);

                    if (read <= 0)
                    {
                        input.Flush();
                        input.Close();

                        return;
                    }

                    output.Write(buffer, 0, read);
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex, "Streem copy error");
                output = null;
            }
        }
Ejemplo n.º 18
0
        public void CloseStream(Stream stream)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream is FileStream);

            stream.Close();
        }
Ejemplo n.º 19
0
 public object Deserialize(Stream buffer)
 {
     Alachisoft.NCache.Common.Protobuf.Command command = null;
     command = ProtoBuf.Serializer.Deserialize<Alachisoft.NCache.Common.Protobuf.Command>(buffer);
     buffer.Close();
     return command;
 }
 private void RestoreFromFile(Stream file)
 {
         //
         //
         using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                 using (var zip = new ZipInputStream(file)) {
                         try {
                                 while (true) {
                                         var ze = zip.GetNextEntry();
                                         if (ze == null) break;
                                         using (var f = new IsolatedStorageFileStream(ze.Name, FileMode.Create, store)) {
                                                 var fs = new byte[ze.Size];
                                                 zip.Read(fs, 0, fs.Length);
                                                 f.Write(fs, 0, fs.Length);
                                         }
                                 }
                         } catch {
                                 lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreFailed;
                                 App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreFailed);
                                 return;
                         } finally {
                                 file.Close();
                                 ClearOldBackupFiles();
                                 App.ViewModel.IsRvDataChanged = true;
                         }
                 }
         }
         lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreSuccess;
         App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreSuccess);
 }
Ejemplo n.º 21
0
        public async Task StreamVideo(Stream stream, HttpContent content, TransportContext transport)
        {
            try
            {
                var buffer = new byte[65536];
                var filename = Path.Combine(String.Format("{0}{1}video.{2}", System.Web.HttpContext.Current.Server.MapPath("~"), Constants.FilePath, _fileExtension));
                using (var file = File.Open(filename, FileMode.Open, FileAccess.Read))
                {
                    var videoLength = (int)file.Length;
                    var placeInFile = 1;

                    while (videoLength > 0 && placeInFile > 0)
                    {
                        placeInFile = file.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await stream.WriteAsync(buffer, 0, placeInFile);
                        videoLength -= placeInFile;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.InnerException);
            }
            finally
            {
                stream.Close();
            }
        }
Ejemplo n.º 22
0
		public PckFile(Stream pckFile, Stream tabFile,int bpp)
		{
			byte[] info = new byte[pckFile.Length];
			pckFile.Read(info,0,info.Length);
			pckFile.Close();

			this.pal=DefaultPalette;

			uint[] offsets = new uint[(tabFile.Length/bpp)+1];
			BinaryReader br = new BinaryReader(tabFile);

			if(bpp==2)
				for(int i=0;i<tabFile.Length/bpp;i++)
					offsets[i] = br.ReadUInt16();
			else
				for(int i=0;i<tabFile.Length/bpp;i++)
					offsets[i] = br.ReadUInt32();

			offsets[offsets.Length-1] = (uint)info.Length;

			images = new ArrayList(offsets.Length-1);

			for(int i=0;i<offsets.Length-1;i++)
			{
				byte[] imgDat = new byte[offsets[i+1]-offsets[i]];
				for(int j=0;j<imgDat.Length;j++)			
					imgDat[j] = info[offsets[i]+j];

				images.Add(new PckImage(i,imgDat,pal));

				if(LoadingEvent!=null)
					LoadingEvent(i,offsets.Length-1);
			}	
			br.Close();
		}
        public bool sendMessage_ToServer(String message)
        {
            bool state = false;
            try
            {
                tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 6000);
                if (tcpClient.Connected)
                {
                    stm = tcpClient.GetStream();
                    byte[] buffer = ascii.GetBytes(message);
                    stm.Write(buffer, 0, buffer.Length);
                    stm.Close();
                    state = true;
                }
                else
                {
                    Console.WriteLine("Server is unreachable.....");
                    state = false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Message Sending Failed...... \n" + e.StackTrace);

            }
            finally {
                tcpClient.Close();
            }

            return state;
        }
        public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
        {
            HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
            HSSFSheet sheet = workbook.GetSheet(SheetName);

            DataTable table = new DataTable();

            HSSFRow headerRow = sheet.GetRow(HeaderRowIndex);
            int cellCount = headerRow.LastCellNum;

            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }

            int rowCount = sheet.LastRowNum;

            for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++)
            {
                HSSFRow row = sheet.GetRow(i);
                DataRow dataRow = table.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                    dataRow[j] = row.GetCell(j).ToString();
            }

            ExcelFileStream.Close();
            workbook = null;
            sheet = null;
            return table;
        }
Ejemplo n.º 25
0
        public static void SaveStreamToFile(Stream stream, string cachePath)
        {
            IsolatedStorageFileStream fileStream = null;
            try
            {
                byte[] buffer = new byte[stream.Length];

                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                if (!store.FileExists(cachePath))
                {
                    fileStream = store.CreateFile(cachePath);

                    stream.Read(buffer, 0, buffer.Length);
                    fileStream.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
Ejemplo n.º 26
0
        private static byte[ ] ComputeMovieHash( Stream input )
        {
            long lhash, streamsize;
            streamsize = input.Length;
            lhash = streamsize;

            long i = 0;
            byte[ ] buffer = new byte[ sizeof ( long ) ];
            while ( i < 65536 / sizeof ( long ) && ( input.Read( buffer, 0, sizeof ( long ) ) > 0 ) )
            {
                i++;
                lhash += BitConverter.ToInt64( buffer, 0 );
            }

            input.Position = Math.Max( 0, streamsize - 65536 );
            i = 0;
            while ( i < 65536 / sizeof ( long ) && ( input.Read( buffer, 0, sizeof ( long ) ) > 0 ) )
            {
                i++;
                lhash += BitConverter.ToInt64( buffer, 0 );
            }
            input.Close( );
            byte[ ] result = BitConverter.GetBytes( lhash );
            Array.Reverse( result );
            return result;
        }
Ejemplo n.º 27
0
        private void CopyWithLambda(Stream s, Stream d, ref long total)
        {
            var buffer = new byte[4096];
            try
            {
                while (true)
                {
                    var read = s.Read(buffer, 0, 4096);
                    if (read == 0)
                        break;
                    var tmpTotal = Interlocked.Add(ref total, read);
					if (VetoTransfer(tmpTotal, new ArraySegment<byte>(buffer, 0, read)))
                    {
                        //force close of both streams
                        s.Close();
                        d.Close();
                        throw new Exception("Transfer vetoed!");
                    }

                    d.Write(buffer, 0, read);
                    if (IsEndOfChunkEncoding(buffer, 0, read))
                    {
                        break;
                    }
                }
            }
            catch (IOException)
            {
            }

        }
Ejemplo n.º 28
0
        // Source: http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx
        public static String Decode(WebResponse response, Stream stream)
        {
            String charset = null;
            String contentType = response.Headers["content-type"];
            if(contentType != null)
            {
                int index = contentType.IndexOf("charset=");
                if(index != -1)
                {
                    charset = contentType.Substring(index + 8);
                }
            }

            MemoryStream data = new MemoryStream();
            byte[] buffer = new byte[1024];
            int read = stream.Read(buffer, 0, buffer.Length);
            while(read > 0)
            {
                data.Write(buffer, 0, read);
                read = stream.Read(buffer, 0, buffer.Length);
            }
            stream.Close();

            Encoding encoding = Encoding.UTF8;
            try
            {
                if(charset != null)
                    encoding = Encoding.GetEncoding(charset);
            }
            catch { }

            data.Seek(0, SeekOrigin.Begin);
            StreamReader streamReader = new StreamReader(data, encoding);
            return streamReader.ReadToEnd();
        }
Ejemplo n.º 29
0
        /// <summary>
        /// HTTPS POST
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStream"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpPost(string url ,Stream  postStream,Encoding encoding = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postStream != null ? postStream.Length : 0;
            request.Accept = "text/html,application/xhtml+xml,application/xml";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Winodws NT 6.1; WOW64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            if (postStream != null)
            {
                postStream.Position = 0;
                Stream requestStream = request.GetRequestStream();
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead=postStream.Read(buffer,0,buffer.Length))!=0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                postStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
                {
                    string retString = myStreamReader.ReadToEnd();

                    return retString;
                }
            }
        }
        public void loadDDS(Stream input)
        {
            this.lockImage = true;

            ddsFile.Load(input);
            pictureBox1.Image = ddsFile.Image();

            toolStripStatusLabel1.Text = "";
            toolStripStatusLabel2.Text = "W: " + ddsFile.m_header.m_width.ToString();
            toolStripStatusLabel3.Text = "H: " + ddsFile.m_header.m_height.ToString();
            if (ddsFile.m_header.m_pixelFormat.m_rgbBitCount.ToString() != "0" && ddsFile.m_header.m_pixelFormat.m_rgbBitCount.ToString() != "")
            {
                toolStripStatusLabel4.Text = ddsFile.m_header.m_pixelFormat.m_rgbBitCount.ToString() + "bit";
                toolStripStatusLabel4.Visible = true;
            }
            else
            {
                toolStripStatusLabel4.Visible = false;
            }

            toolStripStatusLabel5.Text = ddsFile.m_header.fileFormat;

            chkShowRed.Checked = true;
            chkShowGreen.Checked = true;
            chkShowBlue.Checked = true;
            chkShowAlpha.Checked = false;

            input.Close();

            this.lockImage = false;
        }
Ejemplo n.º 31
0
 public void DisposeBasic()
 {
     Content?.Dispose();
     Content = null;
     DisposableStream?.Close();
     DisposableStream?.Dispose();
     DisposableStream = null;
 }
Ejemplo n.º 32
0
 /// <summary>Removes any existing binding</summary>
 public void Unbind()
 {
     if (_boundStream != _rootStream)
     {
         _boundStream?.Close();
     }
     _boundStream      = null;
     ArchiveMemberPath = null;
     BoundIndex        = null;
 }
Ejemplo n.º 33
0
 /// <summary>
 /// <para>Closes the underlying FTP response stream, but does not close control connection</para>
 /// </summary>
 public override void Close()
 {
     if (NetEventSource.Log.IsEnabled())
     {
         NetEventSource.Enter(this);
     }
     _responseStream?.Close();
     if (NetEventSource.Log.IsEnabled())
     {
         NetEventSource.Exit(this);
     }
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Read data from file
        /// </summary>
        /// <param name="fileName">File name</param>
        /// <param name="path">Path to file</param>
        /// <param name="attempts">Number of attempts</param>
        /// <returns>Collection of items of type T</returns>
        public static async Task <T> ReadDataAsync(string fileName, string path, int attempts = 0)
        {
            T      readedObjects = default(T);
            Stream xmlStream     = null;

            try
            {
                XmlSerializer serializ = new XmlSerializer(typeof(T));
                xmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName);

                using (xmlStream)
                {
                    readedObjects = (T)serializ.Deserialize(xmlStream);
                }

                if (readedObjects != null)
                {
                    return(readedObjects);
                }
                else
                {
                    return(default(T));
                }
            }

            // When is file unavailable - 10 attempts is enough
            catch (Exception s) when((s.Message.Contains("denied")) && (attempts < 10))
            {
                return(await ReadDataAsync(fileName, path, attempts + 1));
            }

            catch (Exception e)
            {
                await LogService.AddLogMessageAsync(e.Message);
            }

            finally
            {
                xmlStream?.Close();
            }

            return(default(T));
        }
Ejemplo n.º 35
0
        public byte[] GetReportDefinition(PreviewItemContext itemContext)
        {
            byte[]    value = null;
            Exception ex    = null;

            try
            {
                if (itemContext.DefinitionSource == DefinitionSource.Direct)
                {
                    m_directReportDefinitions.TryGetValue(itemContext.PreviewStorePath, out value);
                }
                else
                {
                    Stream stream = null;
                    try
                    {
                        if (itemContext.DefinitionSource == DefinitionSource.File)
                        {
                            stream = File.OpenRead(itemContext.PreviewStorePath);
                        }
                        else if (itemContext.DefinitionSource == DefinitionSource.EmbeddedResource)
                        {
                            stream = itemContext.EmbeddedResourceAssembly.GetManifestResourceStream(itemContext.PreviewStorePath);
                        }
                        value = new byte[stream.Length];
                        stream.Read(value, 0, (int)stream.Length);
                    }
                    finally
                    {
                        stream?.Close();
                    }
                }
            }
            catch (Exception ex2)
            {
                ex = ex2;
            }
            if (value == null || ex != null)
            {
                throw new ApplicationException(ProcessingStrings.MissingDefinition(itemContext.ItemName), ex);
            }
            return(value);
        }
Ejemplo n.º 36
0
        private async void ConnectionForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _tokenSource?.Cancel();

            if (_clientTask != null)
            {
                await _clientTask;
                _clientTask.Dispose();
            }

            if (_listenerTask != null)
            {
                await _listenerTask;
                _listenerTask.Dispose();
            }

            _client?.Dispose();
            Stream?.Close();
        }
Ejemplo n.º 37
0
        private void PostZJUWLAN(string username, string password)//只负责POST用户名与密码,不负责判断WIFI是否连上
        {
            var             data            = $"action=login&username={username}&password={password}&ac_id=3&user_ip=&nas_ip=&user_mac=&save_me=1&ajax=1";
            string          url             = "https://net.zju.edu.cn/include/auth_action.php";
            HttpWebResponse response        = null;
            HttpWebRequest  request         = null;
            Stream          myRequestStream = null;

            request               = (HttpWebRequest)WebRequest.Create(url);
            request.Method        = "POST";
            request.KeepAlive     = false;
            request.UserAgent     = "Mozilla/5.0 (Windows NT 6.1; WOW64; Tridene/7.0; rv:11.0) like Gecko";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(data);
            request.Host          = "net.zju.edu.cn";

            for (int i = 0; i < 15; i++)
            {
                try
                {
                    myRequestStream = request.GetRequestStream();
                    var myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                    myStreamWriter.Write(data);
                    myStreamWriter.Close();
                    //Thread.Sleep(10);
                    response = (HttpWebResponse)request.GetResponse();
                    if (response == null || response.StatusCode != HttpStatusCode.OK)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                catch
                {
                    //Thread.Sleep(10);
                    continue;
                }
            }
            myRequestStream?.Close();
        }
Ejemplo n.º 38
0
    public override T FromStream <T>(Stream stream)
    {
        if (typeof(Stream).IsAssignableFrom(typeof(T)))
        {
            return((T)(object)stream);
        }

        try
        {
            using var streamReader = new StreamReader(stream, DefaultEncoding, true, 1024, leaveOpen: true);
            using var jsonReader   = new JsonTextReader(streamReader);

            return(SerializerSettings.CreateSerializer().Deserialize <T>(jsonReader));
        }
        finally
        {
            stream?.Close();
        }
    }
Ejemplo n.º 39
0
        private void OpenFile()
        {
            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter           = Resources.supportedfiles_opendialogExtension;
                openFileDialog.FilterIndex      = 1;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (Regex.IsMatch(Path.GetExtension(openFileDialog.FileName)?.ToLower(), @"^.*\.(xml|xlsx|xls|csv)$"))
                    {
                        Stream openedDocument = null;
                        try
                        {
                            // Load the contents of the file into dataGrid
                            openedDocument      = openFileDialog.OpenFile();
                            dataGrid.DataSource = (Path.GetExtension(openFileDialog.FileName)?.ToLower() == ".xml")
                                ? ImpExpUtilities.GetXmlData(openedDocument).Tables[0]                        // if it's an xml document
                                : ImpExpUtilities.GetSpreadSheetData(openedDocument as FileStream).Tables[0]; // else if (xlsx|xls|csv)
                            EnableCtrl(true);

                            currentOpenDocumentPath = openFileDialog.FileName;
                            this.Text = Resources.title + '[' + openFileDialog.SafeFileName + ']'; // Change the Forms title to currentOpenDoc #10
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(Resources.OpenDoc_fail_msg, Resources.fail,
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            openedDocument?.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show(Resources.OpenDoc_fail_msg, Resources.fail, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="picUrl">图片Http地址</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param>
        ///<param name="actualFilePath">压缩之后保存路径(不压缩就不用传参)</param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public static string DownloadPicture(string picUrl, string savePath, int timeOut = -1, string actualFilePath = "", string userId = "")
        {
            var         value    = "";
            WebResponse response = null;
            Stream      stream   = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1)
                {
                    request.Timeout = timeOut;
                }
                response = request.GetResponse();
                stream   = response.GetResponseStream();
                if (!response.ContentType.ToLower().StartsWith("Text/"))
                {
                    var isResult = SaveBinaryFile(response, savePath);
                    if (isResult)
                    {
                        if (!string.IsNullOrEmpty(actualFilePath))
                        {
                            value = GetPicThumbnail(savePath, actualFilePath, 50, 50, 96, userId);
                            if (File.Exists(savePath) && !PublicTalkMothed.IsFileInUsing(savePath))
                            {
                                File.Delete(savePath);
                            }
                        }
                    }
                }
            }
            catch
            {
                return(value);
            }
            finally
            {
                stream?.Close();
                response?.Close();
            }
            return(value);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(this HttpWebResponse rsp, Encoding encoding)
        {
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return(reader.ReadToEnd());
            }
            finally
            {
                // 释放资源
                reader?.Close();
                stream?.Close();
                rsp?.Close();
            }
        }
        public void Destroy()
        {
            try
            {
                TcpClient?.Client?.Close();
                TcpClient = null;

                RestartableStream?.Close();
                RestartableStream = null;


                Stream?.Close();
                Stream = null;

                Buffer = null;
            }
            catch
            {
            }
        }
Ejemplo n.º 43
0
            internal static OnDemandMetadata DeserializeOnDemandMetadata(IChunkFactory chunkFactory, GlobalIDOwnerCollection globalIDOwnerCollection)
            {
                Stream stream = null;

                try
                {
                    stream = chunkFactory.GetChunk("Metadata", Microsoft.ReportingServices.ReportProcessing.ReportProcessing.ReportChunkTypes.Main, ChunkMode.Open, out string _);
                    IntermediateFormatReader intermediateFormatReader = new IntermediateFormatReader(stream, default(GroupTreeRIFObjectCreator), globalIDOwnerCollection);
                    OnDemandMetadata         onDemandMetadata         = (OnDemandMetadata)intermediateFormatReader.ReadRIFObject();
                    Global.Tracer.Assert(onDemandMetadata != null, "(null != odpMetadata)");
                    stream.Close();
                    stream = null;
                    onDemandMetadata.OdpChunkManager = new OnDemandProcessingManager();
                    return(onDemandMetadata);
                }
                finally
                {
                    stream?.Close();
                }
            }
Ejemplo n.º 44
0
        protected virtual void OnDisconnect()
        {
            if (_receiveLoopTask != null)
            {
                //if (_sendKeepAliveLoopTask == null)
                //    await _receiveLoopTask.ConfigureAwait(false);
                //else
                //    await Task.WhenAll(_receiveLoopTask, _sendKeepAliveLoopTask).ConfigureAwait(false);
                //System.Diagnostics.Debug.Assert(_receiveLoopCancellationTokenSource == null);
                //System.Diagnostics.Debug.Assert(_sendKeepAliveLoopCancellationTokenSource == null);
                //_receiveLoopTask?.Dispose();
                //_sendKeepAliveLoopTask?.Dispose();
                _receiveLoopTask       = null;
                _sendKeepAliveLoopTask = null;
            }

            _connectedStream?.Close();
            _connectedStream = null;
            _sendingStream   = null;
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Initializes a new instance of the PdfDocument class with the provided path.
        /// </summary>
        /// <param name="path">Path to the PDF document.</param>
        /// <param name="password">Password for the PDF document.</param>
        public static PdfDocument Load(string path, string password)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            Stream fileStream = null;

            try
            {
                fileStream = FileUtils.OpenReadOnly(path);
                return(Load(fileStream, password));
            }
            catch (Exception)
            {
                fileStream?.Close();
                throw;
            }
        }
Ejemplo n.º 46
0
            private static void SerializeSortFilterEventInfo(OnDemandProcessingContext odpContext)
            {
                ReportSnapshot reportSnapshot = odpContext.OdpMetadata.ReportSnapshot;

                if (reportSnapshot != null && reportSnapshot.SortFilterEventInfo != null)
                {
                    Stream stream = null;
                    try
                    {
                        stream = odpContext.ChunkFactory.GetChunk("SortFilterEventInfo", Microsoft.ReportingServices.ReportProcessing.ReportProcessing.ReportChunkTypes.Interactivity, ChunkMode.OpenOrCreate, out string _);
                        stream.Seek(0L, SeekOrigin.End);
                        new IntermediateFormatWriter(stream, odpContext.GetActiveCompatibilityVersion(), odpContext.ProhibitSerializableValues).Write(reportSnapshot.SortFilterEventInfo);
                        reportSnapshot.SortFilterEventInfo = null;
                    }
                    finally
                    {
                        stream?.Close();
                    }
                }
            }
Ejemplo n.º 47
0
        internal override void Post(IQObject qObject)
        {
            XElement parent = new XElement("qdbapi");;

            qObject.BuildXmlPayload(ref parent);
            var bytes = Encoding.UTF8.GetBytes(parent.ToString());
            //File.AppendAllText(@"C:\Temp\QBDebugLog.txt", "**Sent->>" + qObject.Uri + " " + QUICKBASE_HEADER + qObject.Action + "\r\n" + qObject.XmlPayload + "\r\n");
            Stream      requestStream  = null;
            WebResponse webResponse    = null;
            Stream      responseStream = null;
            XElement    xml;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(qObject.Uri);
                request.Method          = METHOD;
                request.ProtocolVersion = HttpVersion.Version11;
                request.ContentType     = CONTENT_TYPE;
                request.ContentLength   = bytes.Length;
                request.KeepAlive       = false;
                request.Timeout         = 300000;
                request.Headers.Add(QUICKBASE_HEADER + qObject.Action);

                requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);

                webResponse    = request.GetResponse();
                responseStream = webResponse.GetResponseStream();
                xml            = XElement.Load(responseStream);
                //File.AppendAllText(@"C:\Temp\QBDebugLog.txt", "**Received-<<\r\n" + xml.CreateNavigator().InnerXml + "\r\n");
            }
            finally
            {
                requestStream?.Close();
                responseStream?.Close();
                webResponse?.Close();
            }

            Http.CheckForException(xml);
            Response = xml;
        }
Ejemplo n.º 48
0
        public static bool HttpPost(string url, byte[] Data, out string HttpWebResponseString, int timeout, string requestHeader = "")
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebResponseString = "";
            HttpWebRequest httpWebRequest = null;
            Stream         stream         = null;

            try
            {
                httpWebRequest             = (WebRequest.Create(url) as HttpWebRequest);
                httpWebRequest.Method      = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.UserAgent   = DefaultUserAgent;
                httpWebRequest.Timeout     = timeout;
                if (!string.IsNullOrEmpty(requestHeader))
                {
                    AddRequestHeaders(httpWebRequest, requestHeader);
                }
                if (Data != null)
                {
                    requestEncoding.GetString(Data);
                    stream = httpWebRequest.GetRequestStream();
                    stream.Write(Data, 0, Data.Length);
                }
                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                HttpWebResponseString = ReadHttpWebResponse(httpWebResponse);
                return(true);
            }
            catch (Exception ex)
            {
                HttpWebResponseString = ex.ToString();
                return(false);
            }
            finally
            {
                stream?.Close();
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Read data from file
        /// </summary>
        /// <param name="Attempts">Number of attempts</param>
        /// <returns>Collection of items of type T</returns>
        public async Task ReadDataAsync(int Attempts = 0)
        {
            object ReadedObjects = null;
            Stream XmlStream     = null;

            try
            {
                XmlSerializer Serializ = new XmlSerializer(typeof(UpdateHistoryFile));
                XmlStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(FileName);

                using (XmlStream)
                {
                    ReadedObjects = (UpdateHistoryFile)Serializ.Deserialize(XmlStream);
                }

                if (ReadedObjects != null)
                {
                    LastVersion = new Version(((UpdateHistoryFile)ReadedObjects).LastVersion);
                    UpdateList  = ((UpdateHistoryFile)ReadedObjects).UpdateList;
                }
                else
                {
                    LastVersion = new Version(0, 0, 0, 0);
                    UpdateList  = new List <UpdateItem>();
                }
            }

            // When is file unavailable - 10 attempts is enough
            catch (Exception s) when((s.Message.Contains("denied")) && (Attempts < 10))
            {
                await ReadDataAsync(Attempts + 1);
            }

            catch
            {
                XmlStream?.Close();
                XmlStream?.Dispose();
                LastVersion = new Version(0, 0, 0, 0);
                UpdateList  = new List <UpdateItem>();
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="pictureUrl">图片Http地址</param>
        /// <param name="filePath">保存路径</param>
        /// <param name="folder">目录(前后不带/)</param>
        /// <param name="fileName"></param>
        /// <param name="fileExtension">文件后缀(以.开头)</param>
        /// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param>
        /// <returns></returns>
        public static bool DownloadPicture(string pictureUrl, out string filePath, string folder = "WeChat", string fileName = null, string fileExtension = ".png", int timeOut = -1)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
            filePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + folder + "\\" + fileName + fileExtension;
            //是否存在文件夹,没存在则创建
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + folder + "\\"))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + folder + "\\");
            }
            bool        result   = false;
            WebResponse response = null;
            Stream      stream   = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pictureUrl);
                if (timeOut != -1)
                {
                    request.Timeout = timeOut;
                }
                response = request.GetResponse();
                stream   = response.GetResponseStream();
                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    result = SaveBinaryFile(response, filePath);
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteException(e);
            }
            finally
            {
                stream?.Close();
                response?.Close();
            }
            return(result);
        }
Ejemplo n.º 51
0
        private void openXlsFile()
        {
            using (var openFileDialog = new OpenFileDialog()){
                //openFileDialog.InitialDirectory = @"%HOMEPATH%";
                openFileDialog.Filter           = Resources.XMLGUI_xlsfile_dialogextension;
                openFileDialog.FilterIndex      = 1;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (Regex.IsMatch(Path.GetExtension(openFileDialog.FileName)?.ToLower(), @"^.*\.(xlsx|xls|csv)$"))
                    {
                        Stream xlsSheet = null;
                        try
                        {
                            // Load the contents of the file into dataGrid
                            xlsSheet            = openFileDialog.OpenFile();
                            dataGrid.DataSource = XmlUtils.getSpreadSheetData(xlsSheet as FileStream).Tables[0];
                            enableCtrl(true);
                            // TODO: either add export Excel Sheets by saving or remove option.
                            //currentOpenDocumentPath = openFileDialog.FileName; // Set the currentOpenPath variable to be used later for saving
                            this.Text = Resources.XmlGUI_title_ + '[' + openFileDialog.SafeFileName + ']'; // Change the Forms title to currentOpenDoc #10
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(Resources.XmlGUI_OpenXlsSheet_fail_msg, Resources.XMLGUI__fail,
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            // Fixes #29 file lock issue
                            xlsSheet?.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show(Resources.XmlGUI_DragDrop_wrongExt_msg, Resources.XMLGUI__fail, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
Ejemplo n.º 52
0
        public void WriteLine(string msg)
        {
            var now = DateTime.UtcNow;

            lock (this)
            {
                #region Roll the file
                if (_seed++ == 0)
                {
                    if (_openedAt.Date != now.Date)
                    {
                        _writer?.Close();
                        _stream?.Close();
                        Directory.CreateDirectory(LogPath);
                        _stream = File.Open(Path.Combine(LogPath
                                                         , now.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + $"_p{Process.GetCurrentProcess().Id}.log")
                                            , FileMode.Append, FileAccess.Write, FileShare.Read);
                        _openedAt = now.Date;
                        _writer   = new StreamWriter(_stream);

                        #region Remove Old Files
                        var toDelete = new DirectoryInfo(LogPath)
                                       .GetFiles()
                                       .Where(x => (now - x.CreationTimeUtc).TotalDays > 21)
                                       .ToArray();

                        foreach (var item in toDelete)
                        {
                            try
                            {
                                File.Delete(item.FullName);
                            }
                            catch { }
                        }
                        #endregion
                    }
                }
                #endregion
                _writer.WriteLine($"[{now:MM/dd HH:mm:ss.fff}] {msg}");
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Closes this instance.
        /// </summary>
        public override void Close()
        {
            try
            {
                _responseStream?.Close();
            }
            catch (Exception)
            {
                // TODO manage error
            }

            try
            {
                _socksConnection.Disconnect(false);
                _socksConnection?.Close();
            }
            catch (Exception)
            {
                // TODO manage error
            }
        }
Ejemplo n.º 54
0
        private static bool AvailableToDelete(DirectoryInfo application)
        {
            foreach (FileInfo fI in application.GetFiles())
            {
                Stream checkStream = null;
                try
                {
                    checkStream = fI.OpenRead();
                }
                catch (Exception)
                {
                    return(false);
                }
                finally
                {
                    checkStream?.Close();
                }
            }

            return(true);
        }
Ejemplo n.º 55
0
        protected void Dispose(bool disposing)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(SimpleLog));
            }

            try
            {
                Stream?.Close();
            }
            catch
            {
            }

            disposed = true;
            if (disposing)
            {
                GC.SuppressFinalize(this);
            }
        }
Ejemplo n.º 56
0
        private async Task <OperationResult <MediaModel> > UploadPhoto(Stream photoStream)
        {
            try
            {
                photoStream.Position = 0;
                var request      = new UploadMediaModel(BasePresenter.User.UserInfo, photoStream, Path.GetExtension(".jpg"));
                var serverResult = await Presenter.TryUploadMedia(request);

                return(serverResult);
            }
            catch (Exception ex)
            {
                AppSettings.Reporter.SendCrash(ex);
                return(new OperationResult <MediaModel>(new AppError(LocalizationKeys.PhotoProcessingError)));
            }
            finally
            {
                photoStream?.Close();
                photoStream?.Dispose();
            }
        }
Ejemplo n.º 57
0
        private void ReleaseResources()
        {
            if (Reader != null)
            {
                // closing _reader will also close underlying _stream
                Reader.Close();
                Reader = null;
            }
            else
            {
                _stream?.Close();
            }

            _stream = null;

            if (_cachedStringWriter != null)
            {
                _cachedStringWriter.Close();
                _cachedStringWriter = null;
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// 从http下载图片
        /// </summary>
        /// <param name="picUrl">图片Http地址</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param>
        ///<param name="actualFilePath">压缩之后保存路径(不压缩就不用传参)</param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public static string DownloadPictureFromHttp(string picUrl, string savePath, int timeOut = -1)
        {
            if (File.Exists(savePath))
            {
                return(savePath);
            }
            var         value    = "";
            WebResponse response = null;
            Stream      stream   = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1)
                {
                    request.Timeout = timeOut;
                }
                response = request.GetResponse();
                stream   = response.GetResponseStream();
                if (!response.ContentType.ToLower().StartsWith("Text/"))
                {
                    var isResult = SaveBinaryFile(response, savePath);
                    if (isResult)
                    {
                        value = savePath;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("[下载图片失败]:图片原始Url>>>" + picUrl + ">>>错误信息:" + ex.StackTrace);
                return(value);
            }
            finally
            {
                stream?.Close();
                response?.Close();
            }
            return(value);
        }
Ejemplo n.º 59
0
        private TResponse InternalSubmit(Request <TResponse> request)
        {
            Connection connection = Connect(request);

            if (!request.IsEmpty)
            {
                using (Stream stream = connection.CaptureRequestStream())
                {
                    request.WriteContent(stream);
                }
            }

            Stream responseStream = null;

            var response = new TResponse();

            response.ApplyContext(request.Context);

            try
            {
                responseStream = connection.CaptureResponseStream();
                response.ReadContent(responseStream);
            }
            catch (WebException webException)
            {
                if (!ContinueOnServerError)
                {
                    throw;
                }

                responseStream = webException.Response.GetResponseStream();
                response.ReadContent(responseStream);
            }
            finally
            {
                responseStream?.Close();
            }

            return(response);
        }
Ejemplo n.º 60
0
        private static bool SaveBinaryFile(WebResponse response, string savePath)
        {
            var    value     = false;
            var    buffer    = new byte[1024];
            Stream outStream = null;
            Stream inStream  = null;

            try
            {
                if (!File.Exists(savePath))
                {
                    File.Delete(savePath);
                    outStream = System.IO.File.Create(savePath);
                    inStream  = response.GetResponseStream();
                    var l = 0;
                    do
                    {
                        if (inStream != null)
                        {
                            l = inStream.Read(buffer, 0, buffer.Length);
                        }
                        if (l > 0)
                        {
                            outStream.Write(buffer, 0, l);
                        }
                    } while (l > 0);
                    value = true;
                }
                else
                {
                    value = true;
                }
            }
            finally
            {
                outStream?.Close();
                inStream?.Close();
            }
            return(value);
        }