Esempio n. 1
0
        public void Clone_should_return_other_instance()
        {
            var source = new List <object>();
            var clone  = InternalExtensions.Clone(source);

            Assert.NotSame(source, clone);
        }
Esempio n. 2
0
        public void Implements_should_return_true_when_source_does_implement_the_interface()
        {
            var source        = typeof(String);
            var interfaceType = typeof(IDisposable);

            InternalExtensions.Implements(source, interfaceType).Should().BeFalse();
        }
Esempio n. 3
0
        public void IsEmpty_should_return_true_on_empty_list()
        {
            var target  = new List <object>(0);
            var isEmpty = InternalExtensions.IsEmpty(target);

            Assert.True(isEmpty);
        }
Esempio n. 4
0
        public void Implements_generic_should_throw_when_interfaceType_is_not_an_interface_type()
        {
            var    source = typeof(Stream);
            Action act    = () => InternalExtensions.Implements <String>(source);

            act.ShouldThrow <ArgumentException>().And.ParamName.Should().Be("interfaceType");
        }
Esempio n. 5
0
        public void Implements_should_throw_when_source_is_null()
        {
            var    interfaceType = typeof(IDisposable);
            Action act           = () => InternalExtensions.Implements(null, interfaceType);

            act.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("source");
        }
Esempio n. 6
0
        public void Implements_should_throw_when_interfaceType_is_null()
        {
            var    source = typeof(Stream);
            Action act    = () => InternalExtensions.Implements(source, null);

            act.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("interfaceType");
        }
Esempio n. 7
0
        public void Clone_should_throw_ArgumentNullException_when_source_is_null()
        {
            List <string> nullTarget = null;
            Action        act        = () => InternalExtensions.Clone(nullTarget);

            act.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("source");
        }
Esempio n. 8
0
        public void IsEmpty_should_return_true_on_empty_array()
        {
            var target  = new object[0];
            var isEmpty = InternalExtensions.IsEmpty(target);

            Assert.True(isEmpty);
        }
Esempio n. 9
0
        public void IsEmpty_should_throw_ArgumentNullException_on_null_reference()
        {
            List <object> target = null;
            Action        act    = () => InternalExtensions.IsEmpty(target);

            act.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("source");
        }
Esempio n. 10
0
        public void IsEmpty_should_return_false_on_non_empty_array()
        {
            var target  = new object[1];
            var isEmpty = InternalExtensions.IsEmpty(target);

            Assert.False(isEmpty);
        }
Esempio n. 11
0
 protected void UpdateProperty(InternalPropertyData d, bool push = false)
 {
     lock (d)
     {
         d.Data.SerializedData = InternalExtensions.Serialize(d.Descriptor.Property.GetValue(this), this._Context.Host.Serializer);
         d.IsPushed            = push;
     }
 }
Esempio n. 12
0
        public void IsEmpty_should_return_false_on_non_empty_list()
        {
            var target = new List <object>();

            target.Add(new object());
            var isEmpty = InternalExtensions.IsEmpty(target);

            Assert.False(isEmpty);
        }
Esempio n. 13
0
        public void Clone_should_return_list_with_same_values()
        {
            var source = new List <int> {
                1, 2, 3, 4, 5
            };
            var clone = InternalExtensions.Clone(source);

            clone.Should().ContainInOrder(source);
        }
Esempio n. 14
0
        /// <summary>
        /// Clears query caches for all typed queries.
        /// </summary>
        public static void ClearCaches()
        {
            InternalExtensions.ClearCaches();

            foreach (var cleaner in CacheCleaners)
            {
                cleaner();
            }
        }
Esempio n. 15
0
 protected override ITypeSymbol GetArgumentType(
     SemanticModel semanticModel,
     Argument argument,
     CancellationToken cancellationToken
     ) =>
 InternalExtensions.DetermineParameterType(
     argument.Expression,
     semanticModel,
     cancellationToken
     );
Esempio n. 16
0
        /// <summary>
        /// Clears query caches for all typed queries.
        /// </summary>
        public static void ClearCaches()
        {
            InternalExtensions.ClearCaches();

            // ConcurrentBag has thread safe enumerator
            foreach (var cleaner in CacheCleaners)
            {
                cleaner();
            }
        }
