public void Send(string remoteUrl, IDictionary<string, string> headers, Stream data)
        {
            var request = WebRequest.Create(remoteUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers = Encode(headers);
            request.UseDefaultCredentials = true;
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                data.CopyTo(stream);
            }

            HttpStatusCode statusCode;

            //todo make the receiver send the md5 back so that we can double check that the transmission went ok
            using (var response = (HttpWebResponse) request.GetResponse())
            {
                statusCode = response.StatusCode;
            }

            Logger.Debug("Got HTTP response with status code " + statusCode);

            if (statusCode != HttpStatusCode.OK)
            {
                Logger.Warn("Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
Exemple #2
0
 /// <summary>
 /// Write - this write routine for mdat is used only when writing out an MP4 file.
 /// (See MP4StreamWriter.)
 /// </summary>
 /// <param name="writer"></param>
 public void Write(BoxWriter writer, Stream reader)
 {
     if (base.Size == 0UL)
       {
     base.Write(writer);
     reader.CopyTo(writer.BaseStream);
       }
       else
     using (new SizeCalculator(this, writer))
     {
         base.Write(writer);
         reader.CopyTo(writer.BaseStream);
     }
 }
 public void CreateOrAppendToFile(string fileLocation, Stream stream)
 {
     var sourcePath = Path.Combine(DebugConfig.LocalStoragePath, fileLocation);
     var fileInfo = new FileInfo(sourcePath);
     if (fileInfo.Exists)
     {
         using (var streamWrite = fileInfo.Open(FileMode.Append, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
     else
     {
         using (var streamWrite = fileInfo.Open(FileMode.Create, FileAccess.Write))
             stream.CopyTo(streamWrite);
     }
 }
        public void Transform(Stream stream)
        {
            if (mHash == null)
                return;

            stream.CopyTo(mCryptoStream);
        }
 private static TemporaryFile Deploy(Stream stream)
 {
     var tempFile = new TemporaryFile("0install-unit-tests");
     using (var fileStream = File.Create(tempFile))
         stream.CopyTo(fileStream);
     return tempFile;
 }
 public static byte[] ReadFully(Stream input)
 {
     using (MemoryStream ms = new MemoryStream()) {
         input.CopyTo(ms);
         return ms.ToArray();
     }
 }
Exemple #7
0
    public static HttpWebRequest ConstructWebRequest(this Uri uri, string method, Stream contentStream, IDictionary<string, string> headers,
      int timeout = 0)
    {
      if (headers != null)
        headers.FilterHeaders();

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

      var t = timeout == 0 ? NFX.Web.WebSettings.WebDavDefaultTimeoutMs : timeout;
      if (t > 0) request.Timeout = t;

      request.Method = method;
      request.ContentType = "text/plain";

      if (method == "PUT")
        request.ContentLength = contentStream.Length;

      foreach (var kvp in headers)
        request.Headers.Add(kvp.Key, kvp.Value);

      if (method == "PUT")
      {
        using (Stream requestStream = request.GetRequestStream())
        {
          contentStream.Position = 0;
          contentStream.CopyTo(requestStream);

          requestStream.Flush();
          requestStream.Close();
        }
      }

      return request;
    }
Exemple #8
0
        private static Stream Clone(Stream source)
        {
            var cloned = new MemoryStream();
            #if NET35
            // Copy up to 2048 bytes at a time
            byte[] buffer = new byte[2048];

            // Maintains how many bytes were read
            int copiedBytes;

            // Read bytes and copy them into a buffer making sure not to trigger the dispose
            while ((copiedBytes = source.Read(buffer, 0, buffer.Length)) > 0)
            {
                // Write the copied bytes from the buffer into the cloned stream
                cloned.Write(buffer, 0, copiedBytes);
            }

            #else
            source.CopyTo(cloned);
            #endif
            // Move the stream pointers back to the original start locations
            if (source.CanSeek)
            {
                source.Seek(0, 0);
            }

            cloned.Seek(0, 0);

            return cloned;
        }
Exemple #9
0
        public static Stream Resize(int width, int height, Stream image, string fileName)
        {
            Stream fileStream = new MemoryStream();
            Image tempImage = Bitmap.FromStream(image);
            long maxFactor = width * height;
            long imageFactor = tempImage.Width * tempImage.Height;

            if (maxFactor < imageFactor)
            {
                using (ImageResizer resizer = new ImageResizer())
                {
                    resizer.MimeType = Path.GetExtension(fileName);
                    resizer.SourceImage = tempImage;
                    resizer.Background = ColorTranslator.FromHtml("#fff");
                    resizer.Mode = ImageResizer.ResizeMode.KeepOriginalAspect;
                    resizer.Width = width;
                    resizer.Height = height;

                    resizer.Process();

                    resizer.ResultImage.Save(fileStream, tempImage.RawFormat);
                }
            }
            else
            {
                image.Seek(0, SeekOrigin.Begin);
                image.CopyTo(fileStream);
            }

            return fileStream;
        }
Exemple #10
0
 public static void WriteFile(string FilePath, Stream FileContent)
 {
     using (FileStream outStream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
     {
         FileContent.CopyTo(outStream);
     }
 }
Exemple #11
0
		public string Store (string id, Stream stream)
		{
			EnsureOutput ();
			SetupEntry (zipOutput, ref id);
			stream.CopyTo (zipOutput);
			return id;
		}
Exemple #12
0
        //public JsonFormatter()
        //{
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        //}
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = new TaskCompletionSource<object>();

              using (var ms = new MemoryStream())
              {
            readStream.CopyTo(ms);
            //ms.Seek(0, SeekOrigin.Begin);

            //var result = JsonSchemaValidator.Instance().Validate(ms, type);

            //if (!string.IsNullOrWhiteSpace(result))
            //  task.SetResult(result);
            //else
            {
              ms.Seek(0, SeekOrigin.Begin);
              using (var reader = new JsonTextReader(new StreamReader(ms)))
              {
            var serializer = new JsonSerializer();
            task.SetResult(serializer.Deserialize(reader, type));
              }
            }
              }
              return task.Task;
        }
Exemple #13
0
        public static MemoryStream Decrypt(Stream ciphertext)
        {
            var process = new Process
            {
                EnableRaisingEvents = false,
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"C:\Program Files (x86)\GNU\GnuPG\pub\gpg2.exe",
                    Arguments = @"--decrypt",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true
                }
            };
            process.Start();

            var stdin = process.StandardInput;
            ciphertext.CopyTo(stdin.BaseStream);
            stdin.Close();

            var stdout = new MemoryStream();
            process.WaitForExit();
            process.StandardOutput.BaseStream.CopyTo(stdout);

            return stdout;
        }
    // ------------------------------------------
    //  Audio Management
    // ------------------------------------------

    public override void BeforeSpeechRecognition(string device, string text, double confidence, XPathNavigator xnav, string grammar, Stream stream, IDictionary<string, string> options) {
      base.BeforeSpeechRecognition(device, text, confidence, xnav, grammar, stream, options);

      byte[] audioBytes = null;
      stream.Position = 0;
      using (MemoryStream audioStream = new MemoryStream()) {
        stream.CopyTo(audioStream);
        audioStream.Position = 0;
        audioBytes = audioStream.ToArray();
      }

      float[] audioBuffer = new float[audioBytes.Length / 2];
      for (int i = 0, j = 0; i < audioBytes.Length / 2; i += 2, j++) {

        // convert two bytes to one short
        short s = BitConverter.ToInt16(audioBytes, i);

        // convert to range from -1 to (just below) 1
        audioBuffer[j] = s / 32768.0f;
      }

      // Reset
      tracker.Reset();
      pitch.Clear();

      // Process
      tracker.ProcessBuffer(audioBuffer);

      // Notify
      AddOnManager.GetInstance().HandleProfile(device, "pitch", pitch.Mean());
    }
        public void PushPackage(string packageFileName, Stream packageStream)
        {
            packageFileName = PackageNameUtility.NormalizeFileName(packageFileName);

            var packageFile = _directory.GetFile(packageFileName);
            using (var destinationStream = packageFile.OpenWrite())
                packageStream.CopyTo(destinationStream);

            #pragma warning disable 612,618
            var zipPackage = new ZipFilePackage(packageFile);
            IndexDocument.Document.Root.Add(
                    new XElement("wrap",
                                 new XAttribute("name", zipPackage.Name),
                                 new XAttribute("version", zipPackage.Version),
                                 new XAttribute("semantic-version", zipPackage.SemanticVersion),
                                 new XElement("link",
                                              new XAttribute("rel", "package"),
                                              new XAttribute("href", packageFile.Name)),
                                 zipPackage.Dependencies.Select(x => new XElement("depends", x.ToString()))
                            ));
            #pragma warning restore 612,618

            SaveIndex(IndexDocument);

            return;
        }
        private static IList<Bitmap> ProcessInputFrames(Stream input, string text, out int delay)
        {
            // default
            delay = 50;

            using (var copiedInput = new MemoryStream())
            {
                input.CopyTo(copiedInput);

                using (var gifImage = Image.FromStream(copiedInput))
                {
                    var frameCount = gifImage.GetFrameCount(FrameDimension.Time);

                    var frames = new List<Bitmap>();

                    for (var index = 0; index < frameCount; index++)
                    {
                        Console.WriteLine("Processing frame #{0}/{1}", index + 1, frameCount);
                        gifImage.SelectActiveFrame(FrameDimension.Time, index);
                        var bitmap = gifImage.Clone() as Bitmap;

                        if (index == 0)
                        {
                            delay = BitConverter.ToInt32(gifImage.GetPropertyItem(20736).Value, index) * 10;
                        }

                        frames.Add(RenderOverlay(bitmap, text));
                    }

                    return frames;
                }
            }
        }
 private static string HashWithLibGit2Sharp(Stream file)
 {
     var repository = new Repository(Environment.CurrentDirectory);
     var temp = new FileStream(Path.GetTempFileName(),FileMode.Open);
     file.CopyTo(temp);
     return repository.ObjectDatabase.CreateBlob(temp.Name).Sha.ToString();
 }
 public static string UploadFileToS3(IServices services, string fileName, Stream file, string folderName)
 {
     string s3FilePath = string.Empty;
     if (file != null)
     {
         byte[] bFile = null;
         MemoryStream memoryStream = new MemoryStream();
         try
         {
             file.CopyTo(memoryStream);
             bFile = memoryStream.ToArray();
             s3FilePath = services.Image.SaveImage(fileName, bFile, folderName);
         }
         catch (Exception ex)
         {
             Log.Error("FileHelper_UploadFileToS3_error: " + fileName, ex);
         }
         finally
         {
             memoryStream.Close();
             memoryStream.Dispose();
         }
     }
     file.Close();
     file.Dispose();
     return s3FilePath;
 }
 public VTFGenerator(Stream inputStream, Stream outputStream)
 {
     processDelegate = new ProcessAsync(this.Process);
     _output = new VTFOutput(outputStream);
     _smallInputFile = new MemoryStream();
     inputStream.CopyTo(_smallInputFile);
 }
        /// <summary>
        /// Requests the HTTP headers from a stream.
        /// </summary>
        /// <param name="stream">A stream.</param>
        public void RequestHeaders(Stream stream)
        {
            var tempStream = new MemoryStream();
            stream.CopyTo(tempStream);
            tempStream.Seek(0, SeekOrigin.Begin);

            using (var streamReader = new StreamReader(tempStream))
            {
                var headers = new Dictionary<string, string>();

                while (true)
                {
                    var line = streamReader.ReadLine();
                    if (String.IsNullOrWhiteSpace(line))
                    {
                        break;
                    }

                    if (line.StartsWith("HTTP/1."))
                    {
                        continue;
                    }

                    var header = line.Substring(0, line.IndexOf(':')).Trim();
                    var value = line.Substring(line.IndexOf(':') + 1).Trim();
                    headers.Add(header, value);
                }

                stream.Seek(0, SeekOrigin.Begin);
                this.OnHeadersAvailable(headers);
            }
        }
        public async Task<bool> Save(Stream stream, string path)
        {
            var api = await GetApi();

            var tempFilename = Path.GetTempFileName();

            using (var fileStream = File.Create(tempFilename))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
            }

            //var memoryStream = new MemoryStream();
            //var bytes = stream.ToArray();
            //File.WriteAllBytes(tempFilename, bytes);

            var directory = Path.GetDirectoryName(path);
            var filename = Path.GetFileName(path);

            var uploadedItem = await api.UploadFileAs(tempFilename, filename, directory);

            File.Delete(tempFilename);

            return uploadedItem != null;
        }
Exemple #22
0
 public static void WriteStreamToFile(string filePath, Stream networkStream)
 {
     using (var fileStream = new FileStream(filePath, FileMode.Create))
     {
         networkStream.CopyTo(fileStream);
     }
 }
        public DownloadResult( ILog logger, Stream zipContent )
        {
            File = new TemporaryFile( ".zip" );
            using( zipContent )
            using( var sw = System.IO.File.Open( File.Path, FileMode.Open ) )
                zipContent.CopyTo( sw );

            try
            {
                // open the zip file
                using( ZipFile zip = ZipFile.Read( File.Path ) )
                {
                    var manifestEntry = zip.Where( z => z.FileName == "manifest.xml" ).FirstOrDefault();
                    if( manifestEntry != null )
                    {
                        var ms = new MemoryStream();
                        manifestEntry.Extract( ms );
                        try
                        {
                            Manifest = HelpManifestData.Deserialize( ms );
                        }
                        catch( Exception ex )
                        {
                            logger.Error( "Unable to parse manifest", ex );
                            throw;
                        }
                    }
                }
            }
            catch( Exception ex )
            {
                logger.Error( "Unable to read downloaded help content as a zip file", ex );
                throw;
            }
        }
Exemple #24
0
        public void onPost(string light, string hum, string temp, Stream fileCont)
        {
            // save POST content as BMP file ...
            string docname = (DateTime.Now.ToLongTimeString() + "." + light + "_" + hum + "_" + temp + ".bmp").Replace(":", "_");
            string strdocPath;

            strdocPath = System.Web.Hosting.HostingEnvironment.MapPath("~/pics/") + docname;

            // Save Stream to local memory stream for later distrbution ...
            var ms = new MemoryStream();
            fileCont.CopyTo(ms);
            ms.Position = 0;

            FileStream fs = new FileStream(strdocPath, FileMode.Create, FileAccess.ReadWrite);
            ms.CopyTo(fs);
            ms.Position = 0;
            fs.Close(); ;

            Byte[] bytes = new Byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);

            var objContext = new TDataEntities();
            var newData = new TDataItem();
            newData.lightSENS   = int.Parse(light);
            newData.humSENS = int.Parse(hum);
            newData.tempSENS = decimal.Parse(temp);
            newData.Date = DateTime.Now;

            newData.Transacto = bytes;

            objContext.TDataItems.AddObject(newData);
            objContext.SaveChanges();
        }
Exemple #25
0
        public static RSResponse StoreFile(RSRequest rsRequest, Stream entity)
        {
            string extensionToAdd = "";

            //If file extension was not specified, make a good guess
            if (Path.GetExtension(rsRequest.LocalPath) == String.Empty)
            {
                extensionToAdd = rsRequest.ContentType.GetFileExtensionCandidates()[0];
            }

            //Add extension to the target file name (or don't)
            string newFileName = rsRequest.LocalPath + extensionToAdd;

            try
            {
                using (FileStream fs = File.OpenWrite(newFileName))
                {
                    entity.CopyTo(fs);
                }
            }
            catch (Exception ex)
            {
                return new StatusCodeResponse(HttpStatusCode.InternalServerError, ex.Message);
            }

            return new StatusCodeResponse(HttpStatusCode.Created);
        }
Exemple #26
0
        public void Encrypt(Stream streamIn, Stream streamOut, Stream streamKey)
        {
            using (Rijndael rij = Rijndael.Create())
            {

                key = rij.Key;
                iv = rij.IV;

                using (ICryptoTransform encryptor = rij.CreateEncryptor(key, iv))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamOut, encryptor, CryptoStreamMode.Write))
                    {
                        streamIn.CopyTo(cryptoStream);

                        StringBuilder builder = new StringBuilder();
                        builder.AppendLine(Convert.ToBase64String(iv));
                        builder.AppendLine(Convert.ToBase64String(key));

                        byte[] keyfile = System.Text.Encoding.Default.GetBytes(builder.ToString());

                        streamKey.Write(keyfile, 0, keyfile.Length);
                    }
                }
            }
        }
        public Task<SmtpCommandReply> HandleData(Stream stream)
        {
            stream.CopyTo(Body);
            Body.Seek(0, SeekOrigin.Begin);

            return SmtpCommandReply.CreateDefault250SuccessTask();
        }
        private static Stream GenerateThumbinail(Stream origImageStream, Size maxSize, out Size resultSize)
        {
            var resizedImageStream = new MemoryStream();
            using (Image rawImage = Image.FromStream(origImageStream))
            {
                int targetWidth = rawImage.Width;
                int targetHeight = rawImage.Height;

                if (rawImage.Width > maxSize.Width || rawImage.Height > maxSize.Height)
                {
                    CalcTargetSize(rawImage.Width, rawImage.Height, maxSize,
                        out targetWidth, out targetHeight);

                    resultSize = new Size(targetWidth, targetHeight);

                    return GenerateThumbinailExact(origImageStream, resultSize);
                }
                else // image already with allowed size
                {
                    origImageStream.Seek(0, SeekOrigin.Begin);
                    origImageStream.CopyTo(resizedImageStream);

                    resizedImageStream.Seek(0, SeekOrigin.Begin);

                    resultSize = new Size(rawImage.Width, rawImage.Height);

                    return resizedImageStream;
                }
            }
        }
		public Etag AddAttachment(string key, Etag etag, Stream data, RavenJObject headers)
		{
			Api.JetSetCurrentIndex(session, Files, "by_name");
			Api.MakeKey(session, Files, key, Encoding.Unicode, MakeKeyGrbit.NewKey);
			var isUpdate = Api.TrySeek(session, Files, SeekGrbit.SeekEQ);
			if (isUpdate)
			{
				var existingEtag = Etag.Parse(Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]));
				if (existingEtag != etag && etag != null)
				{
					throw new ConcurrencyException("PUT attempted on attachment '" + key +
						"' using a non current etag")
					{
						ActualETag = existingEtag,
						ExpectedETag = etag
					};
				}
			}
			else
			{
				if (data == null)
					throw new InvalidOperationException("When adding new attachment, the attachment data must be specified");

				if (Api.TryMoveFirst(session, Details))
					Api.EscrowUpdate(session, Details, tableColumnsCache.DetailsColumns["attachment_count"], 1);
			}

			Etag newETag = uuidGenerator.CreateSequentialUuid(UuidType.Attachments);
			using (var update = new Update(session, Files, isUpdate ? JET_prep.Replace : JET_prep.Insert))
			{
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["name"], key, Encoding.Unicode);
				if (data != null)
				{
					long written;
					using (var columnStream = new ColumnStream(session, Files, tableColumnsCache.FilesColumns["data"]))
					{
						if (isUpdate)
							columnStream.SetLength(0);
						using (var stream = new BufferedStream(columnStream))
						{
							data.CopyTo(stream);
							written = stream.Position;
							stream.Flush();
						}
					}
					if (written == 0) // empty attachment
					{
						Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["data"], new byte[0]);
					}
				}

				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["etag"], newETag.TransformToValueForEsentSorting());
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["metadata"], headers.ToString(Formatting.None), Encoding.Unicode);

				update.Save();
			}
			logger.Debug("Adding attachment {0}", key);

			return newETag;
		}
