Beispiel #1
0
        public string ConvertERD(string showColumns, string showTypes, System.IO.Stream csv)
        {
            string erd = "";

            try
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                csv.CopyTo(ms);
                byte[] buff = ms.ToArray();

                ERD.ERDFilter conv = new ERD.ERDFilter();

                if (showColumns != null)
                {
                    conv.ShowColumns = (showColumns != "0");
                }
                if (showTypes != null)
                {
                    conv.ShowDataTypes = (showTypes != "0");
                }

                conv.LoadCSVFromString(UTF8Encoding.ASCII.GetString(buff));
                SDON.Model.Diagram diagram = conv.ConvertDatabase();
                erd = SDON.SDONBuilder.ToJSON(diagram);
            }
            catch (Exception e)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError;

                return("Error occurred when trying to parse CSV:\n" + e.Message);
            }

            return(erd);
        }
Beispiel #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PrintDataAsync();
            Debug.Print("three");



            WebRequest webRequest = WebRequest.Create("http://www.baidu.com");

            webRequest.BeginGetResponse(result =>
            {
                WebResponse webResponse = null;
                try
                {
                    webResponse = webRequest.EndGetResponse(result);
                    using (System.IO.FileStream fs = new System.IO.FileStream("$(ProjectDir)/baidu.html", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.Stream webStream = webResponse.GetResponseStream())
                        {
                            webStream?.CopyTo(fs);
                        }
                    }
                }
                catch (WebException ex)
                {
                    Response.Write("Failed:" + ex.GetBaseException().Message);
                }
                finally
                {
                    webResponse?.Close();
                }
            }, null);
        }
        private void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
        {
            string  targetPath = null;
            UIImage image      = args.EditedImage ?? args.OriginalImage;

            if (image != null)
            {
                // Convert UIImage to .NET Stream object
                NSData data = image.AsJPEG(1);
                using (System.IO.Stream stream = data.AsStream())
                {
                    string extension = ".jpg";

                    string fullFileName = FileNameWithoutExtension + extension;
                    targetPath = System.IO.Path.Combine(CopyToDirectory, fullFileName);

                    // copy the file to the destination and set the completion of the Task
                    using (var copiedFileStream = new System.IO.FileStream(targetPath, System.IO.FileMode.OpenOrCreate))
                    {
                        stream.CopyTo(copiedFileStream);
                    }
                    TaskCompletionSource.SetResult(fullFileName); // we'll reconstruct the path at runtime
                }
            }
            else
            {
                TaskCompletionSource.SetResult(null);
            }
            ImagePicker.DismissViewController(true, null);
        }
