OpenRead() private méthode

private OpenRead ( String path ) : FileStream
path String
Résultat FileStream
    /// <summary>
    ///     Opens a <see cref="Stream" /> to read from a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <returns>
    ///     A <see cref="Stream" /> that can read from a file.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
    /// </exception>
    public Stream OpenRead(string path)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));

        return(FSFile.OpenRead(path));
    }
Exemple #2
0
    public async Task RunAsync(CancellationToken cancellationToken)
    {
        var response = await _sqsClient.ReceiveMessageAsync(_servicesSettings.UploaderQueueUrl, cancellationToken);

        var queueMessage = response.Messages.FirstOrDefault();

        if (queueMessage == null)
        {
            return;
        }

        var(receivedMessage, sentMessage, inputFilePath, outputFilePath, thumbnailFilePath) =
            JsonSerializer.Deserialize <UploaderMessage>(queueMessage.Body) !;

        try
        {
            await _bot.EditMessageTextAsync(new(sentMessage.Chat.Id),
                                            sentMessage.MessageId,
                                            "Your file is uploading 🚀", cancellationToken : cancellationToken);

            await using var videoStream = File.OpenRead(outputFilePath);
            await using var imageStream = File.OpenRead(thumbnailFilePath);

            await _bot.DeleteMessageAsync(new(sentMessage.Chat.Id),
                                          sentMessage.MessageId, cancellationToken);

            await _bot.SendVideoAsync(new(sentMessage.Chat.Id),
                                      new InputMedia(videoStream, outputFilePath),
                                      caption : "🇺🇦 Help the Ukrainian army fight russian and belarus invaders: https://savelife.in.ua/en/donate/",
                                      replyToMessageId : receivedMessage.MessageId,
                                      thumb : new(imageStream, thumbnailFilePath),
                                      disableNotification : true, cancellationToken : cancellationToken);

            var cleanerMessage = new CleanerMessage(inputFilePath, outputFilePath, thumbnailFilePath);

            await _sqsClient.SendMessageAsync(_servicesSettings.CleanerQueueUrl,
                                              JsonSerializer.Serialize(cleanerMessage, JsonSerializerConstants.SerializerOptions), cancellationToken);

            await _sqsClient.DeleteMessageAsync(_servicesSettings.UploaderQueueUrl, queueMessage.ReceiptHandle, cancellationToken);
        }
        catch (ApiRequestException telegramException)
        {
            _logger.LogError(telegramException, "Telegram error during Uploader execution:");
            await _sqsClient.DeleteMessageAsync(_servicesSettings.UploaderQueueUrl, queueMessage.ReceiptHandle, cancellationToken);
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Error during Uploader execution:");
        }
    }
        private BlogMLDocument GetDocument(string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("File not found: " + fileName);
            }

            using (var stream = File.OpenRead(fileName))
            {
                var document = new BlogMLDocument();
                document.Load(stream);
                return(document);
            }
        }
Exemple #4
0
    public string[] Load(string filename)
    {
        GD.Print("load");


        var textures = new System.Collections.Generic.Dictionary <string, Texture>();

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(filename)))
        {
            ZipEntry entry;


            while ((entry = s.GetNextEntry()) != null)
            {
                GD.Print($"Name : {entry.Name}");
                GD.Print($"Uncompressed : {entry.Size/1024.0/1024.0}MB");
                GD.Print($"Compressed   : {entry.CompressedSize/1024.0/1024.0}MB");

                if (!entry.IsFile)
                {
                    continue;
                }
                if (!entry.Name.StartsWith(SlotsPrefix))
                {
                    continue;
                }

                var dict = (System.Collections.Generic.Dictionary <object, object>) new BinaryFormatter().Deserialize(s);
                Debug.Assert(1 == s.Read(new byte[1], 0, 1)); //DO NOT REMOVE THIS! REQUIRED!!!

                ImageTexture tex           = new ImageTexture();
                var          dictConverted = new Dictionary(); //NOTE - this is a Godot dictionary, not a C# one, so we need to convert it:

                foreach (var kv in dict)
                {
                    dictConverted.Add(kv.Key, kv.Value);
                }

                tex.CreateFromImage(new Image {
                    Data = dictConverted
                });

                textures.Add(entry.Name.Replace(SlotsPrefix, ""), tex);
            }
        }


        Textures = textures;             //MASSIVE hack
        return(textures.Keys.ToArray()); //MASSIVE hack (needed since marshalling doesn't support dictionaries yet)
    }