Exemple #30
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                MemoryStream stream = new MemoryStream();
                readStream.CopyTo(stream);

                IEnumerable<string> xContentHeader;
                var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);

                if (!success)
                {
                    throw Error.BadRequest("POST to binary must provide a Content-Type header");
                }

                string contentType = xContentHeader.FirstOrDefault();

                Binary binary = new Binary();
                binary.Content = stream.ToArray();
                binary.ContentType = contentType;

                //ResourceEntry entry = ResourceEntry.Create(binary);
                //entry.Tags = content.Headers.GetFhirTags();
                return (object)binary;
            });
        }
Exemple #31
0
 static public int CopyTo__Stream(IntPtr l)
 {
     try {
         System.IO.Stream self = (System.IO.Stream)checkSelf(l);
         System.IO.Stream a1;
         checkType(l, 2, out a1);
         self.CopyTo(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #32
0
 static void Ex1()
 {
     Task.Run(async() =>
     {
         string uri = "https://github.com/K38104011/DataStructureLearning";
         System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
         using (System.Net.WebResponse res = await req.GetResponseAsync())
             using (System.IO.Stream stream = res.GetResponseStream())
                 using (System.IO.FileStream fs = System.IO.File.Create("code.html"))
                 {
                     stream?.CopyTo(fs);
                     Console.WriteLine(res.ContentLength);
                 }
         System.Diagnostics.Process.Start("code.html");
     });
 }
 static void CopyStream(System.IO.Stream input, System.IO.Stream output)
 {
     input.CopyTo(output);
     output.Flush();
 }
Exemple #34
0
        protected override void _Rollback()
        {
            if (ExecutionMode == ExecuteOn.ForwardExecution)
            {
                foreach (string d in _FilesActioned.Keys)
                {
                    try
                    {
                        string s = _FilesActioned[d];

                        if (Action == ActionType.Move)
                        {
                            if (Direction == AzureDirection.ToAzureContainer)
                            {
                                CloudBlockBlob blob = Authentication.GetCloudBlockBlob(s, false);

                                if (blob == null)
                                {
                                    throw new Exception("File does not exist or can not be reached: " + s);
                                }

                                System.Threading.Tasks.Task <System.IO.Stream> streamResult = blob.OpenReadAsync();
                                streamResult.Wait();

                                string tmp = "";

                                try
                                {
                                    tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(d), "TEMP");

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

                                    tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(d));

                                    using (System.IO.Stream sStream = streamResult.Result)
                                    {
                                        using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                        {
                                            sStream.CopyTo(dStream);
                                        }
                                    }

                                    File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(d));
                                }
                                finally
                                {
                                    try
                                    {
                                        if (File.Exists(tmp))
                                        {
                                            File.Delete(tmp);
                                        }
                                    }
                                    catch { }
                                }

                                File.SetLastWriteTimeUtc(STEM.Sys.IO.Path.AdjustPath(d), blob.Properties.LastModified.Value.UtcDateTime);
                            }
                            else
                            {
                                CloudBlockBlob blob = Authentication.GetCloudBlockBlob(d, true);
                                blob.StreamWriteSizeInBytes = 16777216;

                                System.Threading.Tasks.Task <CloudBlobStream> streamResult = blob.OpenWriteAsync();
                                streamResult.Wait();

                                using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                {
                                    using (System.IO.Stream dStream = streamResult.Result)
                                    {
                                        sStream.CopyTo(dStream);
                                    }
                                }
                            }
                        }

                        if (Direction == AzureDirection.ToAzureContainer)
                        {
                            Authentication.DeleteFile(s);
                        }
                        else
                        {
                            STEM.Sys.IO.File.STEM_Delete(s, false, Retry, RetryDelaySeconds);
                        }
                    }
                    catch { }
                }
            }
            else
            {
                Execute();
            }
        }