Beispiel #4
0
        public AddStreamRequest SetFile(System.IO.Stream inputStream)
        {
            Contract.Requires(inputStream != null);
            Contract.Requires(inputStream.CanRead);

            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }
            if (!inputStream.CanRead)
            {
                throw new ArgumentException("Argument inputStream must be readable");
            }

            _inputStream = new Tools.ChunkedMemoryStream();
            inputStream.CopyTo(_inputStream);

            _inputStream.Position = 0;
            var result = File.Bencoding.BencodeDecoder.Decode(_inputStream);

            _inputStream.Position = 0;

            if (result == null || result.Length == 0 || !(result[0] is File.Bencoding.BDictionary))
            {
                throw new InvalidOperationException("Invalid torrent stream");
            }

            var torrent = TorrentInfo.Parse((File.Bencoding.BDictionary)result[0]);

            _torrentInfo = torrent;
            return(this);
        }
        public virtual byte[] GetFont(string faceFileName)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                string ttfPathFile = "";
                try
                {
                    ttfPathFile = SSupportedFonts.ToList().First(x => x.ToLower().Contains(
                                                                     System.IO.Path.GetFileName(faceFileName).ToLower())
                                                                 );

                    using (System.IO.Stream ttf = System.IO.File.OpenRead(ttfPathFile))
                    {
                        ttf.CopyTo(ms);
                        ms.Position = 0;
                        return(ms.ToArray());
                    }
                }
                catch (System.Exception e)
                {
                    System.Console.WriteLine(e);
                    throw new System.Exception("No Font File Found - " + faceFileName + " - " + ttfPathFile);
                }
            }
        }
        public string SendData(string data)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            try
            {
                request = (HttpWebRequest)WebRequest.Create(Server);
                byte[] req = System.Text.UTF8Encoding.UTF8.GetBytes(data);
                //we setup the request header and then we send it
                request.Method        = "POST";
                request.Accept        = "application/json";
                request.ContentType   = "application/json; charset=utf-8";
                request.ContentLength = req.Length;
                request.GetRequestStream().Write(req, 0, req.Length);

                //now see what goodies grandma sent us
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    { //it means something bad happened, so we stop
                        return(null);
                    }

                    System.IO.Stream stream = response.GetResponseStream();

                    stream.CopyTo(ms);

                    return(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
            catch (WebException)
            {
                Console.Out.WriteLine("The bloody server gives me the silence treatment!");
                return(null);
            }
        }
Beispiel #7
0
        private T PerformRequestInternal <T>(Dictionary <string, string> queryparams)
        {
            queryparams["format"] = "json";

            string query = EncodeQueryString(queryparams);

            byte[] data = ENCODING.GetBytes(query);

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(m_controlUri);
            req.Method        = "POST";
            req.ContentLength = data.Length;
            req.ContentType   = "application/x-www-form-urlencoded ; charset=" + ENCODING.BodyName;
            req.Headers.Add("Accept-Charset", ENCODING.BodyName);
            if (m_xsrftoken != null)
            {
                req.Headers.Add(XSRF_HEADER, m_xsrftoken);
            }
            req.UserAgent = "Duplicati TrayIcon Monitor, v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            if (req.CookieContainer == null)
            {
                req.CookieContainer = new System.Net.CookieContainer();
            }

            if (m_authtoken != null)
            {
                req.CookieContainer.Add(new System.Net.Cookie(AUTH_COOKIE, m_authtoken, "/", req.RequestUri.Host));
            }
            if (m_xsrftoken != null)
            {
                req.CookieContainer.Add(new System.Net.Cookie(XSRF_COOKIE, m_xsrftoken, "/", req.RequestUri.Host));
            }

            //Wrap it all in async stuff
            Duplicati.Library.Utility.AsyncHttpRequest areq = new Library.Utility.AsyncHttpRequest(req);

            using (System.IO.Stream s = areq.GetRequestStream())
                s.Write(data, 0, data.Length);

            //Assign the timeout, and add a little processing time as well
            if (queryparams["action"] == "get-current-state" && queryparams.ContainsKey("duration"))
            {
                areq.Timeout = (int)(Duplicati.Library.Utility.Timeparser.ParseTimeSpan(queryparams["duration"]) + TimeSpan.FromSeconds(5)).TotalMilliseconds;
            }

            using (System.Net.HttpWebResponse r = (System.Net.HttpWebResponse)areq.GetResponse())
                using (System.IO.Stream s = areq.GetResponseStream())
                    if (typeof(T) == typeof(string))
                    {
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                        {
                            s.CopyTo(ms);
                            return((T)(object)ENCODING.GetString(ms.ToArray()));
                        }
                    }
                    else
                    {
                        using (var sr = new System.IO.StreamReader(s, ENCODING, true))
                            return(Serializer.Deserialize <T>(sr));
                    }
        }
Beispiel #8
0
        private Android.Net.Uri GetFileForBrowser(Android.Net.Uri dataFromActivityResult)
        {
            try
            {
                string TempfileName = Guid.NewGuid().ToString("N") + ".file";

                string outputFolder = FileCachingHelper.GetFileCacheFolder();
                if (!System.IO.Directory.Exists(outputFolder))
                {
                    System.IO.Directory.CreateDirectory(outputFolder);
                }

                var backingFile = System.IO.Path.Combine(outputFolder, TempfileName);
                using (var output = System.IO.File.Create(backingFile))
                {
                    using (System.IO.Stream inputStream = BlazorWebViewService.GetCurrentActivity().ContentResolver.OpenInputStream(dataFromActivityResult))
                    {
                        inputStream.CopyTo(output);
                    }
                }

                return(Android.Net.Uri.Parse("file://" + backingFile));
            }
            catch (System.Exception e)
            {
                ConsoleHelper.WriteException(e);
                throw;
            }
        }
 public FilterStatus Filter(System.IO.Stream dataIn, out long dataInRead, System.IO.Stream dataOut, out long dataOutWritten)
 {
     try
     {
         if (dataIn == null || dataIn.Length == 0)
         {
             dataInRead     = 0;
             dataOutWritten = 0;
             return(FilterStatus.Done);
         }
         dataInRead     = dataIn.Length;
         dataOutWritten = Math.Min(dataInRead, dataOut.Length);
         dataIn.CopyTo(dataOut);
         dataIn.Seek(0, SeekOrigin.Begin);
         byte[] bs = new byte[dataIn.Length];
         dataIn.Read(bs, 0, bs.Length);
         DataAll.AddRange(bs);
         dataInRead     = dataIn.Length;
         dataOutWritten = dataIn.Length;
         return(FilterStatus.NeedMoreData);
     }
     catch (Exception ex)
     {
         dataInRead     = dataIn.Length;
         dataOutWritten = dataIn.Length;
         return(FilterStatus.Done);
     }
 }
        /// <summary>
        /// Stream + FilePath -> SaveStream -> Bool
        /// </summary>
        /// <param name="thisStream"></param>
        /// <param name="thisFilePath"></param>
        /// <returns></returns>
        public static bool SaveStream(this System.IO.Stream thisStream, string thisFilePath)
        {
            #region Stream + FilePath -> SaveStream -> Bool
            if (thisStream != null)
            {
                try
                {
                    using (var isolatedStorageFile = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var fileStream = isolatedStorageFile.OpenFile(thisFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
                        {
                            thisStream.Position = 0;
                            thisStream.CopyTo(fileStream);
                            return(true);
                        }
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(false);

            #endregion
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="stream"></param>
        public void UploadFileRestFull(string fileUrl, System.IO.Stream stream)
        {
            var requestURI  = new Uri(_ctx.Url);
            var baseDestURL = requestURI.GetLeftPart(UriPartial.Authority);
            var path        = baseDestURL + fileUrl;

            byte[] buffer = new byte[stream.Length];

            try
            {
                using (var ms = new System.IO.MemoryStream())
                {
                    stream.CopyTo(ms);
                    buffer = ms.ToArray();
                }

                using (WebClient client = new WebClient())
                {
                    client.BaseAddress = baseDestURL;
                    client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                    client.Credentials = _ctx.Credentials;
                    var result = Encoding.UTF8.GetString(client.UploadData(path, "PUT", buffer));
                }
            }
            catch (OutOfMemoryException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void UploadFile(System.IO.Stream sourceStream, string destinationFilePath)
        {
            FtpClient conn = null;

            try
            {
                conn = OpenClient(destinationFilePath);

                destinationFilePath = AdjustPath(conn.Host, destinationFilePath);

                using (System.IO.Stream dStream = conn.OpenWrite(destinationFilePath, FtpDataType.Binary))
                {
                    sourceStream.CopyTo(dStream);
                }

                FtpReply reply = conn.GetReply();

                if (!reply.Success)
                {
                    throw new Exception("There was an error writing to the FTP server: " + reply.Message);
                }
            }
            catch (Exception ex)
            {
                DisposeClient(conn);
                conn = null;

                throw ex;
            }
            finally
            {
                RecycleClient(conn);
            }
        }
        public void DownloadFile(string sourceFilePath, System.IO.Stream destinationStream)
        {
            FtpClient conn = null;

            try
            {
                conn = OpenClient(sourceFilePath);

                sourceFilePath = AdjustPath(conn.Host, sourceFilePath);

                using (System.IO.Stream sStream = conn.OpenRead(sourceFilePath, FtpDataType.Binary))
                {
                    sStream.CopyTo(destinationStream);
                }

                FtpReply reply = conn.GetReply();

                if (!reply.Success)
                {
                    throw new Exception("There was an error reading from the FTP server: " + reply.Message);
                }
            }
            catch (Exception ex)
            {
                DisposeClient(conn);
                conn = null;

                throw ex;
            }
            finally
            {
                RecycleClient(conn);
            }
        }
Beispiel #14
0
 private static bool OptimizeImage(string originalFile, string newFile, OptimusAction action, out string error)
 {
     error = null;
     try
     {
         string url = string.Format("https://api.optimus.io/{0}?{1}", licenceKey, action);
         System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
         req.ContentType = "application/x-www-form-urlencoded";
         req.Method      = "POST";
         req.UserAgent   = "Optimus-API";
         req.Accept      = "image/*";
         byte[] bytes = System.IO.File.ReadAllBytes(originalFile);
         req.ContentLength = bytes.Length;
         using (System.IO.Stream stream = req.GetRequestStream())
         {
             stream.Write(bytes, 0, bytes.Length);
         }
         using (System.IO.Stream input = req.GetResponse().GetResponseStream())
             using (System.IO.Stream output = System.IO.File.OpenWrite(newFile))
             {
                 input.CopyTo(output);
             }
     }
     catch (System.Net.WebException ex)
     {
         error = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : "");
         return(false);
     }
     catch (Exception ex)
     {
         error = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : "");
         return(false);
     }
     return(true);
 }
Beispiel #15
0
        private void ExtractNSS(string TempExtractDir)
        {
            string[] NSSFileList = new string[13] {
                "freebl3.dll",
                "libnspr4.dll",
                "libplc4.dll",
                "libplds4.dll",
                "nss3.dll",
                "nssckbi.dll",
                "nssdbm3.dll",
                "nssutil3.dll",
                "smime3.dll",
                "softokn3.dll",
                "sqlite3.dll",
                "ssl3.dll",
                "certutil.exe"
            };

            if (System.IO.Directory.Exists(TempExtractDir))
            {
                System.IO.Directory.Delete(TempExtractDir, true);
            }
            System.IO.Directory.CreateDirectory(TempExtractDir);

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            foreach (string nssfile in NSSFileList)
            {
                System.IO.Stream input = null;
                try
                {
                    input = assembly.GetManifestResourceStream("SuperFishRemovalTool.NSS." + nssfile);
                    System.IO.FileStream output = null;
                    try
                    {
                        output = System.IO.File.Open(System.IO.Path.Combine(TempExtractDir, nssfile), System.IO.FileMode.CreateNew);
                        input.CopyTo(output);  // CopyStream(input, output);
                    }
                    catch { }
                    finally
                    {
                        if (null != output)
                        {
                            output.Dispose();
                            output.Close();
                        }
                    }
                    output = null;
                }
                catch { }
                finally
                {
                    if (null != input)
                    {
                        input.Dispose();
                        input.Close();
                    }
                }
                input = null;
            }
        }
Beispiel #16
0
        public void EncryptStreamAes(string path, System.IO.Stream str)
        {
            System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(path));

            // Create an AesManaged object
            // with the specified key and IV.
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = data;
                aesAlg.IV  = data;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (System.IO.FileStream msEncrypt = new System.IO.FileStream(path, System.IO.FileMode.Create))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        str.CopyTo(csEncrypt);
                    }
                }
            }
        }
        public static void SaveToFile(this System.IO.Stream stream, string outputFilePath)
        {
            var writer = new System.IO.FileStream(outputFilePath, System.IO.FileMode.CreateNew);

            stream.CopyTo(writer);
            writer.Close();
        }
Beispiel #18
0
        public void LoadAttachment()
        {
            if (contentType == Enumerations.CorrespondenceContentType.Attachment)
            {
                // PRIMARY ATTACHMENT

                System.IO.Stream attachmentStream = application.EnvironmentDatabase.BlobRead("dbo.CorrespondenceContent", "Attachment", "CorrespondenceContentId = " + id.ToString());

                if (attachmentStream != null)
                {
                    System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

                    attachmentStream.CopyTo(memoryStream);

                    Attachment = memoryStream;
                }

                // XPS ATTACHMENT

                System.IO.Stream attachmentXpsStream = application.EnvironmentDatabase.BlobRead("dbo.CorrespondenceContent", "AttachmentXps", "CorrespondenceContentId = " + id.ToString());

                if (attachmentXpsStream != null)
                {
                    System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

                    attachmentXpsStream.CopyTo(memoryStream);

                    AttachmentXps = memoryStream;
                }
            }

            return;
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public String GetCertifyFile()
        {
            String result = String.Empty;

            String id = "85c9f279-4245-4aaa-b394-af826b021d0c";

            // Request Data
            sms.didimo.es.GetCertifyFileRequest request = new sms.didimo.es.GetCertifyFileRequest {
                UserName = this.userName,
                Password = this.password,
                Id       = id
            };

            // Execute
            System.IO.Stream certifyStream = this.api.GetCertifyFile(request);

            String fileName      = String.Format("message_{0}.pdf", id);
            String fileDirectory = @"C:\SMSCertifies\sms.didimo\";

            using (System.IO.FileStream fs = new System.IO.FileStream(System.IO.Path.Combine(fileDirectory, fileName), System.IO.FileMode.OpenOrCreate))
            {
                certifyStream.CopyTo(fs);
            }

            result = String.Format("File saved on {0}", System.IO.Path.Combine(fileDirectory, fileName));

            return(result);
        }
        internal static string streamToBase64(System.IO.Stream stream)
        {
            var memoryStream = new System.IO.MemoryStream();

            stream.CopyTo(memoryStream);
            return(System.Convert.ToBase64String(memoryStream.ToArray()));
        }
Beispiel #21
0
        byte[] SerializeStream(System.IO.Stream stream)
        {
            var memoryStream = new System.IO.MemoryStream();

            stream.CopyTo(memoryStream);
            return(memoryStream.ToArray());
        }
        public void SaveFileLocallyViaREST(string directory, bool overwrite)
        {
            string path = System.IO.Path.Combine(directory, Name);

            if (System.IO.File.Exists(path))
            {
                if (!overwrite)
                {
                    throw new Exception("The file already exists locally.");
                }
                System.IO.File.Delete(path);
            }
            string folderUrl = ServerRelativeUrl.Substring(0, ServerRelativeUrl.Length - Name.Length - 1);
            string restCmd   = string.Format("/_api/web/GetFolderByServerRelativeUrl('{0}')/files('{1}')/$value", folderUrl, Name);

            Uri uri = new Uri(_file.Context.Url.TrimEnd('/') + restCmd);

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

            request.Credentials = SPOSiteContext.CurrentSiteContext.Context.Credentials;
            request.Method      = WebRequestMethods.Http.Get;
            request.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.ContentLength > 0)
            {
                response.ContentLength = response.ContentLength;
            }
            using (System.IO.Stream s = response.GetResponseStream())
                using (System.IO.FileStream fs = System.IO.File.Create(path))
                {
                    s.CopyTo(fs);
                }
        }
        private static System.IO.MemoryStream _ToMemoryStream(System.IO.Stream stream, int?bytesToReadHint = null)
        {
            if (bytesToReadHint.HasValue)
            {
                var buffer = new Byte[bytesToReadHint.Value];

                int p = 0;
                while (p < buffer.Length)
                {
                    var r = stream.Read(buffer, p, bytesToReadHint.Value - p);
                    p += r > 0 ? r : throw new System.IO.EndOfStreamException();
                }

                return(new System.IO.MemoryStream(buffer, false));
            }
            else
            {
                var mem = new System.IO.MemoryStream();

                stream.CopyTo(mem);
                stream.Flush();

                mem.Position = 0;
                return(mem);
            }
        }
        public string ConvertCtagsFileBlobAdd(Guid uploadID, System.IO.Stream fileSection)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            fileSection.CopyTo(ms);

            try
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(TempFileLocation + CurrPathSeparator + "tmp-" + uploadID.ToString());
                if (!dir.Exists)
                {
                    dir.Create();
                }

                using (System.IO.FileStream fs = new System.IO.FileStream(dir.FullName + CurrPathSeparator + "temp.raw", System.IO.FileMode.Append))
                {
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }
            }
            catch (Exception e)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode  = System.Net.HttpStatusCode.InternalServerError;
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
                return("Error while receiving data: " + e.Message);
            }

            return("");
        }
        /// <summary>
        /// Besipiel für den Download von Blobs über einen WCF- Dienst mittels Streaming. Das Streanming muß in der 
        /// Konfiguration des Clients unter Bindung im Element TransferMode auf Stream eingestellt werden.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDownloadStream_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbxDownloadFilename.Text))
            {
                try
                {
                    using (var proxy = new DataStreamsRef.DataStreamsClient())
                    {
                        log.Log(mko.Log.RC.CreateStatus("Downstream von " + tbxDownloadFilename.Text + " in " + Properties.Settings.Default.Downloadverzeichnis + " startet"));

                        System.IO.Stream downstream = proxy.DownstreamData(tbxDownloadFilename.Text);

                        string fname = Properties.Settings.Default.Downloadverzeichnis + "\\" + tbxDownloadFilename.Text;
                        var fstream = new System.IO.FileStream(fname, System.IO.FileMode.Create);

                        // Hier wird der Datenstrom kontinuierlich auf die Festplatte geleitet
                        downstream.CopyTo(fstream);

                        log.Log(mko.Log.RC.CreateStatus("Downstream von " + tbxDownloadFilename.Text + " in " + Properties.Settings.Default.Downloadverzeichnis + " erfolgreich beendet"));
                    }
                }
                catch (Exception ex)
                {
                    log.Log(mko.Log.RC.CreateError("Beim Hochladen von " + tbxUploadFilename.Text + ": " + ex.Message));
                }
            }
        }
        public string ConvertCtagsGithubRepositoryStartRequest(Guid uploadID, System.IO.Stream fileSection)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            fileSection.CopyTo(ms);

            try
            {
                byte[] buff = ms.GetBuffer();
                string str  = UnicodeEncoding.Unicode.GetString(buff, 0, (int)ms.Length);

                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(TempFileLocation + CurrPathSeparator + "tmp-github-request-" + uploadID.ToString());
                if (!dir.Exists)
                {
                    dir.Create();
                }

                using (System.IO.StreamWriter fs = new System.IO.StreamWriter(dir.FullName + CurrPathSeparator + "exclusion.txt", true))
                {
                    fs.Write(str);
                }
            }
            catch (Exception e)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode  = System.Net.HttpStatusCode.InternalServerError;
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
                return("Error while receiving data: " + e.Message);
            }

            return("");
        }