Exemple #5
0
        //UserManagement

        private void MainWindow_OnInitialized(object?sender, EventArgs e)
        {
            string csvpath = null;

            //create history
            if (!File.Exists(path_last))
            {
                //Create Directory and File for the Config
                Directory.CreateDirectory(path_last.Remove(path_last.LastIndexOf("\\")));
                var tmp = File.Create(path_last);
                tmp.Close();
            }
            else
            {
                using (FileStream fs = File.OpenRead(path_last))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        //Delete the content of the file
                        csvpath = sr.ReadLine();
                    }
                }

                try
                {
                    AccProjectConfig.LoadBim360Projects(csvpath);
                }
                catch (Exception)
                {
                }
            }

            var ConfigFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Bim360Interface\Config\config.txt";;

            //Get Last Config from Login Data
            if (File.Exists(ConfigFilePath))
            {
                using (FileStream fs = File.OpenRead(ConfigFilePath))
                {
                    using (StreamReader reader = new StreamReader(fs))
                    {
                        ClientId     = reader.ReadLine();
                        ClientSecret = reader.ReadLine();
                        BimId        = reader.ReadLine();
                        AdminMail    = reader.ReadLine();
                    }
                }
            }
        }
Exemple #6
0
        public static void WriteTarGzArchive(string output, params TarInput[] bunches)
        {
            var dirs = new HashSet <string>();

            using (var stream = File.Create(output))
                using (var gzip = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression))
                    using (var tar = new TarOutputStream(gzip))
                    {
                        foreach (var bunch in bunches)
                        {
                            var baseDir   = bunch.BaseDir;
                            var prefixDir = bunch.InstallDir;
                            var inputs    = bunch.Files;
                            if (baseDir != null)
                            {
                                baseDir = Path.GetFullPath(baseDir);
                            }
                            foreach (var file in inputs)
                            {
                                var info = new FileInfo(file);
                                var name = info.Name;
                                if (baseDir != null)
                                {
                                    name = Path.GetFullPath(file).Replace(baseDir, "").TrimStart(Path.DirectorySeparatorChar);
                                }
                                if (prefixDir != null)
                                {
                                    name = Path.Combine(prefixDir, name);
                                }
                                EnsureDirectories(name, dirs, tar);
                                var source   = File.OpenRead(file);
                                var size     = info.Length;
                                var modified = info.LastWriteTime;
                                var entry    = TarEntry.CreateEntryFromFile(file);
                                var header   = entry.TarHeader;
                                header.Name          = FixSlash(name);
                                header.Size          = size;
                                header.ModTime       = modified;
                                header.GroupName     = "root";
                                header.UserName      = "******";
                                entry.TarHeader.Mode = GetPermissions(info.Name, true);
                                tar.PutNextEntry(entry);
                                using (source)
                                    source.CopyTo(tar);
                                tar.CloseEntry();
                            }
                        }
                    }
        }
Exemple #7
0
        public string LoadJson(string source)
        {
            var filePath = _env.WebRootPath + source;

            if (FileIO.Exists(filePath))
            {
                var fs = FileIO.OpenRead(filePath);
                using (var r = new StreamReader(fs))
                {
                    var json = r.ReadToEnd();
                    return(json);
                }
            }
            return(null);
        }
Exemple #8
0
        /// <summary>
        /// Deserializes an xml file into an object.
        /// </summary>
        /// <typeparam name="TType">The type of the deserialized object.</typeparam>
        /// <param name="fileName">The filename to parse.</param>
        /// <param name="serializer">The XML serializer instance to use for parsing</param>
        /// <returns>A matching object instance or <c>null</c></returns>
        private static TType _DeserializeOrDefault <TType>(string fileName, XmlSerializer serializer) where TType : class
        {
            if (!File.Exists(fileName))
            {
                return(null);
            }

            try {
                using (var stream = File.OpenRead(fileName))
                    return(serializer.Deserialize(stream) as TType);
            } catch (Exception e) {
                logger.ErrorFormat($"Failed to parse nfo file for {fileName}", fileName);
                return(null);
            }
        }