Exemple #35
0
        bool Execute()
        {
            try
            {
                if (Direction == AzureDirection.ToAzureContainer)
                {
                    ExpandDestination = false;
                }
                else
                {
                    ExpandSource = false;
                }

                List <string> sources = new List <string>();
                if (ExpandSource)
                {
                    sources = STEM.Sys.IO.Path.ExpandRangedPath(SourcePath);
                }
                else
                {
                    sources.Add(SourcePath);
                }

                List <string> destinations = new List <string>();
                if (ExpandDestination)
                {
                    destinations = STEM.Sys.IO.Path.ExpandRangedPath(DestinationPath);
                }
                else
                {
                    destinations.Add(DestinationPath);
                }

                List <string> sourceFiles = new List <string>();

                int filesActioned = 0;

                foreach (string src in sources)
                {
                    List <IListBlobItem> items = new List <IListBlobItem>();

                    if (Direction == AzureDirection.ToAzureContainer)
                    {
                        sourceFiles = STEM.Sys.IO.Directory.STEM_GetFiles(src, FileFilter, DirectoryFilter, (RecurseSource ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly), false);
                    }
                    else
                    {
                        string container = Authentication.ContainerFromPath(src);
                        string prefix    = Authentication.PrefixFromPath(src);

                        items = Authentication.ListObjects(container, prefix, Sys.IO.Listing.ListingType.File, RecurseSource, DirectoryFilter, FileFilter);

                        sourceFiles = items.Select(i => Authentication.ToString(i)).ToList();
                    }

                    foreach (string s in sourceFiles)
                    {
                        try
                        {
                            bool success = false;

                            Exception lastEX = null;

                            foreach (string d in destinations)
                            {
                                try
                                {
                                    string dFile = "";

                                    try
                                    {
                                        if (PopulatePostMortemMeta)
                                        {
                                            PostMortemMetaData["SourceIP"]      = STEM.Sys.IO.Path.IPFromPath(s);
                                            PostMortemMetaData["DestinationIP"] = STEM.Sys.IO.Path.IPFromPath(d);

                                            if (Direction == AzureDirection.ToAzureContainer)
                                            {
                                                PostMortemMetaData["FileSize"] = new FileInfo(s).Length.ToString();
                                            }
                                            else
                                            {
                                                PostMortemMetaData["FileSize"] = Authentication.GetFileInfo(s).Size.ToString();
                                            }
                                        }
                                    }
                                    catch { }

                                    string dPath = STEM.Sys.IO.Path.AdjustPath(d);
                                    if (RecurseSource && RecreateTree)
                                    {
                                        dPath = System.IO.Path.Combine(dPath, STEM.Sys.IO.Path.GetDirectoryName(s).Replace(STEM.Sys.IO.Path.AdjustPath(src), "").Trim(System.IO.Path.DirectorySeparatorChar));
                                    }

                                    dPath = System.IO.Path.Combine(dPath, DestinationFilename);

                                    if (dPath.Contains("*.*"))
                                    {
                                        dPath = dPath.Replace("*.*", STEM.Sys.IO.Path.GetFileName(s));
                                    }

                                    if (dPath.Contains("*"))
                                    {
                                        dPath = dPath.Replace("*", STEM.Sys.IO.Path.GetFileNameWithoutExtension(s));
                                    }

                                    if (Direction == AzureDirection.ToAzureContainer)
                                    {
                                        if (!Authentication.DirectoryExists(STEM.Sys.IO.Path.GetDirectoryName(dPath)))
                                        {
                                            Authentication.CreateDirectory(STEM.Sys.IO.Path.GetDirectoryName(dPath));
                                        }

                                        if (Authentication.FileExists(dPath))
                                        {
                                            switch (ExistsAction)
                                            {
                                            case Sys.IO.FileExistsAction.Overwrite:
                                                Authentication.DeleteFile(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.OverwriteIfNewer:

                                                if (Authentication.GetFileInfo(dPath).LastWriteTimeUtc >= File.GetLastWriteTimeUtc(STEM.Sys.IO.Path.AdjustPath(s)))
                                                {
                                                    continue;
                                                }

                                                Authentication.DeleteFile(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.Skip:
                                                continue;

                                            case Sys.IO.FileExistsAction.Throw:
                                                throw new IOException("Destination file exists. (" + dPath + ")");

                                            case Sys.IO.FileExistsAction.MakeUnique:
                                                dFile = Authentication.UniqueFilename(dPath);
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            dFile = dPath;
                                        }

                                        CloudBlockBlob blob = Authentication.GetCloudBlockBlob(dPath, true);
                                        blob.StreamWriteSizeInBytes = 16777216;

                                        System.Threading.Tasks.Task <CloudBlobStream> streamResult = blob.OpenWriteAsync();
                                        streamResult.Wait();

                                        using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                        {
                                            using (System.IO.Stream dStream = streamResult.Result)
                                            {
                                                sStream.CopyTo(dStream);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (File.Exists(dPath))
                                        {
                                            switch (ExistsAction)
                                            {
                                            case Sys.IO.FileExistsAction.Overwrite:
                                                File.Delete(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.OverwriteIfNewer:

                                                if (File.GetLastWriteTimeUtc(STEM.Sys.IO.Path.AdjustPath(dPath)) >= Authentication.GetFileInfo(s).LastWriteTimeUtc)
                                                {
                                                    continue;
                                                }

                                                File.Delete(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.Skip:
                                                continue;

                                            case Sys.IO.FileExistsAction.Throw:
                                                throw new IOException("Destination file exists. (" + dPath + ")");

                                            case Sys.IO.FileExistsAction.MakeUnique:
                                                dFile = STEM.Sys.IO.File.UniqueFilename(dPath);
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            dFile = dPath;
                                        }

                                        if (!Directory.Exists(STEM.Sys.IO.Path.GetDirectoryName(dFile)))
                                        {
                                            Directory.CreateDirectory(STEM.Sys.IO.Path.GetDirectoryName(dFile));
                                        }

                                        CloudBlockBlob blob = Authentication.GetCloudBlockBlob(s, false);

                                        if (blob == null)
                                        {
                                            throw new Exception("File does not exist or can not be reached: " + s);
                                        }

                                        System.Threading.Tasks.Task <System.IO.Stream> streamResult = blob.OpenReadAsync();
                                        streamResult.Wait();

                                        string tmp = "";
                                        try
                                        {
                                            tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(dFile), "TEMP");

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

                                            tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(dFile));

                                            using (System.IO.Stream sStream = streamResult.Result)
                                            {
                                                using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                                {
                                                    sStream.CopyTo(dStream);
                                                }
                                            }

                                            try
                                            {
                                                File.SetLastWriteTimeUtc(tmp, blob.Properties.LastModified.Value.UtcDateTime);
                                            }
                                            catch { }

                                            File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(dFile));
                                        }
                                        finally
                                        {
                                            try
                                            {
                                                if (File.Exists(tmp))
                                                {
                                                    File.Delete(tmp);
                                                }
                                            }
                                            catch { }
                                        }
                                    }

                                    if (!String.IsNullOrEmpty(dFile))
                                    {
                                        filesActioned++;

                                        _FilesActioned[s] = dFile;

                                        if (Action == ActionType.Move)
                                        {
                                            AppendToMessage(s + " moved to " + dFile);
                                        }
                                        else
                                        {
                                            AppendToMessage(s + " copied to " + dFile);
                                        }
                                    }

                                    success = true;

                                    if (DestinationActionRule == DestinationRule.FirstSuccess)
                                    {
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lastEX = ex;

                                    if (DestinationActionRule == DestinationRule.AllOrNone)
                                    {
                                        throw ex;
                                    }
                                }
                            }

                            if (!success)
                            {
                                throw new Exception("No successful actions taken for " + s, lastEX); // + "\r\n" + ((lastEX == null) ? "No additional information." : lastEX.ToString()));
                            }
                            if (Action == ActionType.Move)
                            {
                                if (Direction == AzureDirection.ToAzureContainer)
                                {
                                    File.Delete(s);
                                }
                                else
                                {
                                    Authentication.DeleteFile(s);
                                }
                            }
                        }
                        catch (AggregateException ex)
                        {
                            foreach (Exception e in ex.InnerExceptions)
                            {
                                AppendToMessage(e.Message);
                                Exceptions.Add(e);
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendToMessage(ex.Message);
                            Exceptions.Add(ex);
                        }
                    }
                }

                if (PopulatePostMortemMeta)
                {
                    PostMortemMetaData["FilesActioned"] = filesActioned.ToString();
                }
            }
            catch (AggregateException ex)
            {
                foreach (Exception e in ex.InnerExceptions)
                {
                    AppendToMessage(e.Message);
                    Exceptions.Add(e);
                }
            }
            catch (Exception ex)
            {
                AppendToMessage(ex.Message);
                Exceptions.Add(ex);
            }

            if (_FilesActioned.Count == 0)
            {
                switch (ZeroFilesAction)
                {
                case FailureAction.SkipRemaining:
                    SkipRemaining();
                    return(true);

                case FailureAction.SkipNext:
                    SkipNext();
                    return(true);

                case FailureAction.SkipToLabel:
                    SkipForwardToFlowControlLabel(FailureActionLabel);
                    return(true);

                case FailureAction.Rollback:
                    RollbackAllPreceedingAndSkipRemaining();
                    break;

                case FailureAction.Continue:
                    return(true);
                }

                Message = "0 Files Actioned\r\n" + Message;
            }

            return(Exceptions.Count == 0);
        }
Exemple #36
0
        /// <summary>
        /// Take a photo async with specified options
        /// </summary>
        /// <param name="options">Camera Media Options</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>Media file of photo or null if canceled</returns>
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options, CancellationToken token = default(CancellationToken))
        {
            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            if (!(await RequestCameraPermissions()))
            {
                throw new MediaPermissionException(Permission.Camera);
            }


            VerifyOptions(options);

            var media = await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options, token);

            if (string.IsNullOrWhiteSpace(media?.Path))
            {
                return(media);
            }

            if (options.SaveToAlbum)
            {
                try
                {
                    var fileName  = System.IO.Path.GetFileName(media.Path);
                    var publicUri = MediaPickerActivity.GetOutputMediaFile(context, options.Directory ?? "temp", fileName, true, true);
                    using (System.IO.Stream input = File.OpenRead(media.Path))
                        using (System.IO.Stream output = File.Create(publicUri.Path))
                            input.CopyTo(output);

                    media.AlbumPath = publicUri.Path;

                    var f = new Java.IO.File(publicUri.Path);

                    //MediaStore.Images.Media.InsertImage(context.ContentResolver,
                    //    f.AbsolutePath, f.Name, null);

                    try
                    {
                        MediaScannerConnection.ScanFile(context, new[] { f.AbsolutePath }, null, context as MediaPickerActivity);

                        var values = new ContentValues();
                        values.Put(MediaStore.Images.Media.InterfaceConsts.Title, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath));
                        values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty);
                        values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
                        values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode());
                        values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant());
                        values.Put("_data", f.AbsolutePath);

                        var cr = context.ContentResolver;
                        cr.Insert(MediaStore.Images.Media.ExternalContentUri, values);
                    }
                    catch (Exception ex1)
                    {
                        Console.WriteLine("Unable to save to scan file: " + ex1);
                    }

                    var contentUri      = Android.Net.Uri.FromFile(f);
                    var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri);
                    context.SendBroadcast(mediaScanIntent);
                }
                catch (Exception ex2)
                {
                    Console.WriteLine("Unable to save to gallery: " + ex2);
                }
            }

            //check to see if we need to rotate if success


            try
            {
                var exif = new ExifInterface(media.Path);
                if (options.RotateImage)
                {
                    await FixOrientationAndResizeAsync(media.Path, options, exif);
                }
                else
                {
                    await ResizeAsync(media.Path, options, exif);
                }

                if (options.SaveMetaData && IsValidExif(exif))
                {
                    SetMissingMetadata(exif, options.Location);

                    try
                    {
                        exif?.SaveAttributes();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Unable to save exif {ex}");
                    }
                }

                exif?.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to check orientation: " + ex);
            }

            return(media);
        }
        private void ProcessRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;

            // Are they trying to upload a file?
            if (request.HttpMethod == "PUT")
            {
                System.IO.Stream input = request.InputStream;

                string test  = GolemBuildService.Instance.BuildPath;
                string test2 = Path.GetFileNameWithoutExtension(request.RawUrl) + ".zip";

                string     zipName    = Path.Combine(test, test2);
                FileStream fileStream = File.Create(zipName);
                input.CopyTo(fileStream);
                fileStream.Close();
                input.Close();

                // Send back OK
                HttpListenerResponse response = context.Response;
                response.Headers.Clear();
                response.SendChunked = false;
                response.StatusCode  = 201;
                response.AddHeader("Content-Location", zipName);
                //response.AddHeader("Server", String.Empty);
                //response.AddHeader("Date", String.Empty);
                response.Close();

                ZipFile.ExtractToDirectory(zipName, Path.GetDirectoryName(zipName));
            }
            else // They are trying to download a file
            {
                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                //let's check ranges
                long offset = 0;
                long size   = -1;
                foreach (string header in request.Headers.AllKeys)
                {
                    if (header == "Range")
                    {
                        string[] values = request.Headers.GetValues(header);
                        string[] tokens = values[0].Split('=', '-');
                        offset = int.Parse(tokens[1]);
                        size   = (int)(int.Parse(tokens[2]) - offset + 1);
                    }
                }

                try
                {
                    // Are they requesting a CompilerPackage?
                    if (request.RawUrl.StartsWith("/requestID/compiler/"))
                    {
                        string compilerHash = request.RawUrl.Replace("/requestID/compiler/", "");
                        byte[] data;
                        if (GolemCache.GetCompilerPackageData(compilerHash, out data))
                        {
                            response.AddHeader("ETag", "SHA1:" + compilerHash);

                            if (size == -1)
                            {
                                size = data.Length;
                            }

                            response.ContentLength64 = size;

                            Stream output = response.OutputStream;
                            output.Write(data, (int)offset, (int)size);
                            output.Close();
                        }
                    }
                    // Or are they requesting a tasks package?
                    else if (request.RawUrl.StartsWith("/requestID/tasks/"))
                    {
                        string tasksPackageHash = request.RawUrl.Replace("/requestID/tasks/", "");
                        byte[] data;
                        if (GolemCache.GetTasksPackage(tasksPackageHash, out data))
                        {
                            response.AddHeader("ETag", "SHA1:" + tasksPackageHash);

                            if (size == -1)
                            {
                                size = data.Length;
                            }

                            response.ContentLength64 = size;

                            Stream output = response.OutputStream;
                            output.Write(data, (int)offset, (int)size);
                            output.Close();
                        }
                    }
                }
                catch (HttpListenerException ex)
                {
                    Logger.LogMessage(ex.Message);
                }
            }
        }
        /// <summary>
        /// Adds the file.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="stream">The stream.</param>
        public void AddFile(string path, System.IO.Stream stream)
        {
            Contract.Requires(stream != null, "Stream could not be null");

            this.AddFileCore(path, x => stream.CopyTo(x));
        }
