コード例 #1
0
        async Task <UserFile> IUserFileManager.WriteAsync(string userId, string projectName, string filePath, Stream data, string contentType)
        {
            // Get the base files directory.
            string baseDir = GetBaseDir(userId, projectName);

            using (await LockFile.LockAsync(GetLockFile(userId, projectName)))
            {
                List <UserFile> fileMetaList = null;
                try
                {
                    fileMetaList = await GetUserFilesAsync(userId, projectName);
                }
                catch (Exception e)
                {
                    await AsyncIO.WriteAllTextAsync($"{baseDir}\\filemeta.json", "[]", Encoding.UTF8);

                    fileMetaList = new List <UserFile>();
                }

                if (fileMetaList.TryFind(x => x.VirtualPath == filePath, out var _))
                {
                    return(await OverwriteFileAsync(baseDir, fileMetaList, filePath, data, contentType));
                }
                else
                {
                    return(await WriteNewFileAsync(baseDir, fileMetaList, filePath, data, contentType));
                }
            }
        }
コード例 #2
0
        private async Task <List <UserFile> > GetUserFilesAsync(string userId, string projectName)
        {
            string fileMetaJson = await AsyncIO.ReadAllTextAsync($"{GetBaseDir(userId, projectName)}\\filemeta.json", Encoding.UTF8);

            // Get the file meta list.
            return(JsonConvert.DeserializeObject <List <UserFile> >(fileMetaJson));
        }
コード例 #3
0
        private async Task ProduceStart(bool flushHeaders)
        {
            Debug.Assert(_hasResponseStarted == false);

            _hasResponseStarted = true;

            SetResponseHeaders();

            EnsureIOInitialized();
            var canHaveNonEmptyBody = StatusCodeCanHaveBody();

            if (flushHeaders)
            {
                try
                {
                    await AsyncIO.FlushAsync(canHaveNonEmptyBody);
                }
                // Client might be disconnected at this point
                // don't leak the exception
                catch (ConnectionResetException)
                {
                    AbortIO(clientDisconnect: true);
                }
            }

            if (!canHaveNonEmptyBody)
            {
                _bodyOutput.Dispose();
            }
            else
            {
                _writeBodyTask = WriteBody(!flushHeaders);
            }
        }
コード例 #4
0
        private async Task <UserFile> WriteNewFileAsync(string baseDir, List <UserFile> fileMetaList, string filePath, Stream data, string contentType)
        {
            // Generate a new file name.
            string realFileName = GenerateFilename();

            try
            {
                using (FileStream fs = File.Create($"{baseDir}\\{realFileName}"))
                {
                    await data.CopyToAsync(fs);
                }
            }
            catch (Exception e)
            {
                File.Delete($"{baseDir}{realFileName}");
                throw e;
            }

            var file = new UserFile
                       (
                virtualPath: filePath,
                localPath: realFileName,
                fileSize: data.Position,
                contentType: contentType
                       );

            // Add the file to the meta.
            fileMetaList.Add(file);

            // Write the new file meta back to the file.
            await AsyncIO.WriteAllTextAsync($"{baseDir}\\filemeta.json", JsonConvert.SerializeObject(fileMetaList), Encoding.UTF8);

            return(file);
        }
コード例 #5
0
        /**
         * Launch the file transformation process (webpack).
         */
        private async Task TransformFilesAsync(string pwd)
        {
            IDictionary <string, string> dependencies = await GetPackageDependenciesAsync(pwd);

            IList <string> entries = new List <string>();

            IList <string> switchCases = new List <string>();

            foreach (var module in dependencies.Keys)
            {
                string relativeEntry = await GetModuleEntryAsync(pwd, module);

                string moduleEntry = module + "/" + relativeEntry;
                switchCases.Add($"case '{module}': return require('{moduleEntry}');");
            }

            string switchBody   = $"{string.Join("\n", switchCases)} default: throw new Error('Unknown module \"' + moduleId + '\"!'); ";
            string moduleSwitch = $"switch(moduleId) {{ {switchBody} }}";
            string js           = $"self[\"__cwuser_require__\"] = function(moduleId) {{ {moduleSwitch} }}";

            var wbIndex = $"{pwd}\\index.js";
            await AsyncIO.WriteAllTextAsync(wbIndex, js, Encoding.UTF8);

            var     cmd  = $"{_webpackPath} index.js bundle.js";
            Process proc = StartProcess(cmd, pwd);

            await WaitForExitAsync(proc);
        }