Exemple #9
0
        /// <summary>
        /// MIDI ファイルのパスを指定して、再生を開始します。
        /// </summary>
        /// <param name="filePath">ファイルパス。</param>
        /// <param name="loopCount"></param>
        /// <param name="fadeOutTime"></param>
        public void Play(string filePath, int loopCount = -1, int fadeOutTime = 2000)
        {
            // 正しく生成されていればこれらはnullでないはずなので、例外が投げられたらバグが起きているはず
            if (CorePlayer == null ||
                _nativeplayer == null ||
                _cts == null ||
                _buffer == null
                )
            {
                throw new InvalidOperationException("初期化が完了していません。");
            }

            CorePlayer.Load(SmfParser.Parse(F.OpenRead(P.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath))));

            PlayAsync(loopCount, fadeOutTime);
        }
Exemple #10
0
            private void Finish(long chatId, IFileSource source)
            {
                var f = TagLib.File.Create(source.FileInfo.FullName, ReadStyle.Average);

                SendTextMessage(chatId,
                                $"{source.FileName}\nTitle:\t{f.Tag.Title}\nArtists:\t{string.Join(", ", f.Tag.Performers)}");

                BotClient.SendAudioAsync(
                    chatId: chatId,
                    audio: File.OpenRead(source.FileInfo.FullName),
                    caption: f.Tag.Lyrics,
                    duration: (int)f.Properties.Duration.TotalSeconds,
                    performer: string.Join(' ', f.Tag.Performers),
                    title: f.Tag.Title
                    );
            }
        public async Task <Message> SendMediaAsync(string fileId, MediaType mediaType, string caption = "",
                                                   IReplyMarkup replyMarkup = null, int replyToMsgId = -1)
        {
            Log.Information($"Sending media: {mediaType}, fileId: {fileId} to {Message.Chat.Id}");

            switch (mediaType)
            {
            case MediaType.Document:
                return(await Client.SendDocumentAsync(Message.Chat.Id, fileId, caption, ParseMode.Html,
                                                      replyMarkup : replyMarkup, replyToMessageId : replyToMsgId)
                       .ConfigureAwait(false));

                break;

            case MediaType.LocalDocument:
                var fileName = Path.GetFileName(fileId);
                await using (var fs = File.OpenRead(fileId))
                {
                    InputOnlineFile inputOnlineFile = new InputOnlineFile(fs, fileName);
                    return(await Client.SendDocumentAsync(Message.Chat.Id, inputOnlineFile, caption, ParseMode.Html,
                                                          replyMarkup : replyMarkup, replyToMessageId : replyToMsgId)
                           .ConfigureAwait(false));
                }

                break;

            case MediaType.Photo:
                return(await Client.SendPhotoAsync(Message.Chat.Id, fileId, caption, ParseMode.Html,
                                                   replyMarkup : replyMarkup, replyToMessageId : replyToMsgId)
                       .ConfigureAwait(false));

                break;

            case MediaType.Video:
                return(await Client.SendVideoAsync(Message.Chat.Id, fileId, caption : caption, parseMode : ParseMode.Html,
                                                   replyMarkup : replyMarkup, replyToMessageId : replyToMsgId)
                       .ConfigureAwait(false));

                break;

            default:
                Log.Information($"Media unknown: {mediaType}");
                return(null);

                break;
            }
        }
        public override bool Execute()
        {
            if (!IOFile.Exists(File))
            {
                Log.LogError("'{0}' does not exist", File);
                return(false);
            }

            Directory.CreateDirectory(Destination);

            var output = new List <ITaskItem>();

            using (var stream = IOFile.OpenRead(File))
                using (var zip = new ZipArchiveStream(stream, ZipArchiveMode.Read))
                {
                    foreach (var entry in zip.Entries)
                    {
                        var entryPath = entry.FullName;
                        if (!DisablePathNormalization)
                        {
                            if (entry.FullName.IndexOf('\\') >= 0)
                            {
                                Log.LogMessage(null, null, null, File, 0, 0, 0, 0, MessageImportance.Low,
                                               message: $"Zip entry '{entry.FullName}' has been normalized because it contains a backslash. Set DisablePathNormalization=true to disable this.");
                                entryPath = entry.FullName.Replace('\\', '/');
                            }
                        }

                        var fileDest = Path.Combine(Destination, entryPath);
                        var dirName  = Path.GetDirectoryName(fileDest);
                        Directory.CreateDirectory(dirName);

                        // Do not try to extract directories
                        if (Path.GetFileName(fileDest) != string.Empty)
                        {
                            entry.ExtractToFile(fileDest, Overwrite);
                            Log.LogMessage(MessageImportance.Low, "Extracted '{0}'", fileDest);
                            output.Add(new TaskItem(fileDest));
                        }
                    }
                }

            Log.LogMessage(MessageImportance.High, "Extracted {0} file(s) to '{1}'", output.Count, Destination);
            OutputFiles = output.ToArray();

            return(true);
        }
        public static void NewMicrosoftAuthentication(this IObjectSpaceProvider objectSpaceProvider, Platform platform = Platform.Win)
        {
            using (var manifestResourceStream = File.OpenRead($"{AppDomain.CurrentDomain.ApplicationPath()}\\AuthenticationData{platform}.json")){
                var token = Encoding.UTF8.GetBytes(new StreamReader(manifestResourceStream).ReadToEnd());
                using (var objectSpace = objectSpaceProvider.CreateObjectSpace()){
                    var authenticationOid = (Guid)objectSpace.GetKeyValue(SecuritySystem.CurrentUser);
                    if (objectSpace.GetObjectByKey <MSAuthentication>(authenticationOid) == null)
                    {
                        var authentication = objectSpace.CreateObject <MSAuthentication>();

                        authentication.Oid   = authenticationOid;
                        authentication.Token = token.GetString();
                        objectSpace.CommitChanges();
                    }
                }
            }
        }