Exemple #39
0
        public FilterStatus Filter(System.IO.Stream dataIn, out long dataInRead, System.IO.Stream dataOut, out long dataOutWritten)
        {
            try
            {
                if (dataIn == null)
                {
                    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);
                string str = System.Text.Encoding.Default.GetString(bs);
                NotifyData(str);

                //if (dataAll.Count == this.contentLength)
                //{
                //    // 通过这里进行通知
                //    NotifyData(dataAll.ToArray());

                //    return FilterStatus.Done;
                //}
                //else if (dataAll.Count < this.contentLength)
                //{
                //    dataInRead = dataIn.Length;
                //    dataOutWritten = dataIn.Length;

                //    return FilterStatus.NeedMoreData;
                //}
                //else
                //{
                //    return FilterStatus.Error;
                //}
            }
            catch (Exception ex)
            {
                LoggerFactory.GetLog().Error("CustomResponseFilter-Filter  出错!", ex);

                dataInRead     = dataIn.Length;
                dataOutWritten = dataIn.Length;

                return(FilterStatus.Done);
            }



            //if (dataIn == null)
            //{
            //    dataInRead = 0;
            //    dataOutWritten = 0;

            //    return FilterStatus.Done;
            //}

            //dataInRead = dataIn.Length;
            //dataOutWritten = Math.Min(dataInRead, dataOut.Length);

            //dataIn.CopyTo(dataOut);

            return(FilterStatus.Done);
        }
Exemple #40
0
 /// <summary>
 /// Copies an stream to another stream using the buffer with specified size.
 /// </summary>
 /// <param name="source">source stream</param>
 /// <param name="destination">destination stream</param>
 /// <param name="bufferLen">length of buffer to create</param>
 /// <returns>number of bytes copied</returns>
 public static long CopyTo(this System.IO.Stream source, System.IO.Stream destination, int bufferLen)
 {
     return(source.CopyTo(destination, new byte[bufferLen]));
 }
Exemple #41
0
 public override void Serialization(Request request, object data, PipeStream stream)
 {
     if (data == null)
     {
         return;
     }
     if (data is IDictionary <string, object> dictionary)
     {
         foreach (var item in dictionary)
         {
             stream.Write("--");
             stream.WriteLine(request.Boundary);
             if (item.Value is UploadFile uploadFile)
             {
                 stream.WriteLine($"Content-Disposition: form-data; name=\"{item.Key}\"; filename=\"{uploadFile.Name}\"");
                 stream.WriteLine($"Content-Type: binary");
                 stream.WriteLine("");
                 stream.Write(uploadFile.Data.Array, uploadFile.Data.Offset, uploadFile.Data.Count);
                 stream.WriteLine("");
             }
             else if (item.Value is FileInfo file)
             {
                 stream.WriteLine($"Content-Disposition: form-data; name=\"{item.Key}\"; filename=\"{file.Name}\"");
                 stream.WriteLine($"Content-Type: binary");
                 stream.WriteLine("");
                 using (System.IO.Stream open = file.OpenRead())
                 {
                     open.CopyTo(stream);
                 }
                 stream.WriteLine("");
             }
             else
             {
                 stream.WriteLine($"Content-Disposition: form-data; name=\"{item.Key}\"");
                 stream.WriteLine("");
                 if (item.Value is IEnumerable subitems)
                 {
                     List <string> values = new List <string>();
                     foreach (var v in subitems)
                     {
                         values.Add(v.ToString());
                     }
                     stream.Write(string.Join(",", values));
                 }
                 else
                 {
                     stream.Write(item.Value.ToString());
                 }
                 stream.WriteLine("");
             }
         }
         if (dictionary.Count > 0)
         {
             stream.Write("--");
             stream.Write(request.Boundary);
             stream.WriteLine("--");
         }
     }
     else
     {
         throw new HttpClientException($"post data must be IDictionary<string, object>!");
     }
 }
Exemple #42
0
        private void DownloadFile()
        {
            if (
                (CurrentPage != null) &&
                (sharedFile != null)
                )
            {
                string virtualPath = "~/Data/Sites/" + this.CurrentPage.SiteId.ToInvariantString() + "/SharedFiles/"
                                     + sharedFile.ServerFileName;

                if (fileSystem.FileExists(virtualPath))
                {
                    //FileInfo fileInfo = new System.IO.FileInfo(downloadPath);
                    WebFile fileInfo = fileSystem.RetrieveFile(virtualPath);

                    Page.Response.AppendHeader("Content-Length", fileInfo.Size.ToString(CultureInfo.InvariantCulture));
                }
                else
                {
                    log.Error("Shared File Not Found. User tried to download file " + virtualPath);
                    return;
                }

                string fileType = Path.GetExtension(sharedFile.FriendlyName).Replace(".", string.Empty);

                string mimeType = SiteUtils.GetMimeType(fileType);
                //Page.Response.ContentType = mimeType;
                Page.Response.ContentType = "application/" + fileType;

                if ((!SharedFilesConfiguration.TreatPdfAsAttachment) && (SiteUtils.IsNonAttacmentFileType(fileType)))
                {
                    //this will display the pdf right in the browser
                    // and the file may be cached by the web browser
                    Page.Response.AddHeader("Content-Disposition", "filename=\"" + HttpUtility.UrlEncode(sharedFile.FriendlyName, Encoding.UTF8) + "\"");
                    if (SharedFilesConfiguration.NonAttachmentDownloadExpireDays != 0)
                    {
                        Page.Response.AddHeader("Expires", DateTime.Now.AddDays(SharedFilesConfiguration.NonAttachmentDownloadExpireDays).ToUniversalTime().ToString("R"));
                    }
                }
                else
                {
                    // other files just use file save dialog
                    Page.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(sharedFile.FriendlyName, Encoding.UTF8) + "\"");

                    // 0 is the default so we should not be settings a cache header here
                    // attachments are not stored in the web browser cache
                    if (SharedFilesConfiguration.AttachmentDownloadExpireDays != 0)
                    {
                        Page.Response.AddHeader("Expires", DateTime.Now.AddDays(SharedFilesConfiguration.AttachmentDownloadExpireDays).ToUniversalTime().ToString("R"));
                    }
                }

                //Page.Response.AddHeader("Content-Length", documentFile.DocumentImage.LongLength.ToString());

                try
                {
                    Page.Response.Buffer       = false;
                    Page.Response.BufferOutput = false;
                    if (Page.Response.IsClientConnected)
                    {
                        //Page.Response.TransmitFile(downloadPath);
                        using (System.IO.Stream stream = fileSystem.GetAsStream(virtualPath))
                        {
                            stream.CopyTo(Page.Response.OutputStream);
                            SharedFile.IncrementDownloadCount(sharedFile.ItemId);
                        }
                        try
                        {
                            Page.Response.End();
                        }
                        catch (System.Threading.ThreadAbortException) { }
                    }
                }
                catch (HttpException) { }
            }
        }