コード例 #6
0
        private async Task ProduceStart(bool flushHeaders)
        {
            Debug.Assert(_hasResponseStarted == false);

            _hasResponseStarted = true;

            SetResponseHeaders();

            EnsureIOInitialized();

            if (flushHeaders)
            {
                try
                {
                    await AsyncIO.FlushAsync();
                }
                // Client might be disconnected at this point
                // don't leak the exception
                catch (IOException)
                {
                    // ignore
                }
            }

            _writeBodyTask = WriteBody(!flushHeaders);
        }
コード例 #7
0
ファイル: OpcGroup.cs プロジェクト: simple555a/OpcDaClient
        public int[] AsyncWrite(int connection, int[] serverHandles, object[] values, out int transactionId)
        {
            var ppErrors = IntPtr.Zero;

            AsyncIO.Write(connection, serverHandles.Length, serverHandles, values, out transactionId, out ppErrors);
            return(ComUtils.GetInt32s(ref ppErrors, serverHandles.Length, true));
        }
コード例 #8
0
        async Task IUserFileManager.RenameAsync(string userId, string projectName, string oldFilePath, string newFilePath)
        {
            // Get the base files directory.
            string baseDir = GetBaseDir(userId, projectName);

            using (await LockFile.LockAsync(GetLockFile(userId, projectName)))
            {
                string fileMetaJson = null;
                try
                {
                    // Read the metadata file.
                    fileMetaJson = await AsyncIO.ReadAllTextAsync($"{baseDir}\\filemeta.json", Encoding.UTF8);
                }
                catch (FileNotFoundException e)
                {
                    ThrowNotFound(projectName, oldFilePath);
                }
                // Get the file meta dict.
                List <UserFile> fileMetaList = JsonConvert.DeserializeObject <List <UserFile> >(fileMetaJson);
                if (fileMetaList.TryFind(x => x.VirtualPath == oldFilePath, out var fileMeta))
                {
                    // Update the value in the list.
                    fileMetaList.Remove(fileMeta);
                    fileMetaList.Add(fileMeta.WithVirtualPath(newFilePath));
                }
                // Write the new file meta back to the file.
                await AsyncIO.WriteAllTextAsync($"{baseDir}\\filemeta.json", JsonConvert.SerializeObject(fileMetaList), Encoding.UTF8);
            }
        }
コード例 #9
0
        // Constructor
        public UI161()
        {
            InitializeComponent();

            // Instantiate Modbus printer and register for log events
            MB           = new Modbus(this);
            MB.Log      += Modbus_Log;
            MB.Complete += P_Complete;

            // Instantiate the user pattern
            up      = new UserPattern(this, MB, tabLogo);
            up.Log += Modbus_Log;

            // Start AsyncIO
            asyncIO           = new AsyncIO(this, MB);
            asyncIO.Log      += Modbus_Log;
            asyncIO.Complete += AsyncIO_Complete;

            doSubs      = new DoSubs(this, MB, grpMain);
            doSubs.Subs = new Substitution[2];
            //if (global.DefaultSubRules != null) {
            //   doSubs.Subs[(int)DoSubs.Src.global] = global.DefaultSubRules.Copy();
            //}
            //if (parent.msg != null && parent.msg.Substitution != null) {
            //   doSubs.Subs[(int)DoSubs.Src.msg] = parent.msg.Substitution.Copy();
            //}
            doSubs.BuildControls(prop);
        }