Esempio n. 17
0
            Expression BuildExpression(int fieldIndex, ISqlExpression?sqlExpression)
            {
                Expression expr;

                if (SequenceHelper.UnwrapSubqueryContext(Sequence) is DefaultIfEmptyBuilder.DefaultIfEmptyContext defaultIfEmpty)
                {
                    expr = Builder.BuildSql(_returnType, fieldIndex, sqlExpression);
                    if (defaultIfEmpty.DefaultValue != null && expr is ConvertFromDataReaderExpression convert)
                    {
                        var generator = new ExpressionGenerator();
                        expr = convert.MakeNullable();
                        if (expr.Type.IsNullable())
                        {
                            var exprVar      = generator.AssignToVariable(expr, "nullable");
                            var defaultValue = defaultIfEmpty.DefaultValue;
                            if (defaultValue.Type != expr.Type)
                            {
                                var convertLambda = Builder.MappingSchema.GenerateSafeConvert(defaultValue.Type, expr.Type);
                                defaultValue = InternalExtensions.ApplyLambdaToExpression(convertLambda, defaultValue);
                            }

                            var resultVar = generator.AssignToVariable(defaultValue, "result");

                            generator.AddExpression(Expression.IfThen(
                                                        Expression.NotEqual(exprVar, ExpressionInstances.UntypedNull),
                                                        Expression.Assign(resultVar, Expression.Convert(exprVar, resultVar.Type))));

                            generator.AddExpression(resultVar);

                            expr = generator.Build();
                        }
                    }
                }
                else
                if (_methodName == "Sum" || _returnType.IsNullableType())
                {
                    expr = Builder.BuildSql(_returnType, fieldIndex, sqlExpression);
                }
                else
                {
                    expr = Expression.Block(
                        Expression.Call(null, MemberHelper.MethodOf(() => CheckNullValue(false, null !)), Expression.Call(ExpressionBuilder.DataReaderParam, Methods.ADONet.IsDBNull, ExpressionInstances.Constant0), Expression.Constant(_methodName)),
                        Builder.BuildSql(_returnType, fieldIndex, sqlExpression));
                }

                return(expr);
            }
        public static Task CopyToAsync(this Stream stream, Stream destination, int bufferSize, CancellationToken cancellationToken)
        {
            byte[] buffer    = new byte[bufferSize];
            int    bytesRead = 0;

            return(InternalExtensions.WhileAsync(() => stream.ReadAsync(buffer, 0, bufferSize, cancellationToken).OnSuccess(delegate(Task <int> readTask)
            {
                bytesRead = readTask.Result;
                return bytesRead > 0;
            }), delegate
            {
                cancellationToken.ThrowIfCancellationRequested();
                return destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).OnSuccess(delegate(Task _)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                });
            }));
        }
Esempio n. 19
0
        internal static ParameterAccessor GetParameter(Type type, IDataContext dataContext, SqlField field)
        {
            var exprParam = Expression.Parameter(typeof(Expression), "expr");

            Expression getter = Expression.Convert(
                Expression.Property(
                    Expression.Convert(exprParam, typeof(ConstantExpression)),
                    ReflectionHelper.Constant.Value),
                type);

            var descriptor    = field.ColumnDescriptor;
            var dbValueLambda = descriptor.GetDbParamLambda();

            Expression?valueGetter;
            Expression?dbDataTypeExpression;

            valueGetter = InternalExtensions.ApplyLambdaToExpression(dbValueLambda, getter);

            if (typeof(DataParameter).IsSameOrParentOf(valueGetter.Type))
            {
                dbDataTypeExpression = Expression.Call(Expression.Constant(field.ColumnDescriptor.GetDbDataType(false)),
                                                       DbDataType.WithSetValuesMethodInfo,
                                                       Expression.PropertyOrField(valueGetter, nameof(DataParameter.DbDataType)));
                valueGetter = Expression.PropertyOrField(valueGetter, nameof(DataParameter.Value));
            }
            else
            {
                var dbDataType = field.ColumnDescriptor.GetDbDataType(true).WithSystemType(valueGetter.Type);
                dbDataTypeExpression = Expression.Constant(dbDataType);
            }

            var param = ExpressionBuilder.CreateParameterAccessor(
                dataContext, valueGetter, getter, dbDataTypeExpression, valueGetter, exprParam, Expression.Parameter(typeof(object[]), "ps"), Expression.Parameter(typeof(IDataContext), "ctx"), field.Name.Replace('.', '_'));

            return(param);
        }