Exemple #43
0
 public void readFromStream(System.IO.Stream stream)
 {
     stream.CopyTo(this.getRawStream());
 }
Exemple #44
0
        private UpLoadFileResult UpLoadPicture(System.IO.Stream file, string dirPath, string fileName = "")
        {
            UpLoadFileResult upLoadFileResult = new UpLoadFileResult();
            string           encodingName     = "utf-8";
            string           imgType          = string.Empty;
            List <string>    typeList         = new List <string>()
            {
                "JPG", "BMP", "PNG", "JPEG"
            };

            using (MemoryStream ms = new MemoryStream())
            {
                file.CopyTo(ms);
                ms.Position = 0;

                var encoding     = Encoding.GetEncoding(encodingName);
                var reader       = new StreamReader(ms, encoding);
                var headerLength = 0L;

                //读取第一行
                var firstLine = reader.ReadLine();
                //计算偏移(字符串长度+回车换行2个字符)
                headerLength += encoding.GetBytes(firstLine).LongLength + 2;

                //读取第二行
                var secondLine = reader.ReadLine();
                //计算偏移(字符串长度+回车换行2个字符)
                headerLength += encoding.GetBytes(secondLine).LongLength + 2;
                //解析文件名
                string orgFileName = new System.Text.RegularExpressions.Regex("filename=\"(?<fn>.*)\"").Match(secondLine).Groups["fn"].Value;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = orgFileName;
                }
                else
                {
                    fileName = orgFileName.Replace(orgFileName.Substring(0, orgFileName.LastIndexOf('.')), fileName);
                }
                //判断图片格式
                imgType = fileName.Substring(fileName.LastIndexOf('.') + 1).ToUpper();
                if (!typeList.Contains(imgType))
                {
                    upLoadFileResult.FileName = "errorType";
                    upLoadFileResult.success  = false;
                    return(upLoadFileResult);
                }
                //一直读到空行为止
                while (true)
                {
                    //读取一行
                    var line = reader.ReadLine();
                    //若到头,则直接返回
                    if (line == null)
                    {
                        break;
                    }
                    //若未到头,则计算偏移(字符串长度+回车换行2个字符)
                    headerLength += encoding.GetBytes(line).LongLength + 2;
                    if (line == "")
                    {
                        break;
                    }
                }

                //设置偏移,以开始读取文件内容
                ms.Position = headerLength;
                ////减去末尾的字符串:“/r/n--/r/n”
                ms.SetLength(ms.Length - encoding.GetBytes(firstLine).LongLength - 3 * 2);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string path = Path.Combine(dirPath, fileName);
                using (FileStream fileToupload = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    ms.CopyTo(fileToupload);
                    fileToupload.Flush();
                }
                upLoadFileResult.FileName = fileName;
                upLoadFileResult.success  = true;
            }
            return(upLoadFileResult);
        }
Exemple #45
0
        bool Execute()
        {
            try
            {
                if (Direction == FtpDirection.ToFtpServer)
                    ExpandDestination = false;
                else
                    ExpandSource = false;

                List<string> sources = new List<string>();
                if (ExpandSource)
                {
                    sources = STEM.Sys.IO.Path.ExpandRangedPath(SourcePath);
                }
                else
                {
                    sources.Add(SourcePath);
                }

                List<string> destinations = new List<string>();
                if (ExpandDestination)
                {
                    destinations = STEM.Sys.IO.Path.ExpandRangedPath(DestinationPath);
                }
                else
                {
                    destinations.Add(DestinationPath);
                }

                List<string> sourceFiles = new List<string>();
                
                int filesActioned = 0;

                FtpClient conn = Authentication.OpenClient(_Address, Int32.Parse(Port));

                try
                {
                    foreach (string src in sources)
                    {
                        List<FtpListItem> items = new List<FtpListItem>();

                        if (Direction == FtpDirection.ToFtpServer)
                        {
                            sourceFiles = STEM.Sys.IO.Directory.STEM_GetFiles(src, FileFilter, DirectoryFilter, (RecurseSource ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly), false);
                        }
                        else
                        {
                            items = Authentication.ListDirectory(_Address, Int32.Parse(Port), src, FTPListType.File, RecurseSource, DirectoryFilter, FileFilter);
                            sourceFiles = items.Select(i => i.FullName).ToList();
                        }

                        foreach (string s in sourceFiles)
                        {
                            try
                            {
                                bool success = false;

                                Exception lastEX = null;

                                foreach (string d in destinations)
                                {
                                    try
                                    {
                                        string dFile = "";

                                        try
                                        {
                                            if (PopulatePostMortemMeta)
                                            {
                                                if (Direction == FtpDirection.ToFtpServer)
                                                {
                                                    PostMortemMetaData["SourceIP"] = STEM.Sys.IO.Path.IPFromPath(s);
                                                    PostMortemMetaData["FileSize"] = new FileInfo(s).Length.ToString();
                                                    PostMortemMetaData["DestinationIP"] = _Address;
                                                }
                                                else
                                                {
                                                    PostMortemMetaData["SourceIP"] = _Address;
                                                    PostMortemMetaData["FileSize"] = conn.GetFileSize(s).ToString();
                                                    PostMortemMetaData["DestinationIP"] = STEM.Sys.IO.Path.IPFromPath(d);
                                                }
                                            }
                                        }
                                        catch { }

                                        string dPath = STEM.Sys.IO.Path.AdjustPath(d);
                                        if (RecurseSource && RecreateTree)
                                        {
                                            dPath = System.IO.Path.Combine(dPath, STEM.Sys.IO.Path.GetDirectoryName(s).Replace(STEM.Sys.IO.Path.AdjustPath(src), "").Trim(System.IO.Path.DirectorySeparatorChar));
                                        }

                                        dPath = System.IO.Path.Combine(dPath, DestinationFilename);

                                        if (dPath.Contains("*.*"))
                                            dPath = dPath.Replace("*.*", STEM.Sys.IO.Path.GetFileName(s));

                                        if (dPath.Contains("*"))
                                            dPath = dPath.Replace("*", STEM.Sys.IO.Path.GetFileNameWithoutExtension(s));

                                        if (Direction == FtpDirection.ToFtpServer)
                                        {
                                            dPath = Authentication.AdjustPath(_Address, dPath);
                                            string directory = Authentication.AdjustPath(_Address, STEM.Sys.IO.Path.GetDirectoryName(dPath));
                                            
                                            if (!conn.DirectoryExists(directory))
                                                conn.CreateDirectory(directory);
                                            
                                            if (conn.FileExists(dPath))
                                            {
                                                switch (ExistsAction)
                                                {
                                                    case Sys.IO.FileExistsAction.Overwrite:
                                                        conn.DeleteFile(dPath);
                                                        dFile = dPath;
                                                        break;

                                                    case Sys.IO.FileExistsAction.OverwriteIfNewer:
                                                        if (conn.GetModifiedTime(dPath, FtpDate.UTC) >= File.GetLastWriteTimeUtc(s))
                                                            continue;

                                                        conn.DeleteFile(dPath);
                                                        dFile = dPath;
                                                        break;

                                                    case Sys.IO.FileExistsAction.Skip:
                                                        continue;

                                                    case Sys.IO.FileExistsAction.Throw:
                                                        throw new IOException("Destination file exists. (" + dPath + ")");

                                                    case Sys.IO.FileExistsAction.MakeUnique:
                                                        dFile = Authentication.UniqueFilename(_Address, Int32.Parse(Port), dPath);
                                                        break;
                                                }
                                            }
                                            else
                                            {
                                                dFile = dPath;
                                            }

                                            DateTime mt = File.GetLastWriteTimeUtc(s);

                                            using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                            {
                                                using (System.IO.Stream dStream = conn.OpenWrite(dFile, FtpDataType.Binary))
                                                {
                                                    sStream.CopyTo(dStream);
                                                }

                                                FtpReply reply = conn.GetReply();

                                                if (!reply.Success)
                                                    throw new Exception("There was an error writing to the FTP server: " + reply.Message);
                                            }

                                            try
                                            {
                                                conn.SetModifiedTime(dFile, mt, FtpDate.UTC);
                                            }
                                            catch { }
                                        }
                                        else
                                        {
                                            if (File.Exists(dPath))
                                            {
                                                switch (ExistsAction)
                                                {
                                                    case Sys.IO.FileExistsAction.Overwrite:
                                                        File.Delete(dPath);
                                                        dFile = dPath;
                                                        break;

                                                    case Sys.IO.FileExistsAction.OverwriteIfNewer:
                                                        if (File.GetLastWriteTimeUtc(dPath) >= conn.GetModifiedTime(s, FtpDate.UTC))
                                                            continue;

                                                        File.Delete(dPath);
                                                        dFile = dPath;
                                                        break;

                                                    case Sys.IO.FileExistsAction.Skip:
                                                        continue;

                                                    case Sys.IO.FileExistsAction.Throw:
                                                        throw new IOException("Destination file exists. (" + dPath + ")");

                                                    case Sys.IO.FileExistsAction.MakeUnique:
                                                        dFile = STEM.Sys.IO.File.UniqueFilename(dPath);
                                                        break;
                                                }
                                            }
                                            else
                                            {
                                                dFile = dPath;
                                            }

                                            if (!Directory.Exists(STEM.Sys.IO.Path.GetDirectoryName(dFile)))
                                                Directory.CreateDirectory(STEM.Sys.IO.Path.GetDirectoryName(dFile));

                                            string tmp = "";

                                            try
                                            {
                                                tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(dFile), "TEMP");

                                                if (!Directory.Exists(tmp))
                                                    Directory.CreateDirectory(tmp);

                                                tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(dFile));

                                                using (System.IO.Stream sStream = conn.OpenRead(s, FtpDataType.Binary))
                                                {
                                                    using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                                    {
                                                        sStream.CopyTo(dStream);
                                                    }
                                                }

                                                try
                                                {
                                                    File.SetLastWriteTimeUtc(tmp, conn.GetModifiedTime(s, FtpDate.UTC));
                                                }
                                                catch { }

                                                File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(dFile));
                                            }
                                            finally
                                            {
                                                try
                                                {
                                                    if (File.Exists(tmp))
                                                        File.Delete(tmp);
                                                }
                                                catch { }
                                            }
                                        }

                                        if (!String.IsNullOrEmpty(dFile))
                                        {
                                            filesActioned++;

                                            _FilesActioned[s] = dFile;

                                            if (Action == ActionType.Move)
                                                AppendToMessage(s + " moved to " + dFile);
                                            else
                                                AppendToMessage(s + " copied to " + dFile);
                                        }

                                        success = true;

                                        if (DestinationActionRule == DestinationRule.FirstSuccess)
                                            break;
                                    }
                                    catch (Exception ex)
                                    {
                                        lastEX = ex;

                                        if (DestinationActionRule == DestinationRule.AllOrNone)
                                            throw ex;
                                    }
                                }

                                if (!success)
                                    throw new Exception("No successful actions taken for " + s, lastEX); // + "\r\n" + ((lastEX == null) ? "No additional information." : lastEX.ToString()));

                                if (Action == ActionType.Move)
                                {
                                    if (Direction == FtpDirection.ToFtpServer)
                                    {
                                        File.Delete(s);
                                    }
                                    else
                                    {
                                        conn.DeleteFile(s);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                AppendToMessage(ex.Message);
                                Exceptions.Add(ex);
                            }
                        }
                    }
                }
                finally
                {
                    Authentication.RecycleClient(conn);
                }

                if (PopulatePostMortemMeta)
                {
                    PostMortemMetaData["FilesActioned"] = filesActioned.ToString();
                }
            }
            catch (Exception ex)
            {
                AppendToMessage(ex.Message);
                Exceptions.Add(ex);
            }

            if (_FilesActioned.Count == 0)
            {
                switch (ZeroFilesAction)
                {
                    case FailureAction.SkipRemaining:
                        SkipRemaining();
                        return true;

                    case FailureAction.SkipNext:
                        SkipNext();
                        return true;

                    case FailureAction.SkipToLabel:
                        SkipForwardToFlowControlLabel(FailureActionLabel);
                        return true;

                    case FailureAction.Rollback:
                        RollbackAllPreceedingAndSkipRemaining();
                        break;

                    case FailureAction.Continue:
                        return true;
                }

                Message = "0 Files Actioned\r\n" + Message;
            }

            return Exceptions.Count == 0;
        }