コード例 #10
0
        /// <summary>
        /// Loads the bot token from disk.
        /// </summary>
        /// <exception cref="FileNotFoundException">Thrown if the bot token file can't be found.</exception>
        /// <exception cref="InvalidDataException">Thrown if no token exists in the file.</exception>
        /// <returns>A retrieval result which may or may not have succeeded.</returns>
        public async Task <RetrieveEntityResult <string> > GetBotTokenAsync()
        {
            var tokenPath = UPath.Combine(UPath.Root, "Discord", "bot.token");

            if (!this.FileSystem.FileExists(tokenPath))
            {
                return(RetrieveEntityResult <string> .FromError("The token file could not be found."));
            }

            var getTokenStream = OpenLocalStream(tokenPath);

            if (!getTokenStream.IsSuccess)
            {
                return(RetrieveEntityResult <string> .FromError("The token file could not be opened."));
            }

            await using var tokenStream = getTokenStream.Entity;
            var token = await AsyncIO.ReadAllTextAsync(tokenStream);

            if (string.IsNullOrEmpty(token))
            {
                return(RetrieveEntityResult <string> .FromError("The token file did not contain a valid token."));
            }

            return(RetrieveEntityResult <string> .FromSuccess(token));
        }
コード例 #11
0
ファイル: OpcGroup.cs プロジェクト: simple555a/OpcDaClient
        public int[] AsyncRead(int connection, OpcDataSource source, int[] serverHandles, out int transactionId)
        {
            var ppErrors = IntPtr.Zero;

            AsyncIO.Read(connection, (OPCDATASOURCE)source, serverHandles.Length, serverHandles, out transactionId, out ppErrors);
            return(ComUtils.GetInt32s(ref ppErrors, serverHandles.Length, true));
        }
コード例 #12
0
        private async Task WriteBody(bool flush = false)
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    var result = await _bodyOutput.Reader.ReadAsync();

                    var buffer = result.Buffer;
                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            await AsyncIO.WriteAsync(buffer);
                        }

                        // if request is done no need to flush, http.sys would do it for us
                        if (result.IsCompleted)
                        {
                            // When is the reader completed? Is it always after the request pipeline exits? Or can CompleteAsync make it complete early?
                            if (HasTrailers)
                            {
                                SetResponseTrailers();
                            }

                            break;
                        }

                        flush |= result.IsCanceled;

                        if (flush)
                        {
                            await AsyncIO.FlushAsync(moreData : true);

                            flush = false;
                        }
                    }
                    finally
                    {
                        _bodyOutput.Reader.AdvanceTo(buffer.End);
                    }
                }
            }
            // We want to swallow IO exception and allow app to finish writing
            catch (ConnectionResetException)
            {
                AbortIO(clientDisconnect: true);
            }
            catch (Exception ex)
            {
                error = ex;
                Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
            }
            finally
            {
                _bodyOutput.Reader.Complete(error);
            }
        }
コード例 #13
0
        /// <summary>
        /// Loads the sass from disk.
        /// </summary>
        private async Task <DetermineConditionResult> LoadSassAsync()
        {
            var sassPath     = UPath.Combine(UPath.Root, "Sass", "sass.txt");
            var sassNSFWPath = UPath.Combine(UPath.Root, "Sass", "sass-nsfw.txt");

            var getSassStream = _content.OpenLocalStream(sassPath);

            if (getSassStream.IsSuccess)
            {
                await using var sassStream = getSassStream.Entity;
                _sass = (await AsyncIO.ReadAllLinesAsync(sassStream)).ToList();
            }
            else
            {
                return(DetermineConditionResult.FromError(getSassStream));
            }

            var getNSFWSassStream = _content.OpenLocalStream(sassNSFWPath);

            if (getNSFWSassStream.IsSuccess)
            {
                await using var nsfwSassStream = getNSFWSassStream.Entity;
                _sassNSFW = (await AsyncIO.ReadAllLinesAsync(nsfwSassStream)).ToList();
            }
            else
            {
                return(DetermineConditionResult.FromError(getNSFWSassStream));
            }

            _isSassLoaded = true;
            return(DetermineConditionResult.FromSuccess());
        }
コード例 #14
0
        /// <summary>
        /// Loads the sass from disk.
        /// </summary>
        private async Task LoadSassAsync()
        {
            var sassPath     = UPath.Combine(UPath.Root, "Sass", "sass.txt");
            var sassNSFWPath = UPath.Combine(UPath.Root, "Sass", "sass-nsfw.txt");

            var getSassStream = OpenLocalStream(sassPath);

            if (getSassStream.IsSuccess)
            {
                using (var sassStream = getSassStream.Entity)
                {
                    _sass = (await AsyncIO.ReadAllLinesAsync(sassStream)).ToList();
                }
            }

            var getNSFWSassStream = OpenLocalStream(sassNSFWPath);

            if (getNSFWSassStream.IsSuccess)
            {
                using (var nsfwSassStream = getNSFWSassStream.Entity)
                {
                    _sassNSFW = (await AsyncIO.ReadAllLinesAsync(nsfwSassStream)).ToList();
                }
            }
        }