Esempio n. 20
0
        /*********
        ** Private methods
        *********/
        /// <summary>Initialise SMAPI and mods after the game starts.</summary>
        private void InitialiseAfterGameStart()
        {
            // load settings
            this.Settings = JsonConvert.DeserializeObject <SConfig>(File.ReadAllText(Constants.ApiConfigPath));
            this.GameInstance.VerboseLogging = this.Settings.VerboseLogging;

            // load core components
            this.ModRegistry        = new ModRegistry(this.Settings.ModCompatibility);
            this.DeprecationManager = new DeprecationManager(this.Monitor, this.ModRegistry);
            this.CommandManager     = new CommandManager();

            // inject compatibility shims
#pragma warning disable 618
            Command.Shim(this.CommandManager, this.DeprecationManager, this.ModRegistry);
            Config.Shim(this.DeprecationManager);
            InternalExtensions.Shim(this.ModRegistry);
            Log.Shim(this.DeprecationManager, this.GetSecondaryMonitor("legacy mod"), this.ModRegistry);
            Mod.Shim(this.DeprecationManager);
            ContentEvents.Shim(this.ModRegistry, this.Monitor);
            GameEvents.Shim(this.DeprecationManager);
            PlayerEvents.Shim(this.DeprecationManager);
            TimeEvents.Shim(this.DeprecationManager);
#pragma warning restore 618

            // redirect direct console output
            {
                Monitor monitor = this.GetSecondaryMonitor("Console.Out");
                if (monitor.WriteToConsole)
                {
                    this.ConsoleManager.OnMessageIntercepted += message => this.HandleConsoleMessage(monitor, message);
                }
            }

            // add headers
            if (this.Settings.DeveloperMode)
            {
                this.Monitor.ShowTraceInConsole = true;
                this.Monitor.Log($"You configured SMAPI to run in developer mode. The console may be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Info);
            }
            if (!this.Settings.CheckForUpdates)
            {
                this.Monitor.Log($"You configured SMAPI to not check for updates. Running an old version of SMAPI is not recommended. You can enable update checks by reinstalling SMAPI or editing {Constants.ApiConfigPath}.", LogLevel.Warn);
            }
            if (!this.Monitor.WriteToConsole)
            {
                this.Monitor.Log("Writing to the terminal is disabled because the --no-terminal argument was received. This usually means launching the terminal failed.", LogLevel.Warn);
            }
            if (this.Settings.VerboseLogging)
            {
                this.Monitor.Log("Verbose logging enabled.", LogLevel.Trace);
            }

            // validate XNB integrity
            if (!this.ValidateContentIntegrity())
            {
                this.Monitor.Log("SMAPI found problems in the game's XNB files which may cause errors or crashes while you're playing. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Warn);
            }

            // load mods
            int modsLoaded;
            {
                // load mods
                JsonHelper     jsonHelper          = new JsonHelper();
                IList <Action> deprecationWarnings = new List <Action>();
                ModMetadata[]  mods = this.FindMods(Constants.ModPath, new JsonHelper(), deprecationWarnings);
                modsLoaded = this.LoadMods(mods, jsonHelper, (SContentManager)Game1.content, deprecationWarnings);

                // log deprecation warnings together
                foreach (Action warning in deprecationWarnings)
                {
                    warning();
                }
            }
            if (this.Monitor.IsExiting)
            {
                this.Monitor.Log("SMAPI shutting down: aborting initialisation.", LogLevel.Warn);
                return;
            }

            // update window titles
            this.GameInstance.Window.Title = $"Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} - running SMAPI {Constants.ApiVersion} with {modsLoaded} mods";
            Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} with {modsLoaded} mods";

            // start SMAPI console
            new Thread(this.RunConsoleLoop).Start();
        }
Esempio n. 21
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public virtual string[] ToArray() => InternalExtensions.ToArrayInternal(this);
Esempio n. 22
0
        public Task <Tuple <HttpStatusCode, string> > ExecuteAsync(HttpRequest httpRequest,
                                                                   IProgress <ParseUploadProgressEventArgs> uploadProgress,
                                                                   IProgress <ParseDownloadProgressEventArgs> downloadProgress,
                                                                   CancellationToken cancellationToken)
        {
            uploadProgress   = uploadProgress ?? new Progress <ParseUploadProgressEventArgs>();
            downloadProgress = downloadProgress ?? new Progress <ParseDownloadProgressEventArgs>();

            var httpMethod = new HttpMethod(httpRequest.Method);
            var message    = new HttpRequestMessage(httpMethod, httpRequest.Uri);

            // Fill in zero-length data if method is post.
            Stream data = httpRequest.Data;

            if (httpRequest.Data == null && httpRequest.Method.ToLower().Equals("post"))
            {
                data = new MemoryStream(new byte[0]);
            }

            if (data != null)
            {
                message.Content = new StreamContent(data);
            }

            if (httpRequest.Headers != null)
            {
                foreach (var header in httpRequest.Headers)
                {
                    if (HttpContentHeaders.Contains(header.Key))
                    {
                        message.Content.Headers.Add(header.Key, header.Value);
                    }
                    else
                    {
                        message.Headers.Add(header.Key, header.Value);
                    }
                }
            }

            // Avoid aggressive caching on Windows Phone 8.1.
            message.Headers.Add("Cache-Control", "no-cache");
            message.Headers.IfModifiedSince = DateTimeOffset.UtcNow;

            // TODO: (richardross) investigate progress here, maybe there's something we're missing in order to support this.
            uploadProgress.Report(new ParseUploadProgressEventArgs {
                Progress = 0
            });

            return(_client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                   .ContinueWith(httpMessageTask =>
            {
                var response = httpMessageTask.Result;

                uploadProgress.Report(new ParseUploadProgressEventArgs {
                    Progress = 1
                });

                return response.Content.ReadAsStreamAsync().ContinueWith(streamTask =>
                {
                    var resultStream = new MemoryStream();
                    var responseStream = streamTask.Result;

                    int bufferSize = 4096;
                    byte[] buffer = new byte[bufferSize];
                    int bytesRead = 0;
                    long totalLength = -1;
                    long readSoFar = 0;

                    try
                    {
                        totalLength = responseStream.Length;
                    }
                    catch (NotSupportedException)
                    {
                    }

                    return InternalExtensions.WhileAsync(() =>
                    {
                        return responseStream.ReadAsync(buffer, 0, bufferSize, cancellationToken).OnSuccess(
                            readTask =>
                        {
                            bytesRead = readTask.Result;
                            return bytesRead > 0;
                        });
                    }, () =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        return resultStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).OnSuccess(_ =>
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            readSoFar += bytesRead;

                            if (totalLength > -1)
                            {
                                downloadProgress.Report(
                                    new ParseDownloadProgressEventArgs {
                                    Progress = 1.0 * readSoFar / totalLength
                                });
                            }
                        });
                    }).ContinueWith(_ =>
                    {
                        responseStream.Dispose();
                        return _;
                    }, cancellationToken).Unwrap().OnSuccess(_ =>
                    {
                        // If getting stream size is not supported, then report download only once.
                        if (totalLength == -1)
                        {
                            downloadProgress.Report(new ParseDownloadProgressEventArgs {
                                Progress = 1.0
                            });
                        }

                        // Assume UTF-8 encoding.
                        var resultAsArray = resultStream.ToArray();
                        var resultString = Encoding.UTF8.GetString(resultAsArray, 0, resultAsArray.Length);
                        resultStream.Dispose();
                        return new Tuple <HttpStatusCode, string>(response.StatusCode, resultString);
                    });
                }, cancellationToken);
            }, cancellationToken).Unwrap().Unwrap());
        }