Exemple #14
0
        public IActionResult Download(string md5, string token)
        {
            if (!CheckReferer())
            {
                _logger.LogError($"非安全域名访问:{GetHost()}");
                return(new StatusCodeResult((int)HttpStatusCode.NotAcceptable));
            }

            var jwthandle = new JwtSecurityTokenHandler();

            if (string.IsNullOrEmpty(token) || !jwthandle.CanReadToken(token))
            {
                _logger.LogInformation($"非法下载:{md5}!");
                return(new StatusCodeResult((int)HttpStatusCode.NonAuthoritativeInformation));
            }

            var paramters = JwtHelper.GetParameters(_jwtConfig);

            jwthandle.ValidateToken(token, paramters, out SecurityToken sToekn);
            if (sToekn == null)
            {
                _logger.LogInformation($"非法下载:{md5}!");
                return(new StatusCodeResult((int)HttpStatusCode.NonAuthoritativeInformation));
            }

            var file = _sysFileManager.GetForMd5(md5);

            if (file == null)
            {
                _logger.LogError($"文件不存在:{md5}!");
                return(new StatusCodeResult((int)HttpStatusCode.NotFound));
            }
            var path = Path.Combine(_appConfig.FilePath, file.FileDate, file.CreatedUserId.ToString(), $"{md5}{Path.GetExtension(file.FileName)}");

            if (!IoFile.Exists(path))
            {
                _logger.LogError($"文件不存在:{md5}!");
                return(new StatusCodeResult((int)HttpStatusCode.NotFound));
            }
            new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(path), out var contenttype);
            var stream = IoFile.OpenRead(path);

            return(File(stream, contenttype ?? "application/octet-stream", file.FileName));
        }