コード例 #15
0
        public async Task <string> GetChamp2ndLane(string champName)
        {
            try {
                var jsonString = await AsyncIO.ReadFileAsync("cache/champMatchUps.json");

                var champMatchUps = JsonConvert.DeserializeObject <Dictionary <string, ChampMatchups> >(jsonString);
                var lanes         = champMatchUps[champName];
                //get the max value
                int    FirstMaxGames   = 0;
                string FirstMaxLane    = "";
                string secoundMaxLane  = "";
                int    secoundMaxGames = 0;
                foreach (var lane in lanes.GetType().GetFields())
                {
                    var gamesPlayed = (int)lanes.GetType().GetField(lane.Name).GetValue(lanes);
                    if (gamesPlayed > FirstMaxGames)
                    {
                        FirstMaxGames = gamesPlayed;
                        FirstMaxLane  = lane.Name;
                    }

                    if (gamesPlayed > secoundMaxGames && gamesPlayed < FirstMaxGames)
                    {
                        secoundMaxGames = gamesPlayed;
                        secoundMaxLane  = lane.Name;
                    }
                }
                return(secoundMaxLane);
            } catch (Exception error) {
                throw error;
            }
        }
コード例 #16
0
        public ILearner GetLearner(int result)
        {
            ILearner learner = null;

            switch (result)
            {
            case 1:
                learner = new DownloadWinForm();
                break;

            case 2:
                learner = new Threads();
                break;

            case 3:
                learner = new ThreadSafety();
                break;

            case 4:
                learner = new EasyPools();
                break;

            case 5:
                learner = new SignalManualReset();
                break;

            case 6:
                learner = new AsyncIO();
                break;

            case 7:
                learner = new TPLDemo();
                break;

            case 8:
                learner = new AsyncAndAwait();
                break;

            case 9:
                learner = new ConcurrentQueueDemo();
                break;

            case 10:
                learner = new ConcurrentDictionaryDemo();
                break;

            case 11:
                learner = new ProduceConsumer();
                break;

            default:
                learner = new DownloadWinForm();
                break;
            }
            return(learner);
        }
コード例 #17
0
        private async Task WriteBody(bool flush = false)
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    var result = await _bodyOutput.Reader.ReadAsync();

                    var buffer = result.Buffer;

                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            await AsyncIO.WriteAsync(buffer);
                        }

                        // if request is done no need to flush, http.sys would do it for us
                        if (result.IsCompleted)
                        {
                            break;
                        }

                        flush = flush | result.IsCanceled;

                        if (flush)
                        {
                            await AsyncIO.FlushAsync();

                            flush = false;
                        }
                    }
                    finally
                    {
                        _bodyOutput.Reader.AdvanceTo(buffer.End);
                    }
                }
            }
            // We want to swallow IO exception and allow app to finish writing
            catch (ConnectionResetException)
            {
                ConnectionReset();
            }
            catch (Exception ex)
            {
                error = ex;
                Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
            }
            finally
            {
                _bodyOutput.Reader.Complete(error);
            }
        }
コード例 #18
0
        public static async Task <RetrieveEntityResult <IReadOnlyList <Species> > > DiscoverBundledSpeciesAsync
        (
            [NotNull] this ContentService @this
        )
        {
            const string speciesFilename = "Species.yml";

            var deser = new DeserializerBuilder()
                        .WithNodeDeserializer(i => new ValidatingNodeDeserializer(i), s => s.InsteadOf <ObjectNodeDeserializer>())
                        .WithNamingConvention(new UnderscoredNamingConvention())
                        .Build();

            var species        = new List <Species>();
            var speciesFolders = @this.FileSystem.EnumerateDirectories
                                 (
                BaseTransformationSpeciesPath
                                 );

            foreach (var directory in speciesFolders)
            {
                var speciesFilePath = UPath.Combine(directory, speciesFilename);
                if ([email protected](speciesFilePath))
                {
                    continue;
                }

                var openStreamResult = @this.OpenLocalStream(speciesFilePath);
                if (!openStreamResult.IsSuccess)
                {
                    return(RetrieveEntityResult <IReadOnlyList <Species> > .FromError(openStreamResult));
                }

                using (var speciesFile = openStreamResult.Entity)
                {
                    var content = await AsyncIO.ReadAllTextAsync(speciesFile, Encoding.UTF8);

                    try
                    {
                        species.Add(deser.Deserialize <Species>(content));
                    }
                    catch (YamlException yex)
                    {
                        if (yex.InnerException is SerializationException sex)
                        {
                            return(RetrieveEntityResult <IReadOnlyList <Species> > .FromError(sex));
                        }

                        return(RetrieveEntityResult <IReadOnlyList <Species> > .FromError(yex));
                    }
                }
            }

            return(RetrieveEntityResult <IReadOnlyList <Species> > .FromSuccess(species));
        }