Beispiel #27
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            WebRequest         webRequest = WebRequest.Create("http://www.baidu.com");
            TaskFactory        factroy    = new TaskFactory();
            Task <WebResponse> task       = factroy.FromAsync <WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse, TaskCreationOptions.None);

            task.ContinueWith(t =>
            {
                WebResponse webResponse = null;
                try
                {
                    webResponse = t.Result;
                    using (System.IO.FileStream fs = new System.IO.FileStream("$(ProjectDir)", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.Stream webStream = webResponse.GetResponseStream())
                        {
                            webStream.CopyTo(fs);
                        }
                    }
                }
                catch (WebException ex)
                {
                    Response.Write("Failed:" + ex.GetBaseException().Message);
                }
                finally
                {
                    webResponse?.Close();
                }
            });
        }
Beispiel #28
0
 public static byte[] ConvertToBytes(this System.IO.Stream input)
 {
     input.Position = 0;
     using var ms   = new System.IO.MemoryStream();
     input.CopyTo(ms);
     return(ms.ToArray());
 }
Beispiel #29
0
        public void PackagerSupportsJpeg()
        {
            byte[] imageData;
            var    assembly     = System.Reflection.Assembly.GetExecutingAssembly();
            var    resourceName = "Urunium.Stitch.Tests.img.jpg";

            using (System.IO.Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    stream.CopyTo(ms);
                    imageData = ms.ToArray();
                }
            var base64 = System.Convert.ToBase64String(imageData);

            // Arrange
            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\App\img.jpg", new MockFileData(imageData) }
            });

            var packager = new Packager(
                fileSystem: fileSystem,
                transformers: new IModuleTransformer[]
            {
                new Base64ModuleTransformer(fileSystem)
            });
            Package package = packager.Package(new SourceConfig
            {
                RootPath    = @"c:\App",
                EntryPoints = new[] { "./img.jpg" },
            });

            Assert.AreEqual(1, package.Modules.Count);
            Assert.AreEqual("Object.defineProperty(exports, '__esModule', {value: true}); exports.default = \"data:image/jpeg;base64," + base64 + "\"", package.Modules[0].TransformedContent);
        }
Beispiel #30
0
 /// <summary>
 /// Copy stream as new stream.
 /// </summary>
 /// <param name="stream">Stream to copy</param>
 /// <returns>Copy of original stream</returns>
 public static System.IO.Stream CopyStream(this System.IO.Stream stream)
 {
     System.IO.Stream targetStream = new System.IO.MemoryStream();
     stream.Rewind();
     stream.CopyTo(targetStream);
     return(targetStream);
 }