Esempio n. 23
0
        public void Implements_generic_should_return_false_when_source_does_not_implement_the_interface()
        {
            var source = typeof(Stream);

            InternalExtensions.Implements <IDisposable>(source).Should().BeTrue();
        }
Esempio n. 24
0
        /// <summary>Launch SMAPI.</summary>
        internal void LaunchInteractively()
        {
            // initialise logging
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); // for consistent log formatting
            this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} on {this.GetFriendlyPlatformName()}", LogLevel.Info);
            Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)}";

            // inject compatibility shims
#pragma warning disable 618
            Command.Shim(this.CommandManager, this.DeprecationManager, this.ModRegistry);
            Config.Shim(this.DeprecationManager);
            InternalExtensions.Shim(this.ModRegistry);
            Log.Shim(this.DeprecationManager, this.GetSecondaryMonitor("legacy mod"), this.ModRegistry);
            Mod.Shim(this.DeprecationManager);
            ContentEvents.Shim(this.ModRegistry, this.Monitor);
            PlayerEvents.Shim(this.DeprecationManager);
            TimeEvents.Shim(this.DeprecationManager);
#pragma warning restore 618

            // redirect direct console output
            {
                Monitor monitor = this.GetSecondaryMonitor("Console.Out");
                monitor.WriteToFile = false; // not useful for troubleshooting mods per discussion
                if (monitor.WriteToConsole)
                {
                    this.ConsoleManager.OnLineIntercepted += line => monitor.Log(line, LogLevel.Trace);
                }
            }

            // add warning headers
            if (this.Settings.DeveloperMode)
            {
                this.Monitor.ShowTraceInConsole = true;
                this.Monitor.Log($"You configured SMAPI to run in developer mode. The console may be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Warn);
            }
            if (!this.Settings.CheckForUpdates)
            {
                this.Monitor.Log($"You configured SMAPI to not check for updates. Running an old version of SMAPI is not recommended. You can enable update checks by reinstalling SMAPI or editing {Constants.ApiConfigPath}.", LogLevel.Warn);
            }
            if (!this.Monitor.WriteToConsole)
            {
                this.Monitor.Log("Writing to the terminal is disabled because the --no-terminal argument was received. This usually means launching the terminal failed.", LogLevel.Warn);
            }

            // print file paths
            this.Monitor.Log($"Mods go here: {Constants.ModPath}");

            // hook into & launch the game
            try
            {
                // verify version
                if (Constants.GameVersion.IsOlderThan(Constants.MinimumGameVersion))
                {
                    this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)}, but the oldest supported version is {Constants.GetGameDisplayVersion(Constants.MinimumGameVersion)}. Please update your game before using SMAPI. If you have the beta version on Steam, you may need to opt out to get the latest non-beta updates.", LogLevel.Error);
                    this.PressAnyKeyToExit();
                    return;
                }
                if (Constants.MaximumGameVersion != null && Constants.GameVersion.IsNewerThan(Constants.MaximumGameVersion))
                {
                    this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)}, but this version of SMAPI is only compatible up to Stardew Valley {Constants.GetGameDisplayVersion(Constants.MaximumGameVersion)}. Please check for a newer version of SMAPI.", LogLevel.Error);
                    this.PressAnyKeyToExit();
                    return;
                }

                // initialise folders
                this.Monitor.Log("Loading SMAPI...");
                this.VerifyPath(Constants.ModPath);
                this.VerifyPath(Constants.LogDir);

                // check for update when game loads
                if (this.Settings.CheckForUpdates)
                {
                    GameEvents.GameLoaded += (sender, e) => this.CheckForUpdateAsync();
                }

                // launch game
                this.StartGame();
            }
            catch (Exception ex)
            {
                this.Monitor.Log($"Critical error: {ex.GetLogSummary()}", LogLevel.Error);
            }
            this.PressAnyKeyToExit();
        }
Esempio n. 25
0
        public void IsNullOrEmpty_should_return_false_on_string_with_text()
        {
            var result = InternalExtensions.IsNullOrEmpty("Hello world");

            result.Should().BeFalse();
        }
Esempio n. 26
0
        public void IsNullOrEmpty_should_return_true_on_empty()
        {
            var result = InternalExtensions.IsNullOrEmpty(string.Empty);

            result.Should().BeTrue();
        }
Esempio n. 27
0
        public void IsNullOrEmpty_should_return_true_on_null()
        {
            var result = InternalExtensions.IsNullOrEmpty(null);

            result.Should().BeTrue();
        }