コード例 #19
0
    public static async Task <Result <IReadOnlyList <Transformation> > > DiscoverBundledTransformationsAsync
    (
        this ContentService @this,
        TransformationService transformation,
        Species species
    )
    {
        const string speciesFilename = "Species.yml";

        var speciesDir          = GetSpeciesDirectory(species);
        var transformationFiles = @this.FileSystem.EnumerateFiles(speciesDir)
                                  .Where(p => !p.ToString().EndsWith(speciesFilename));

        var transformations = new List <Transformation>();
        var deserializer    = new DeserializerBuilder()
                              .WithTypeConverter(new ColourYamlConverter())
                              .WithTypeConverter(new SpeciesYamlConverter(transformation))
                              .WithTypeConverter(new EnumYamlConverter <Pattern>())
                              .WithTypeConverter(new NullableEnumYamlConverter <Pattern>())
                              .WithNodeDeserializer(i => new ValidatingNodeDeserializer(i), s => s.InsteadOf <ObjectNodeDeserializer>())
                              .WithNamingConvention(UnderscoredNamingConvention.Instance)
                              .Build();

        foreach (var transformationFile in transformationFiles)
        {
            var getTransformationFileStream = @this.OpenLocalStream(transformationFile);
            if (!getTransformationFileStream.IsSuccess)
            {
                continue;
            }

            string content;
            await using (var transformationFileStream = getTransformationFileStream.Entity)
            {
                content = await AsyncIO.ReadAllTextAsync(transformationFileStream);
            }

            try
            {
                transformations.Add(deserializer.Deserialize <Transformation>(content));
            }
            catch (YamlException yex)
            {
                if (yex.InnerException is SerializationException sex)
                {
                    return(Result <IReadOnlyList <Transformation> > .FromError(sex));
                }

                return(Result <IReadOnlyList <Transformation> > .FromError(yex));
            }
        }

        return(Result <IReadOnlyList <Transformation> > .FromSuccess(transformations));
    }
コード例 #20
0
        private async Task ReadBody()
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    var memory = _bodyInputPipe.Writer.GetMemory();

                    var read = await AsyncIO.ReadAsync(memory);

                    // End of body
                    if (read == 0)
                    {
                        break;
                    }

                    // Read was not canceled because of incoming write or IO stopping
                    if (read != -1)
                    {
                        _consumedBytes += read;
                        _bodyInputPipe.Writer.Advance(read);
                    }

                    if (_consumedBytes > MaxRequestBodySize)
                    {
                        IISBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge);
                    }

                    var result = await _bodyInputPipe.Writer.FlushAsync();

                    if (result.IsCompleted || result.IsCanceled)
                    {
                        break;
                    }
                }
            }
            catch (ConnectionResetException ex)
            {
                AbortIO(clientDisconnect: true);
                error = ex;
            }
            catch (Exception ex)
            {
                error = ex;
                Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
            }
            finally
            {
                _bodyInputPipe.Writer.Complete(error);
            }
        }
コード例 #21
0
 public GameSettings(Arkanoid arkanoidGame)
 {
     ArkanoidGame = arkanoidGame;
     if (AsyncIO.DoesFileExistAsync(ApplicationData.Current.RoamingFolder, "Unlocks"))
     {
         _result = Load <Dictionary <string, WadScore> >(ApplicationData.Current.RoamingFolder, "Unlocks");
     }
     else
     {
         _unlocks = new Dictionary <string, WadScore>();
         Save();
     }
 }