Exemple #46
0
        protected override void LoadInternal(OpenedFile file, System.IO.Stream stream)
        {
            wasChangedInDesigner = false;
            Debug.Assert(file == this.PrimaryFile);
            SD.AnalyticsMonitor.TrackFeature(typeof(WpfViewContent), "Load");

            _stream = new MemoryStream();
            stream.CopyTo(_stream);
            stream.Position = 0;

            if (designer == null)
            {
                // initialize designer on first load
                designer         = new DesignSurface();
                this.UserContent = designer;
                InitPropertyEditor();
                InitWpfToolbox();
            }
            this.UserContent = designer;
            if (outline != null)
            {
                outline.Root = null;
            }


            using (XmlTextReader r = new XmlTextReader(stream)) {
                XamlLoadSettings settings = new XamlLoadSettings();
                settings.DesignerAssemblies.Add(typeof(WpfViewContent).Assembly);
                settings.CustomServiceRegisterFunctions.Add(
                    delegate(XamlDesignContext context) {
                    context.Services.AddService(typeof(IUriContext), new FileUriContext(this.PrimaryFile));
                    context.Services.AddService(typeof(IPropertyDescriptionService), new PropertyDescriptionService(this.PrimaryFile));
                    context.Services.AddService(typeof(IEventHandlerService), new SharpDevelopEventHandlerService(this));
                    context.Services.AddService(typeof(ITopLevelWindowService), new WpfAndWinFormsTopLevelWindowService());
                    context.Services.AddService(typeof(ChooseClassServiceBase), new IdeChooseClassService());
                });
                settings.TypeFinder = MyTypeFinder.Create(this.PrimaryFile);
                settings.CurrentProjectAssemblyName = SD.ProjectService.CurrentProject.AssemblyName;

                try
                {
                    if (WpfEditorOptions.EnableAppXamlParsing)
                    {
                        var appXaml = SD.ProjectService.CurrentProject.Items.FirstOrDefault(x => x.FileName.GetFileName().ToLower() == ("app.xaml"));
                        if (appXaml != null)
                        {
                            var        f = appXaml as FileProjectItem;
                            OpenedFile a = SD.FileService.GetOrCreateOpenedFile(f.FileName);

                            var xml = XmlReader.Create(a.OpenRead());
                            var doc = new XmlDocument();
                            doc.Load(xml);
                            var node = doc.FirstChild.ChildNodes.Cast <XmlNode>().FirstOrDefault(x => x.Name == "Application.Resources");

                            foreach (XmlAttribute att in doc.FirstChild.Attributes.Cast <XmlAttribute>().ToList())
                            {
                                if (att.Name.StartsWith("xmlns"))
                                {
                                    foreach (var childNode in node.ChildNodes.OfType <XmlNode>())
                                    {
                                        childNode.Attributes.Append(att);
                                    }
                                }
                            }

                            var appXamlXml     = XmlReader.Create(new StringReader(node.InnerXml));
                            var appxamlContext = new XamlDesignContext(appXamlXml, settings);

                            //var parsed = XamlParser.Parse(appXamlXml, appxamlContext.ParserSettings);
                            var dict = (ResourceDictionary)appxamlContext.RootItem.Component;                             // parsed.RootInstance;
                            designer.DesignPanel.Resources.MergedDictionaries.Add(dict);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error("Error in loading app.xaml", ex);
                }

                try
                {
                    settings.ReportErrors = UpdateTasks;
                    designer.LoadDesigner(r, settings);

                    designer.DesignPanel.ContextMenuHandler = (contextMenu) => {
                        var newContextmenu     = new ContextMenu();
                        var sdContextMenuItems = MenuService.CreateMenuItems(newContextmenu, designer, "/AddIns/WpfDesign/Designer/ContextMenu", "ContextMenu");
                        foreach (var entry in sdContextMenuItems)
                        {
                            newContextmenu.Items.Add(entry);
                        }
                        newContextmenu.Items.Add(new Separator());

                        var items = contextMenu.Items.Cast <Object>().ToList();
                        contextMenu.Items.Clear();
                        foreach (var entry in items)
                        {
                            newContextmenu.Items.Add(entry);
                        }

                        designer.DesignPanel.ContextMenu = newContextmenu;
                    };

                    if (outline != null && designer.DesignContext != null && designer.DesignContext.RootItem != null)
                    {
                        outline.Root = OutlineNode.Create(designer.DesignContext.RootItem);
                    }

                    propertyGridView.PropertyGrid.SelectedItems = null;
                    designer.DesignContext.Services.Selection.SelectionChanged += OnSelectionChanged;
                    designer.DesignContext.Services.GetService <UndoService>().UndoStackChanged += OnUndoStackChanged;
                } catch (Exception e) {
                    this.UserContent = new WpfDocumentError(e);
                }
            }
        }
Exemple #47
0
        /// <inheritdoc />
        public override void ForwardProcessDataStream(System.IO.Stream inStream, System.IO.Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            else if (!options.ContainsKey(PasswordOption))
            {
                throw new ArgumentException("Options must contain encryption key", "options");
            }

            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }

#if NETFX_CORE
            inStream.Seek(0, 0);
            outStream.Seek(0, 0);

            IBuffer pwBuffer   = CryptographicBuffer.ConvertStringToBinary(options[PasswordOption], BinaryStringEncoding.Utf8);
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT);

            // Derive key material for password size 32 bytes for AES256 algorithm
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            // using salt and 1000 iterations
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            // create a key based on original key and derivation parmaters
            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

            // derive buffer to be used for encryption salt from derived password key
            IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            // create symmetric key from derived password key
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            using (MemoryStream ms = new MemoryStream())
            {
                inStream.CopyTo(ms);
                // encrypt data buffer using symmetric key and derived salt material
                IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms), saltMaterial);
                resultBuffer.AsStream().CopyTo(outStream);
                writtenBytes = outStream.Position;
            }
#else
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(options[PasswordOption], SALT);
            var key = pdb.GetBytes(32);
            pdb.Reset();
            var iv = pdb.GetBytes(16);

            using (var transform = encrypter.CreateEncryptor(key, iv))
            {
                using (MemoryStream internalStream = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(internalStream, transform, CryptoStreamMode.Write))
                    {
                        StreamTools.Write(inStream, csEncrypt);
                        inStream.Flush();
                        csEncrypt.FlushFinalBlock();

                        internalStream.Seek(0, 0);
                        StreamTools.Write(internalStream, outStream);
                        writtenBytes = outStream.Position;
                    }
                }
            }
#endif
        }
Exemple #48
0
        protected override void _Rollback()
        {
            if (ExecutionMode == ExecuteOn.ForwardExecution)
            {
                foreach (string d in _FilesActioned.Keys)
                {
                    try
                    {
                        string s = _FilesActioned[d];

                        if (Action == ActionType.Move)
                        {
                            if (Direction == FtpDirection.ToFtpServer)
                            {
                                FtpClient conn = Authentication.OpenClient(_Address, Int32.Parse(Port));

                                string tmp = "";

                                try
                                {
                                    tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(d), "TEMP");

                                    if (!Directory.Exists(tmp))
                                        Directory.CreateDirectory(tmp);

                                    tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(d));

                                    using (System.IO.Stream sStream = conn.OpenRead(s, FtpDataType.Binary))
                                    {
                                        using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                        {
                                            sStream.CopyTo(dStream);
                                        }
                                    }

                                    FtpReply reply = conn.GetReply();

                                    if (!reply.Success)
                                        throw new Exception("There was an error reading from the FTP server: " + reply.Message);

                                    try
                                    {
                                        File.SetLastWriteTimeUtc(tmp, conn.GetModifiedTime(s, FtpDate.UTC));
                                    }
                                    catch { }

                                    File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(d));
                                }
                                finally
                                {
                                    try
                                    {
                                        if (File.Exists(tmp))
                                            File.Delete(tmp);
                                    }
                                    catch { }

                                    Authentication.RecycleClient(conn);
                                }
                            }
                            else
                            {
                                FtpClient conn = Authentication.OpenClient(_Address, Int32.Parse(Port));

                                try
                                {
                                    DateTime mt = File.GetLastWriteTimeUtc(STEM.Sys.IO.Path.AdjustPath(s));

                                    using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                    {
                                        using (System.IO.Stream dStream = conn.OpenWrite(d, FtpDataType.Binary))
                                        {
                                            sStream.CopyTo(dStream);
                                        }

                                        FtpReply reply = conn.GetReply();

                                        if (!reply.Success)
                                            throw new Exception("There was an error writing to the FTP server: " + reply.Message);
                                    }

                                    try
                                    {
                                        conn.SetModifiedTime(d, mt, FtpDate.UTC);

                                        FtpReply reply = conn.GetReply();

                                        if (!reply.Success)
                                            throw new Exception("There was an error in SetModifiedTime on the FTP server: " + reply.Message);
                                    }
                                    catch { }
                                }
                                finally
                                {
                                    Authentication.RecycleClient(conn);
                                }
                            }
                        }

                        if (Direction == FtpDirection.ToFtpServer)
                        {
                            FtpClient conn = Authentication.OpenClient(_Address, Int32.Parse(Port)); 
                            
                            try
                            {
                                conn.DeleteFile(s);

                                FtpReply reply = conn.GetReply();

                                if (!reply.Success)
                                    throw new Exception("There was an error deleting a file from the FTP server: " + reply.Message);
                            }
                            finally
                            {
                                Authentication.RecycleClient(conn);
                            }
                        }
                        else
                        {
                            STEM.Sys.IO.File.STEM_Delete(s, false, Retry, RetryDelaySeconds);
                        }
                    }
                    catch { }
                }
            }
            else
            {
                int r = Retry;
                while (r-- >= 0)
                {
                    _Address = Authentication.NextAddress(ServerAddress);

                    if (_Address == null)
                    {
                        Exception ex = new Exception("No valid address. (" + ServerAddress + ")");
                        Exceptions.Add(ex);
                        AppendToMessage(ex.Message);
                        return;
                    }

                    Exceptions.Clear();
                    Message = "";
                    bool success = Execute();
                    if (success)
                        return;

                    System.Threading.Thread.Sleep(RetryDelaySeconds * 1000);
                }
            }
        }