Exemple #15
0
        /// <summary>
        /// Sends the file to virtual machine using SSH.NET SFTP.
        /// </summary>
        /// <param name="hostname">The hostname.</param>
        /// <param name="port">The port.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="localFilesPath">The local files path.</param>
        /// <param name="remotePath">The remote path.</param>
        /// <returns></returns>
        public static string SendFileSftp(string hostname, int port, string username, string password, List <string> localFilesPath, string remotePath)
        {
            SftpClient client;

            try
            {
                client = new SftpClient(hostname, port, username, password);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return("Cannot create client");
            }

            try
            {
                using (client)
                {
                    client.Connect();
                    client.BufferSize = 4 * 1024;
                    foreach (string filePath in localFilesPath)
                    {
                        string fname = filePath;
                        //new FileInfo(filePath).ToString();

                        //var fileStream = new FileStream(fname, FileMode.Open);
                        FileStream fileStream  = File.OpenRead(fname);
                        var        destination =
                            $"{remotePath}/{new FileInfo(filePath).Name}";
                        client.UploadFile(fileStream, destination, true, null);
                        logger.Info("Uploaded: {0}", destination);
                    }

                    client.Disconnect();
                    client.Dispose();
                    return("Uploaded");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return("Cannot upload");
            }
        }
        public MicrosoftGraphBlobProvider( )
        {
            Logger.LogInformation("Loading setting file.");

            if (File.Exists(SettingFileName))
            {
                Logger.LogInformation("Setting file exists, Reading.");

                try
                {
                    using (FileStream stream = File.OpenRead(SettingFileName))
                    {
                        Setting = MicrosoftGraphSetting.Load(stream);
                    }

                    Logger.LogInformation("Setting file loaded.");
                }
                catch (Exception)
                {
                    Logger.LogInformation("Setting file error, will use default value.");
                    Setting = MicrosoftGraphSetting.GenerateNew( );
                }
            }
            else
            {
                Logger.LogInformation("Setting file doesn't exists, generating new.");
                Setting = MicrosoftGraphSetting.GenerateNew( );
                SaveSettingFile( );
            }

            if (string.IsNullOrWhiteSpace(Setting.ClientId) ||
                string.IsNullOrWhiteSpace(Setting.TenantId) ||
                string.IsNullOrWhiteSpace(Setting.UserName) ||
                string.IsNullOrWhiteSpace(Setting.Password) ||
                string.IsNullOrWhiteSpace(Setting.BlockDirectory))
            {
                Logger.LogCritical(
                    "Current setting file lacks required settings, check setting file and start program again.");

                Program.Program.Current.Exit(ProgramExitCode.InvalidSetting);
            }

            Login( ).Wait( );
        }
        private ParseImageResponse ParseImages(string body, MultipartFileStreamProvider multiPartRequest, bool extractFirstImageAsProperty)
        {
            var firstImage = string.Empty;
            var bodyText   = Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m =>
            {
                var index = m.Groups[1].Value.TryConvertTo <int>();
                if (index)
                {
                    //get the file at this index
                    var file = multiPartRequest.FileData[index.Result];

                    var rndId = Guid.NewGuid().ToString("N");

                    using (var stream = File.OpenRead(file.LocalFileName))
                    {
                        var fileUrl = "articulate/" + rndId + "/" + file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\"");

                        _mediaFileSystem.AddFile(fileUrl, stream);

                        var result = string.Format("![{0}]({1})",
                                                   fileUrl,
                                                   fileUrl
                                                   );

                        if (extractFirstImageAsProperty && string.IsNullOrEmpty(firstImage))
                        {
                            firstImage = fileUrl;
                            //in this case, we've extracted the image, we don't want it to be displayed
                            // in the content too so don't return it.
                            return(string.Empty);
                        }

                        return(result);
                    }
                }

                return(m.Value);
            });

            return(new ParseImageResponse {
                BodyText = bodyText, FirstImage = firstImage
            });
        }