コード例 #22
0
        /**
         * Initializes the project if it has not already been initialized.
         */
        private async Task TryInitProjectAsync(string pwd, string userId, string projectName)
        {
            if (!Directory.Exists(pwd))
            {
                using (await LockFile.LockAsync(GetLockFile(userId, projectName)))
                {
                    await TryInstallToolsAsync();

                    Directory.CreateDirectory(pwd);
                    await AsyncIO.WriteAllTextAsync(pwd + "\\package.json", "{\"name\":\"creo-web-" + userId + "-" + projectName + "\",\"version\":\"1.0.0\",\"dependencies\":{}}", Encoding.UTF8);
                }
            }
        }
コード例 #23
0
 public GamePersistance(BaseGame game)
 {
     Game = game;
     if (AsyncIO.DoesFileExistAsync(ApplicationData.Current.RoamingFolder, "Data"))
     {
         _result = Load <T>(ApplicationData.Current.RoamingFolder, "Data");
     }
     else
     {
         _data = new T();
         Save();
     }
 }
コード例 #24
0
        private async Task WriteBody(bool flush = false)
        {
            try
            {
                while (true)
                {
                    var result = await _bodyOutput.Reader.ReadAsync();

                    var buffer = result.Buffer;

                    try
                    {
                        if (!buffer.IsEmpty)
                        {
                            await AsyncIO.WriteAsync(buffer);
                        }

                        // if request is done no need to flush, http.sys would do it for us
                        if (result.IsCompleted)
                        {
                            break;
                        }

                        flush = flush | result.IsCanceled;

                        if (flush)
                        {
                            await AsyncIO.FlushAsync();

                            flush = false;
                        }
                    }
                    finally
                    {
                        _bodyOutput.Reader.AdvanceTo(buffer.End);
                    }
                }
            }
            // We want to swallow IO exception and allow app to finish writing
            catch (Exception ex)
            {
                if (!(ex is IOException))
                {
                    _bodyOutput.Reader.Complete(ex);
                }
            }
            finally
            {
                _bodyOutput.Reader.Complete();
            }
        }
コード例 #25
0
        public Binding()
        {
            Task.Run(() => AsyncIO.CreateDirectoryAsync(deploymentAppFolder)).GetAwaiter().GetResult();
            var appsettingsFilePath = Path.Combine(deploymentAppFolder, "appsettings.json");

            _appsettingsFilePath = appsettingsFilePath;
            if (!File.Exists(appsettingsFilePath))
            {
                CreateSettingsFile(appsettingsFilePath);
            }
            var json = File.ReadAllText(appsettingsFilePath);

            Config = JsonConvert.DeserializeObject <Config>(json);
        }
コード例 #26
0
        /**
         * Get a map of the project's dependencies.
         */
        private async Task <IDictionary <string, string> > GetPackageDependenciesAsync(string pwd)
        {
            var packageJsonPath = $"{pwd}\\package.json";

            if (!File.Exists(packageJsonPath))
            {
                return(new Dictionary <string, string>());
            }
            else
            {
                var package = JObject.Parse(await AsyncIO.ReadAllTextAsync(packageJsonPath, Encoding.UTF8));
                var deps    = package["dependencies"];
                var dict    = JsonConvert.DeserializeObject <Dictionary <string, string> >(deps.ToString());
                return(dict);
            }
        }
コード例 #27
0
        private async Task ReadBody()
        {
            Exception error = null;

            try
            {
                while (true)
                {
                    var memory = _bodyInputPipe.Writer.GetMemory();

                    var read = await AsyncIO.ReadAsync(memory);

                    // End of body
                    if (read == 0)
                    {
                        break;
                    }

                    // Read was not canceled because of incoming write or IO stopping
                    if (read != -1)
                    {
                        _bodyInputPipe.Writer.Advance(read);
                    }

                    var result = await _bodyInputPipe.Writer.FlushAsync();

                    if (result.IsCompleted || result.IsCanceled)
                    {
                        break;
                    }
                }
            }
            catch (ConnectionResetException ex)
            {
                ConnectionReset();
                error = ex;
            }
            catch (Exception ex)
            {
                error = ex;
                Log.UnexpectedError(_logger, nameof(IISHttpContext), ex);
            }
            finally
            {
                _bodyInputPipe.Writer.Complete(error);
            }
        }