Exemple #49
0
 public static void CopyTo(this Stream me, Stream destination)
 {
     me.CopyTo(destination, 4096);
 }
Exemple #50
0
 public FakeStream(SIO.Stream stream)
 {
     stream.CopyTo(this);
     Stream   = stream;
     Position = 0;
 }
Exemple #51
0
        public MACRSTable()
        {
            string tmp = @"SFACalcEngine.DeprMethods.macrpcts.tbl";

            //string tmp = @"C:\GitSrc\sfa-daas\daas\CalcEngine\SFACalcEngine\DeprMethods\macrpcts.tbl";
            //string tmp = @"..\SFACalcEngine\DeprMethods\macrpcts.tbl";
            try
            {
                Assembly a         = Assembly.GetEntryAssembly();
                string[] resources = a.GetManifestResourceNames();

                System.IO.Stream s = a.GetManifestResourceStream(tmp);
                var memoryStream   = new MemoryStream();
                s.CopyTo(memoryStream);
                m_macrsTable = memoryStream.ToArray();
            }
            catch (Exception e)
            {
                string t = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                //string s = AppDomain.CurrentDomain.BaseDirectory;
                //s = e.Message;
            }
            m_macrsTableCount = m_macrsTable[0];

            //tmp = @"C:\GitSrc\sfa-daas\daas\CalcEngine\SFACalcEngine\DeprMethods\macrs2.tbl";
            tmp = @"SFACalcEngine.DeprMethods.macrs2.tbl";
            try
            {
                Assembly a         = Assembly.GetEntryAssembly();
                string[] resources = a.GetManifestResourceNames();

                System.IO.Stream s = a.GetManifestResourceStream(tmp);
                var memoryStream   = new MemoryStream();
                s.CopyTo(memoryStream);
                m_apolloMacrsTable = memoryStream.ToArray();
            }
            catch (Exception e)
            {
                string t = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                //string s = AppDomain.CurrentDomain.BaseDirectory;
                //s = e.Message;
            }
            //m_apolloMacrsTable = File.ReadAllBytes(tmp);
            m_apolloMacrsTableCount = m_apolloMacrsTable[0];

            m_dAdjustedCost      = 0;
            m_dPostUsedDeduction = 0;
            m_dSalvageDeduction  = 0;
            m_dPriorAccum        = 0;
            m_dYearElapsed       = 0;
            m_dLife               = 0;
            m_dDBPercent          = 0;
            m_dFiscalYearFraction = 0;
            m_dtDeemedStartDate   = DateTime.MinValue;
            m_dtDeemedEndDate     = DateTime.MinValue;
            m_iYearNum            = 0;

            m_dAnuualRate      = 0;
            m_iSwitchYearNum   = 0;
            m_bSwitchRequired  = true;
            m_bIsShortYear     = false;
            m_pObjSwitchMethod = null;
            m_lPeriod          = 0;
            m_parentFlags      = "";
        }
Exemple #52
0
        private async Task StartDownload(DownloadGroup group, DownloadItem item, AccountProfile profile)
        {
            Log("State Downloading - " + item.ID.ToString() + " - " + item.Name);
            item.State = DownloadItem.States.Downloading;
            queryUpdate.Add(item);

            Log("Start Download " + item.ID);
            _lastReadList = new List <double>();
            _lastCurrent  = 0;

            System.IO.Stream s = null;

            IDownloader downloader = DownloadHelper.GetDownloader(item);

            try
            {
                s = await downloader.GetDownloadStream(item, profile);
            }
            catch (Exception e)
            {
                Log("State Error - " + item.ID.ToString() + " - " + item.Name);
                item.State = DownloadItem.States.Error;
                queryUpdate.Add(item);
                queryAdd.Add(new DownloadError(3, item, e));
                await SocketHandler.Instance.SendIDError(item);

                _isDownloading = false;
                Log("Stream Problem");
                Log("DOWNLOAD FALSE");
                return;
            }
            Log("Got Stream " + item.ID);

            string groupDir   = System.IO.Path.Combine(_settings.DownloadFolder, group.Name);
            string filesDir   = System.IO.Path.Combine(_settings.DownloadFolder, group.Name, "files");
            string extractDir = System.IO.Path.Combine(_settings.DownloadFolder, group.Name, "extracted");

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

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

                if (!System.IO.Directory.Exists(extractDir))
                {
                    System.IO.Directory.CreateDirectory(extractDir);
                }
            }
            catch (Exception e)
            {
                Log("State Error - " + item.ID.ToString() + " - " + item.Name);
                item.State = DownloadItem.States.Error;
                queryUpdate.Add(item);
                await SocketHandler.Instance.SendIDError(item);

                queryAdd.Add(new DownloadError(4, item, e));
                Log("Error happened: " + e.Message);
                _isDownloading = false;
                return;
            }
            Log("Folders Checked " + item.ID + " - " + item.Name);


            string filePath = System.IO.Path.Combine(filesDir, item.Name);

            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }

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

            _state = new Timer(CheckStatus, new GroupItemModel()
            {
                Group = group, Item = item
            }, 0, 1000);
            Log("Timer started " + item.ID);

            try
            {
                s.CopyTo(fs);
            }
            catch (Exception e)
            {
                await SocketHandler.Instance.SendIDError(item);

                item.State = DownloadItem.States.Error;
                Log("State Error - " + item.ID.ToString() + " - " + item.Name);
                queryUpdate.Add(item);
                queryAdd.Add(new DownloadError(5, item, e));
                _isDownloading = false;
                return;
            }

            fs.Close();
            fs.Dispose();
            _state.Dispose();
            _state = null;
            Log("fs + state disposed");



            if (_stopRequested)
            {
                _stopRequested = false;
                Log("Cancel requested");
                item.State = DownloadItem.States.Waiting;
                Log("State Waiting - " + item.ID.ToString() + " - " + item.Name);
                queryUpdate.Add(item);
                _isDownloading = false;
                return;
            }

            Log("Download finished " + item.ID);

            if (item.MD5 == null)
            {
                await SocketHandler.Instance.SendIDDownloaded(item);

                Log("State Downloaded - " + item.ID.ToString() + " - " + item.Name);
                item.State = DownloadItem.States.Downloaded;
                Log("Md5 not set " + item.ID);
                queryUpdate.Add(item);
                _isDownloading = false;

                return;
            }


            await SocketHandler.Instance.SendIDCheck(item);

            Log("Check MD5 " + item.ID);
            string hash = "";

            using (var md5 = MD5.Create())
                using (var stream = System.IO.File.OpenRead(filesDir + System.IO.Path.DirectorySeparatorChar + item.Name))
                    hash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLowerInvariant();

            if (item.MD5 == hash)
            {
                await SocketHandler.Instance.SendIDDownloaded(item);

                item.State = DownloadItem.States.Downloaded;
            }
            else
            {
                await SocketHandler.Instance.SendIDError(item);

                item.State = DownloadItem.States.Error;
                Log("MD5 Error - " + item.ID.ToString() + " - " + item.Name);
                queryAdd.Add(new DownloadError(6, item, new Exception("MD5 Check failed")));
            }

            Log("Md5 checked " + item.ID);

            try
            {
                queryUpdate.Add(item);
            }
            catch (Exception e)
            {
                Log("Update Error - " + e.Message + " - " + item.Name);
            }
            _isDownloading = false;

            Log("Added to query download completed " + item.ID);
        }
Exemple #53
0
        private void Download(HttpContext context)
        {
            try
            {
                if (OnFileDownloading(virtualPath))
                {
                    WebFile file = fileSystem.RetrieveFile(virtualPath);

                    if (file != null)
                    {
                        if (!fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(file.Name)))
                        {
                            RenderJsonResult(context, OpResult.FileTypeNotAllowed);
                            //context.Response.StatusCode = 500;
                            return;
                        }

                        if (file.Path != null)
                        {
                            context.Response.AppendHeader("Content-Length", file.Size.ToString(CultureInfo.InvariantCulture));
                            context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name.Trim() + "\"");

                            try
                            {
                                if (WebConfigSettings.DownloadScriptTimeout > -1)
                                {
                                    context.Server.ScriptTimeout = WebConfigSettings.DownloadScriptTimeout;
                                }

                                context.Response.Buffer       = false;
                                context.Response.BufferOutput = false;
                                // this won't work for Azure storage
                                //context.Response.TransmitFile(file.Path);
                                // so we use this approach
                                using (System.IO.Stream stream = fileSystem.GetAsStream(virtualPath))
                                {
                                    stream.CopyTo(context.Response.OutputStream);
                                }

                                context.Response.End();
                            }
                            catch (System.Threading.ThreadAbortException) { } // can happen with Response.End
                            catch (HttpException ex)
                            {
                                log.Error(ex);
                                context.Response.StatusCode = 500;
                            }

                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                //context.Response.StatusCode = 500;
            }

            // Requested file not found
            context.Response.StatusCode = 404;
        }
        private void DownloadFile()
        {
            ProductFile productFile = null;

            if (downloadTicket != null)
            {
                productFile = new ProductFile(downloadTicket.ProductGuid);
            }
            else if (userCanEdit && (productGuid != Guid.Empty))
            {
                productFile = new ProductFile(productGuid);
            }


            if (productFile == null)
            {
                return;
            }

            string fileType = Path.GetExtension(productFile.FileName).Replace(".", string.Empty).ToLowerInvariant();
            string mimeType = SiteUtils.GetMimeType(fileType);

            Page.Response.ContentType = mimeType;

            if (WebConfigSettings.DownloadScriptTimeout > -1)
            {
                Server.ScriptTimeout = WebConfigSettings.DownloadScriptTimeout;
            }

            if (SiteUtils.IsNonAttacmentFileType(fileType))
            {
                Page.Response.AddHeader("Content-Disposition", "filename=" + productFile.FileName);
            }
            else
            {
                Page.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(productFile.FileName, Encoding.UTF8) + "\"");
            }

            //Page.Response.AddHeader("Content-Length", documentFile.DocumentImage.LongLength.ToString());

            Page.Response.ContentType  = "application/" + fileType;
            Page.Response.Buffer       = false;
            Page.Response.BufferOutput = false;
            //Page.Response.TransmitFile(upLoadPath + productFile.ServerFileName);

            if (Page.Response.IsClientConnected)
            {
                using (System.IO.Stream stream = fileSystem.GetAsStream(upLoadPath + productFile.ServerFileName))
                {
                    stream.CopyTo(Page.Response.OutputStream);
                }

                if (downloadTicket != null)
                {
                    downloadTicket.RecordDownloadHistory(SiteUtils.GetIP4Address());
                }
            }


            try
            {
                Page.Response.End();
            }
            catch (System.Threading.ThreadAbortException) { }
        }