Exemple #18
0
        public async Task <UploadedDocumentResponse> AddFormatToDocument(
            AddFormatFromFileToDocumentModel model,
            IDictionary <string, object> customData = null)
        {
            using (var sourceStream = File.OpenRead(model.PathToFile))
            {
                using (var client = new HttpClient())
                {
                    using (
                        var content =
                            new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
                    {
                        var fileInfo = new FileInfo(model.PathToFile);
                        content.Add(
                            new StreamContent(sourceStream),
                            "stream",
                            fileInfo.Name
                            );

                        customData = customData ?? new Dictionary <String, Object>();
                        customData.Add(AddFormatToDocumentParameters.CreatedBy, model.CreatedById);
                        customData.Add(AddFormatToDocumentParameters.DocumentHandle, model.DocumentHandle);
                        customData.Add(AddFormatToDocumentParameters.JobId, model.JobId);
                        customData.Add(AddFormatToDocumentParameters.QueueName, model.QueueName);
                        customData.Add(AddFormatToDocumentParameters.Format, model.Format);

                        var stringContent = new StringContent(JsonConvert.SerializeObject(customData));
                        content.Add(stringContent, "custom-data");

                        var modelFormat = model.Format == null ? "null" : model.Format.ToString();
                        var endPoint    = new Uri(_documentStoreUri, Tenant + "/documents/addformat/" + modelFormat);

                        using (var message = await client.PostAsync(endPoint, content).ConfigureAwait(false))
                        {
                            var json = await message.Content.ReadAsStringAsync().ConfigureAwait(false);

                            message.EnsureSuccessStatusCode();
                            return(JsonConvert.DeserializeObject <UploadedDocumentResponse>(json));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Send Media or Document
        /// </summary>
        /// <param name="fileIdOrPath"></param>
        /// <param name="mediaType"></param>
        /// <param name="caption"></param>
        /// <param name="replyMarkup"></param>
        /// <param name="replyToMsgId"></param>
        protected async Task SendMediaDocumentAsync(
            string fileIdOrPath,
            MediaType mediaType,
            HtmlString caption       = null,
            IReplyMarkup replyMarkup = null,
            int replyToMsgId         = 0
            )
        {
            if (caption != null)
            {
                if (!caption.ToString().EndsWith(Environment.NewLine + Environment.NewLine))
                {
                    caption.Br();
                }

                caption = new HtmlString()
                          .Append(caption).Br()
                          .Code($"⏱ {TimeInit} s").Text(" | ").Code($"⌛ {TimeProc} s");
            }

            switch (mediaType)
            {
            case MediaType.LocalDocument:
                var fileName = Path.GetFileName(fileIdOrPath);
                await using (var fs = SystemFile.OpenRead(fileIdOrPath))
                {
                    var inputOnlineFile = new InputOnlineFile(fs, fileName);
                    // var inputThumb = new InputMedia(fs, fileName);

                    SentMessage = await Bot.SendDocumentAsync(
                        Chat.Id,
                        inputOnlineFile,
                        thumb : null,
                        caption?.ToString(),
                        parseMode : ParseMode.Html,
                        replyMarkup : replyMarkup,
                        replyToMessageId : replyToMsgId
                        );
                }

                break;
            }
        }
Exemple #20
0
        public async Task Should_Set_Webhook_With_SelfSigned_Cert()
        {
            await using (Stream stream = File.OpenRead(Constants.PathToFile.Certificate.PublicKey))
            {
                await BotClient.SetWebhookAsync(
                    url : "https://www.telegram.org/",
                    certificate : stream,
                    maxConnections : 3,
                    allowedUpdates : Array.Empty <UpdateType>() // send all types of updates
                    );
            }

            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Equal("https://www.telegram.org/", info.Url);
            Assert.True(info.HasCustomCertificate);
            Assert.Equal(3, info.MaxConnections);
            Assert.Null(info.AllowedUpdates);
        }
        public string Upload(string folderId, string localPath, Guid userId)
        {
            CoreContext.TenantManager.SetCurrentTenant(tenantId);
            if (!userId.Equals(Guid.Empty))
            {
                SecurityContext.AuthenticateMe(userId);
            }
            else
            {
                var tenant = CoreContext.TenantManager.GetTenant(tenantId);
                SecurityContext.AuthenticateMe(tenant.OwnerId);
            }

            using (var folderDao = GetFolderDao())
                using (var fileDao = GetFileDao())
                {
                    var folder = folderDao.GetFolder(folderId);
                    if (folder == null)
                    {
                        throw new FileNotFoundException("Folder not found.");
                    }
                    using (var source = IoFile.OpenRead(localPath))
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var file = fileDao.SaveFile(
                            new File
                        {
                            Title         = Path.GetFileName(localPath),
                            FolderID      = folder.ID,
                            ContentLength = source.Length
                        },
                            source);

                        return(Convert.ToString(file.ID));
                    }
                }
        }
Exemple #22
0
        static void CompressNew(string src, string dest)
        {
            using (FileStream streamDest = F.OpenWrite(dest))
            {
                using (Stream streamSnappy = IronSnappy.Snappy.OpenWriter(streamDest))
                {
                    using (FileStream streamSrc = F.OpenRead(src))
                    {
                        using (var time = new TimeMeasure())
                        {
                            streamSrc.CopyTo(streamSnappy);

                            TimeSpan duration = time.Elapsed;

                            Console.WriteLine($"new: {src} => {dest}. {duration} {new FileInfo(dest).Length}");
                        }
                    }
                }
            }
        }
Exemple #23
0
        /// <inheritdoc />
        public async Task <Stream> OpenAsync(FileAccessMode accessMode)
        {
            if (!this.Exists)
            {
                throw new StorageItemNotFoundException(this.Name, "Cannot open a file that does not exist.");
            }

            await TaskSchedulerAwaiter.NewTaskSchedulerAwaiter();

            switch (accessMode)
            {
            case FileAccessMode.Read:
                return(File.OpenRead(this.Path));

            case FileAccessMode.ReadWrite:
                return(File.Open(this.Path, FileMode.Open, FileAccess.ReadWrite));

            default:
                throw new StorageFileIOException(this.Name, "The file could not be opened.");
            }
        }
Exemple #24
0
/* ==> Stap 7 -> Detect faces and match them to Umbraco Members */
        private void MediaService_Saving(IMediaService sender, SaveEventArgs <IMedia> e)
        {
            FaceServiceClient faceServiceClient = new FaceServiceClient(_faceApiKey, _faceApiUrl);
            IMemberService    memberService     = ApplicationContext.Current.Services.MemberService;

            foreach (IMedia media in e.SavedEntities)
            {
                string relativeImagePath = ImagePathHelper.GetImageFilePath(media);
                string fullPath          = _fs.GetFullPath(relativeImagePath);

                using (Stream imageFileStream = File.OpenRead(fullPath))
                {
                    var faces = AsyncHelpers.RunSync(() =>
                                                     faceServiceClient.DetectAsync(imageFileStream));

                    if (faces.Any())
                    {
                        Guid[]           faceIds = faces.Select(a => a.FaceId).ToArray();
                        IdentifyResult[] results = AsyncHelpers.RunSync(() =>
                                                                        faceServiceClient.IdentifyAsync(_faceApiGroup, faceIds, 5));

                        var matchedPersons = new List <IMember>();

                        foreach (IdentifyResult identifyResult in results)
                        {
                            foreach (var candidate in identifyResult.Candidates)
                            {
                                IEnumerable <IMember> searchResult = memberService.GetMembersByPropertyValue("personId", candidate.PersonId.ToString());
                                matchedPersons.AddRange(searchResult);
                            }
                        }

                        if (matchedPersons.Any())
                        {
                            media.SetValue("persons", string.Join(",", matchedPersons.Select(a => a.GetUdi().ToString())));
                        }
                    }
                }
            }
        }
    unsafe void Start()
    {
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();

        var file = File.OpenRead(Application.streamingAssetsPath + "/data");

        SHA256 sha256 = new SHA256();

        SHA256.Initialize(&sha256);

        var buffer = new byte[64 * 1024];

        for (;;)
        {
            var n = file.Read(buffer, 0, buffer.Length);
            if (n == 0)
            {
                break;
            }

            fixed(byte *p = buffer)
            {
                SHA256.Update(&sha256, p, n);
            }
        }

        var hash = new NativeArray <byte>(32, Allocator.Temp);

        SHA256.Final(&sha256, hash);

        stopWatch.Stop();

        TimeSpan ts = stopWatch.Elapsed;

        Debug.Log($"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}");
        Debug.Log($"{hash[0]:X2}{hash[1]:X2}{hash[2]:X2}{hash[3]:X2}{hash[4]:X2}{hash[5]:X2}{hash[6]:X2}{hash[7]:X2}{hash[8]:X2}{hash[9]:X2}{hash[10]:X2}{hash[11]:X2}{hash[12]:X2}{hash[13]:X2}{hash[14]:X2}{hash[15]:X2}{hash[16]:X2}{hash[17]:X2}{hash[18]:X2}{hash[19]:X2}{hash[20]:X2}{hash[21]:X2}{hash[22]:X2}{hash[23]:X2}{hash[24]:X2}{hash[25]:X2}{hash[26]:X2}{hash[27]:X2}{hash[28]:X2}{hash[29]:X2}{hash[30]:X2}{hash[31]:X2}");
    }
        private static ParseImageResponse ParseImages(string body, MultipartFileStreamProvider multiPartRequest)
        {
            var firstImage = string.Empty;
            var bodyText   = Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m =>
            {
                var index = m.Groups[1].Value.TryConvertTo <int>();
                if (index)
                {
                    //get the file at this index
                    var file = multiPartRequest.FileData[index.Result];

                    var rndId = Guid.NewGuid().ToString("N");

                    using (var stream = File.OpenRead(file.LocalFileName))
                    {
                        var savedFile = UmbracoMediaFile.Save(stream, "articulate/" + rndId + "/" +
                                                              file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\""));

                        var result = string.Format("![{0}]({1})",
                                                   savedFile.Url,
                                                   savedFile.Url
                                                   );

                        if (string.IsNullOrEmpty(firstImage))
                        {
                            firstImage = savedFile.Url;
                        }

                        return(result);
                    }
                }

                return(m.Value);
            });

            return(new ParseImageResponse {
                BodyText = bodyText, FirstImage = firstImage
            });
        }
Exemple #27
0
        private DataSet ReadCsv(string name)
        {
            DataSet result;

            using (Stream fs = F.OpenRead(GetDataFilePath(name)))
            {
                var reader = new CsvReader(fs, Encoding.UTF8);

                //header
                string[] columnNames = reader.ReadNextRow();
                result = new DataSet(new Schema(columnNames.Select(n => new SchemaElement(n, typeof(string)))));

                //values
                string[] values;
                while ((values = reader.ReadNextRow()) != null)
                {
                    var row = new Row(values);
                    result.Add(row);
                }
            }
            return(result);
        }
Exemple #28
0
        /// <summary>
        /// Calculates the MD5 sum.
        /// </summary>
        /// <param name="filepath">The filepath.</param>
        /// <param name="upperCase">if set to <c>true</c> if need to convert to [upper case].</param>
        /// <returns>MD5 sun in string format</returns>
        public static string Calc_md5(string filepath, bool upperCase)
        {
            using (var md5 = MD5.Create())
            {
                if (!File.Exists(filepath))
                {
                    return("-1");
                }
                using (var stream = File.OpenRead(filepath))
                {
                    var bytes = md5.ComputeHash(stream);

                    StringBuilder result = new StringBuilder(bytes.Length * 2);

                    foreach (var t in bytes)
                    {
                        result.Append(t.ToString(upperCase ? "X2" : "x2"));
                    }
                    return(result.ToString());
                }
            }
        }
Exemple #29
0
    private string?ProcessFile(ContentPropertyFile file, Guid cuid, Guid puid)
    {
        // process the file
        // no file, invalid file, reject change
        if (UploadFileTypeValidator.IsValidFileExtension(file.FileName, _contentSettings) == false)
        {
            return(null);
        }

        // get the filepath
        // in case we are using the old path scheme, try to re-use numbers (bah...)
        var filepath = _mediaFileManager.GetMediaPath(file.FileName, cuid, puid); // fs-relative path

        using (FileStream filestream = File.OpenRead(file.TempFilePath))
        {
            // TODO: Here it would make sense to do the auto-fill properties stuff but the API doesn't allow us to do that right
            // since we'd need to be able to return values for other properties from these methods
            _mediaFileManager.FileSystem.AddFile(filepath, filestream, true); // must overwrite!
        }

        return(filepath);
    }
Exemple #30
0
        public void OpenXmlFileMapTest(FarmSimulatorVersion version, string fileName)
        {
            var mapsPath = GamePaths.GetGameMapsPath(version);

            if (mapsPath == null)
            {
                Assert.Inconclusive("Maps path by \"{0}\" not found.", version);
            }

            var mapFilePath = Path.Combine(mapsPath, fileName);

            if (!File.Exists(mapFilePath))
            {
                Assert.Inconclusive("Map file \"{0}\" by \"{1}\" not found.", fileName, version);
            }

            using (var stream = File.OpenRead(mapFilePath))
            {
                var mapFile = MapFile.Serializer.Deserialize(stream) as MapFile;
                Assert.IsNotNull(mapFile);
            }
        }
        private void TestSameCore(File memTempFile, File localTempFile, FileMode mode, FileAccess access, FileShare share)
        {
            Stream memStream = null, localStream = null;
            Exception memException = null, localException = null;
            try
            {
                memStream = memTempFile.Open(mode, access, share);
            }
            catch (Exception e)
            {
                memException = e;
            }
            try
            {
                localStream = localTempFile.Open(mode, access, share);
            }
            catch (Exception e)
            {
                localException = e;
            }
            if (memException != null || localException != null)
            {
                if (memStream != null) memStream.Dispose();
                if (localStream != null) localStream.Dispose();

                var anyException = (memException ?? localException).GetType();

                Assert.That(memException, Is.InstanceOf(anyException), string.Format("In-Memory ex was {0}, but file was: {1}",
                    memException != null ? memException.ToString() : "NULL",
                    localException != null ? localException.ToString() : "NULL"));

                Assert.That(localException, Is.InstanceOf(anyException), string.Format("Local file ex was {0}, but in mem was: {1}.",
                    localException != null ? localException.ToString() : "NULL",
                    memException != null ? memException.ToString() : "NULL"));

                if (!(memException.GetType() == anyException && localException.GetType() == anyException))
                    Console.WriteLine("Memory exception: " + (memException != null ? memException.GetType().Name : null) +
                                      " Local exception: " + (localException != null ? localException.GetType().Name : null));
                return;
            }
            if (memStream.CanWrite)
                memStream.WriteByte(99);
            if (localStream.CanWrite)
                localStream.WriteByte(99);
            memStream.Dispose();
            localStream.Dispose();

            using (memStream = memTempFile.OpenRead())
            using (localStream = localTempFile.OpenRead())
            {
                memStream.ReadToEnd().ShouldBe(localStream.ReadToEnd());
                localStream.Close();
                memStream.Close();
            }
        }