コード例 #28
0
ファイル: SiteController.cs プロジェクト: veselink1/CreoWeb
        public async Task <object> AddSite([FromBody] Site site)
        {
            var email = HttpContext.User.Claims.First().Value;
            var user  = _context.User.First(x => x.Email == email);

            if (_defaultSiteResources == null)
            {
                _defaultSiteResources = await AsyncIO.ReadAllTextAsync(Directory.GetCurrentDirectory() + @"\StaticData\Defaults\global-res.json", Encoding.UTF8);
            }
            if (site.Favicon.Length > 46600)
            {
                site.Favicon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTM0A1t6AAAKIklEQVRYR9VXeVDTZxpm263buvVCEJArQIBwJNxX7hASIOFGQW4BRVBQEESB1YAQICAIAoUICJZDBRQth7VrtVXa9axtp7WXSw+3bseubbfnbLU++/4wHaeztms7+88+M88wk0m+53nf7/ne78Po/wqNJ57+o6g2RhmyS12u6BT1hnVKDqv16hFxfWK7jaysYLm4wMvISPOI4ev/OyjrUj2k1Wl9cX1JX645HYuEqVCoRgVQjNlh5VElQqorwYnrgVNkO3gZ2z5IHo6uSRlYa2H4+W8HNzlvSXSfsj/lpPfd7HMByLnsg7VXfFDwuhhZz6dC1V2C2OeckHOOD7+CDvht1JGR3ZDVJkG1n/eNuku9XX9J/5hhuV8HXlaaV8R+wWzqGS7S/uKO7PMSxB/YhuSpUuRdTEfuxRTIG4eQccEXqw4XwivvEJTNxeCsaoZT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fhPfCfTWJp1EXEkk8pg2O6mbYSMoPGyT/E9bCwqK5Ligq4aDSgpddjrABR4i7rOcmmZfWBG6aRXAuf3KO3Kol8KtzJhPr6SasQEB5DbjrqGoKnnsmI95N4k/BKXYP2BFNsAupvm0VuIFrkHsAJJrfUxYuMjPBnjkRFMigimTaY2v4N5mBqzGG89YFsC+cT3wCnLIF9NkS+O8yg7CDRux+B0i1+VR5D1xT9OAktFPlLbROIx3xOtiISuoNSj8Pq8D1bBvJtltzgSQTjpFaSFsC7nWgbilcyheCXcwYmD9ngFdFt2WDGSR6a4S0RVDrO+ZeRM7xrXCMaqJO6mgdLbV+6xk2u+APBplfho1wo4+tpOwzxoSdcidcEqrIhAxBnebwbl4Kt6pFcKlYCPfKxfBtNAV/jwXkfbbgl22i8LbQKWqiljfQI6SWQlcNCvibC01d2bQ08yT73ZzIf4OVuIhrKy2/ZkcLMFVw4um53e0Bvt4cfq2m8G4wge8uEm+1hKzDC8q9/mRUS+2upxBrqepqsOQaWPitPffoE4ujackgoiPxSeLDmVjAkS+1DMzrs5NX3nEIq4e8yxcivRUEncvBb7eAqMMGfE0EnCK0cFTVkOhOCnAV7IJ3wFpc+qWxs6qdlokiRhDDiYyJZcSH/u+JmdcmCyw9VVTJqGC7+p8hPS6Qd9tD2hwEXvpGSraGKp1774G50i0Fmz42cY/rf+TxhQn0WxUxlCgn/voOGMCYYH5kZjRvnrOlrySVHatusPRfc9DCP2eKjE2Ze2cOmbjG6uab89LoeyIin+hPZB6gLkRb4lLiw2fgAWDaxtzhzCKMoUVEY6IpkWnrjzQhLiEuJM4nMslnivjNwj8HZsFf4kPAyOjfzQbaVlWapK4AAAAASUVORK5CYII=";
            }
            site.UserID       = user.ID;
            site.IsPublic     = false;
            site.MainPage     = 0;
            site.Resources    = _defaultSiteResources;
            site.Contributors = "{}";
            _context.Site.Add(site);
            _context.SaveChanges();
            site = _context.Site.OrderByDescending(x => x.ID).First(x => x.UserID == user.ID);
            Component component = new Component();

            component.ComponentText = "{}";
            component.SiteID        = site.ID;
            component.Name          = "HomePage";
            component.IsPage        = true;
            component.IsPrefab      = false;
            component.Screenshot    = "";
            component.CreationDate  = DateTime.Now;
            component.Creator       = user.ID;
            component.LastEdited    = DateTime.Now;
            component.LastEditedBy  = user.ID;
            component.Description   = "The default homepage.";
            component.AccessLevel   = 0;
            component.Path          = "/";
            component.Resources     = "{}";
            _context.Component.Add(component);
            _context.SaveChanges();
            component     = _context.Component.OrderByDescending(x => x.ID).First(x => x.SiteID == site.ID);
            site.MainPage = component.ID;
            _context.Site.Update(site);
            _context.SaveChanges();
            var u = new { ID = user.ID, username = user.Username };

            return(new { Success = true, ID = site.ID, Size = new SitePartial(site).size, Main = new { ID = component.ID, SiteID = component.SiteID, ComponentText = component.ComponentText, Size = new ComponentPartial(component).size, IsPage = component.IsPage, IsPrefab = component.IsPrefab, Name = component.Name, Screenshot = component.Screenshot, CreationDate = component.CreationDate, Creator = u, LastEdited = component.LastEdited, LastEditedBy = u, Resources = component.Resources, Description = component.Description, AccessLevel = component.AccessLevel, Path = component.Path } });
        }