Exemple #55
0
        public string UploadSPFile(SharePointContext spContext, HttpPostedFileBase tempFile, string documentFolder, string siteUrl, string prefix)
        {
            log.Info("- OutboxDocs - UploadSPFile");
            var result = string.Empty;

            using (var clientContext = spContext.CreateAppOnlyClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    try
                    {
                        var relativeSite = clientContext.Url.Substring(clientContext.Url.IndexOf('/', 10));
                        var folder       = clientContext.Web.GetFolderByServerRelativeUrl(documentFolder);
                        clientContext.Load(folder);
                        clientContext.ExecuteQuery();
                        FileCreationInformation fci = new FileCreationInformation();
                        if (tempFile.ContentLength < 1000000) // ~1MB
                        {
                            using (System.IO.Stream inputStream = tempFile.InputStream)
                            {
                                var memoryStream = inputStream as System.IO.MemoryStream;
                                if (memoryStream == null)
                                {
                                    memoryStream = new System.IO.MemoryStream();
                                    inputStream.CopyTo(memoryStream);
                                }
                                fci.Content = memoryStream.ToArray();
                            }
                            fci.Url       = documentFolder + "/" + prefix + tempFile.FileName;
                            fci.Overwrite = true;
                            Microsoft.SharePoint.Client.File fileToUpload = folder.Files.Add(fci);
                            clientContext.Load(fileToUpload);
                            clientContext.ExecuteQuery();
                            Uri hostUrl = new Uri(siteUrl);
                            result = "https://" + hostUrl.Host + fileToUpload.ServerRelativeUrl;
                        }
                        else if (tempFile.ContentLength < 5000000) // ~5MB
                        {
                            fci.ContentStream = tempFile.InputStream;
                            fci.Url           = documentFolder + "/" + prefix + tempFile.FileName;
                            fci.Overwrite     = true;
                            Microsoft.SharePoint.Client.File fileToUpload = folder.Files.Add(fci);
                            clientContext.Load(fileToUpload);
                            clientContext.ExecuteQuery();
                            Uri hostUrl = new Uri(siteUrl);
                            result = "https://" + hostUrl.Host + fileToUpload.ServerRelativeUrl;
                        }
                        if (tempFile.ContentLength >= 5000000) // > ~5MB
                        {
                            Guid uploadId = Guid.NewGuid();
                            Microsoft.SharePoint.Client.File uploadFile;
                            int blockSize = 4 * 1024 * 1024; // 5MB blocks
                            ClientResult <long> bytesUploaded = null;
                            byte[] buffer         = new byte[blockSize];
                            Byte[] lastBuffer     = null;
                            long   fileoffset     = 0;
                            long   totalBytesRead = 0;
                            int    bytesRead;
                            bool   first = true;
                            bool   last  = false;
                            using (BinaryReader br = new BinaryReader(tempFile.InputStream))
                            {
                                while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    totalBytesRead = totalBytesRead + bytesRead;

                                    // You've reached the end of the file.
                                    if (totalBytesRead == tempFile.ContentLength)
                                    {
                                        last = true;
                                        // Copy to a new buffer that has the correct size.
                                        lastBuffer = new byte[bytesRead];
                                        Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                                    }

                                    if (first)
                                    {
                                        using (MemoryStream contentStream = new MemoryStream())
                                        {
                                            // Add an empty file.
                                            FileCreationInformation fileInfo = new FileCreationInformation();
                                            fileInfo.ContentStream = contentStream;
                                            fileInfo.Url           = prefix + tempFile.FileName;
                                            fileInfo.Overwrite     = true;
                                            uploadFile             = folder.Files.Add(fileInfo);

                                            // Start upload by uploading the first slice.
                                            using (MemoryStream s = new MemoryStream(buffer))
                                            {
                                                // Call the start upload method on the first slice.
                                                bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                                clientContext.ExecuteQuery();
                                                // fileoffset is the pointer where the next slice will be added.
                                                fileoffset = bytesUploaded.Value;
                                            }

                                            // You can only start the upload once.
                                            first = false;
                                        }
                                    }
                                    else
                                    {
                                        // Get a reference to your file.
                                        uploadFile = clientContext.Web.GetFileByServerRelativeUrl(folder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + prefix + tempFile.FileName);

                                        if (last)
                                        {
                                            // Is this the last slice of data?
                                            using (MemoryStream s = new MemoryStream(lastBuffer))
                                            {
                                                // End sliced upload by calling FinishUpload.
                                                uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                                clientContext.Load(uploadFile);
                                                clientContext.ExecuteQuery();

                                                // Return the file object for the uploaded file.
                                                Uri hostUrl = new Uri(siteUrl);
                                                result = "https://" + hostUrl.Host + uploadFile.ServerRelativeUrl;
                                            }
                                        }
                                        else
                                        {
                                            using (MemoryStream s = new MemoryStream(buffer))
                                            {
                                                // Continue sliced upload.
                                                bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                                clientContext.ExecuteQuery();
                                                // Update fileoffset for the next slice.
                                                fileoffset = bytesUploaded.Value;
                                            }
                                        }
                                    }
                                } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                    }
                }
            }
            return(result);
        }
Exemple #56
0
        public ActionResult Editar(AtividadeLink item)
        {
            //if(item.atividadeArq.MudançaArq == 1 && item.atividadeArq.caminhoArquivo != null)
            //{
            //    return BadRequest("Impossivel enviar duas escolhas ao mesmo tempo");
            //}

            string arquivoAntigo = item.atividade.caminhoArquivo;

            if (ModelState.IsValid)
            {
                if (item == null)
                {
                    return(new BadRequestResult());
                }


                string nomedoArquivo = null;


                if (item.atividade.Arquivo != null)
                {
                    string arquivosPasta = Path.Combine(hostingEnvironment.ContentRootPath, "arquivos");
                    if (item.atividade.caminhoArquivo != null)
                    {
                        List <string> tiposArquivos = new List <string>();



                        tiposArquivos.Add(MediaTypeNames.Application.Pdf);
                        tiposArquivos.Add(MediaTypeNames.Application.Rtf);
                        tiposArquivos.Add(MediaTypeNames.Image.Jpeg);
                        tiposArquivos.Add(MediaTypeNames.Image.Tiff);
                        tiposArquivos.Add("image/png");
                        tiposArquivos.Add("image/jpg");
                        tiposArquivos.Add("image/bmp");

                        /*Os tipos de formatos de arquivo de certificado usados podem basear-se em uma combinação de questões de segurança e de compatibilidade. Nesta versão do Windows, você pode importar e exportar certificados nestes formatos:
                         * Troca de Informações Pessoais (PKCS #12)
                         * Padrão de Sintaxe de Mensagens Criptografadas (PKCS #7)
                         * X.509 binário codificado por DER
                         * X.509 codificado na Base64
                         *
                         * Trata-se de um método de codificação desenvolvido para uso com extensões multipropósito do Internet Mail protegidas (S/MIME), que é um método padrão popular para transferência de anexos binários pela Internet.
                         * Como todos os clientes compatíveis com MIME podem decodificar arquivos Base64, esse formato pode ser usado por autoridades de certificação que não estão em computadores com o Windows Server 2003, para que seja permitida a interoperabilidade. Os arquivos de certificado na Base64 usam a extensão .cer.*/


                        int tipos = 0;
                        while (tipos <= tiposArquivos.Count)
                        {
                            if (tipos == tiposArquivos.Count)
                            {
                                TempData["erroTiposArquivo"] = true;
                                return(RedirectToAction("Index"));
                            }
                            else if (tiposArquivos[tipos] == item.atividade.Arquivo.ContentType)
                            {
                                break;
                            }

                            tipos++;
                        }



                        if (item.atividade.Arquivo.Length > 2000000)
                        {
                            TempData["erroTamanhoArquivo"] = true;
                            return(RedirectToAction("Index"));
                        }
                        //ESSE TAMANHO FOI ESCOLHIDO, POIS UM ARQUIVO PDF DE 2MBS, TEM CERCA DE 30 PÁGINAS. Logo, um "simples" arquivo de atividade, não é necessário passar disso.

                        nomedoArquivo = Guid.NewGuid().ToString() + "_" + item.atividade.Arquivo.FileName;
                        string caminhoArquivo = Path.Combine(arquivosPasta, nomedoArquivo);

                        using (System.IO.Stream a = item.atividade.Arquivo.OpenReadStream())
                        {
                            a.CopyTo(new FileStream(caminhoArquivo, FileMode.CreateNew));
                            a.Close();
                        }


                        item.atividade.caminhoArquivo = nomedoArquivo;
                    }
                    else
                    {
                        nomedoArquivo = Guid.NewGuid().ToString() + "_" + item.atividade.Arquivo.FileName;
                        string caminhoArquivo = Path.Combine(arquivosPasta, nomedoArquivo);

                        using (System.IO.Stream a = item.atividade.Arquivo.OpenReadStream())
                        {
                            a.CopyTo(new FileStream(caminhoArquivo, FileMode.CreateNew));
                            a.Close();
                        }

                        item.atividade.caminhoArquivo = nomedoArquivo;
                    }
                }

                try
                {
                    context.TBAtividades.Update(item.atividade);
                    context.SaveChanges();
                    if (System.IO.File.Exists(arquivoAntigo))
                    {
                        System.IO.File.Delete(arquivoAntigo);
                    }
                }
                catch (Exception e)
                {
                    //erro na hora de salvar
                    return(BadRequest("É impossível enviar o arquivo:" + e));
                }

                TempData["EditarAtividade"] = true;
                return(RedirectToAction("Index"));
            }
            else
            {
                TempData["EditarAtividade"] = false;
                return(RedirectToAction("Index"));
            }
        }