コード例 #29
0
ファイル: Fonts.cs プロジェクト: pixelwhipped/MiniGolfMayhem
        public static void LoadContent(ContentManager content)
        {
            try
            {
                var fontFilePath    = "Content\\Fonts\\Font2o.fnt";
                var fontFile        = FontLoader.Load(AsyncIO.GetContentStream(fontFilePath));
                var fontTexture     = content.Load <Texture2D>("Fonts/font2o_0");
                var fontGreyTexture = content.Load <Texture2D>("Fonts/font2o_1");

                GameFont     = new GameFont(fontFile, fontTexture, 1f);
                GameFontGrey = new GameFont(fontFile, fontGreyTexture, 0.75f);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
コード例 #30
0
        private async Task ProduceStart(bool flushHeaders)
        {
            Debug.Assert(_hasResponseStarted == false);

            _hasResponseStarted = true;

            SetResponseHeaders();

            EnsureIOInitialized();

            if (flushHeaders)
            {
                await AsyncIO.FlushAsync();
            }

            _writeBodyTask = WriteBody(!flushHeaders);
        }
コード例 #31
0
ファイル: NetworkIO.cs プロジェクト: burris/monotorrent
 internal static void EnqueueSend(IConnection connection, byte[] buffer, int offset, int count, AsyncTransfer callback, object state, RateLimiter limiter, ConnectionMonitor managerMonitor, ConnectionMonitor peerMonitor)
 {
     AsyncIO io = new AsyncIO(connection, buffer, offset, count, callback, state, limiter, managerMonitor, peerMonitor);
     EnqueueSend(io);
 }
コード例 #32
0
ファイル: NetworkIO.cs プロジェクト: burris/monotorrent
        private static void EnqueueSend(AsyncIO io)
        {
            try
            {
                if (io.RateLimiter == null)
                {
                    io.Connection.BeginSend(io.Buffer, io.Offset + io.Count, io.Total - io.Count, EndSendCallback, io);
                }
                else if (io.RateLimiter.Chunks > 0)
                {
                    if ((io.Total - io.Count) > ConnectionManager.ChunkLength / 2)
                        Interlocked.Decrement(ref io.RateLimiter.Chunks);

                    // Receive in 2kB (or less) chunks to allow rate limiting to work
                    io.Connection.BeginSend(io.Buffer, io.Offset + io.Count, Math.Min(ConnectionManager.ChunkLength, io.Total - io.Count), EndSendCallback, io);
                }
                else
                {
                    lock (sendQueue)
                        sendQueue.Add(io);
                }
            }
            catch
            {
                io.Callback(false, 0, io.State);
            }
        }