NotNull() public static method

public static NotNull ( object? value, string parameterName, string? field = null ) : void
value object?
parameterName string
field string?
return void
示例#1
0
        public async Task <object> InsertAsync(NsDatabase database, string tableName, string json, object id, ObjectIdType typeOfObjectId)
        {
            Validate.NotNull(database, nameof(database));
            Validate.NotNullOrEmptyOrWhiteSpace(tableName, nameof(tableName));
            Validate.NotNull(json, nameof(json));

            if (id != null || typeOfObjectId == ObjectIdType.Guid)
            {
                await ExecuteNonQueryAsync(new[]
                {
                    $"INSERT INTO \"{database.Name}\".\"{tableName}\"",
                    $"           (\"_id\"",
                    $"           ,\"_document\")",
                    $"     VALUES",
                    $"           (@id",
                    $"           ,@document)"
                },
                                           new Dictionary <string, object>()
                {
                    { "@id", id ?? Guid.NewGuid() },
                    { "@document", json }
                },
                                           executeAsScalar : false);

                return(id);
            }

            return(await ExecuteNonQueryAsync(new[]
            {
                $"INSERT INTO \"{database.Name}\".\"{tableName}\"",
                $"           (\"_document\")" +
                $"     VALUES",
                $"           (@document)",
                $"RETURNING _id"
            },
                                              new Dictionary <string, object>()
            {
                { "@document", json }
            },
                                              executeAsScalar : true));
        }
示例#2
0
        public bool Add(StackSnapshotsBufferSegment segment)
        {
            if (_isReadonly)
            {
                return(false);
            }

            Validate.NotNull(segment, nameof(segment));

            lock (_updateLock)
            {
                if (_isReadonly)
                {
                    return(false);
                }

                if (_segments.Count == 0)
                {
                    _totalTimeRangeStart = segment.TimeRangeStart;
                    _totalTimeRangeEnd   = segment.TimeRangeEnd;
                }
                else
                {
                    if (segment.TimeRangeStart < _totalTimeRangeStart)
                    {
                        _totalTimeRangeStart = segment.TimeRangeStart;
                    }

                    if (segment.TimeRangeEnd > _totalTimeRangeEnd)
                    {
                        _totalTimeRangeEnd = segment.TimeRangeEnd;
                    }
                }

                _totalByteCount      += segment.SegmentByteCount;
                _totalSnapshotsCount += segment.SnapshotsCount;
                _segments.Add(segment);

                return(true);
            }
        }
示例#3
0
        private Task <AvailabilityTestInfo> CreateAvailabilityTestInfo(AvailabilityTestInfoAttribute attribute, ValueBindingContext valueBindingContext)
        {
            // A function is an Availability Test iff is has a return value marked with [AvailabilityTestResult];
            // whereas a [AvailabilityTestInfo] is OPTIONAL to get test information at runtime.
            // User could have marked a parameter with [AvailabilityTestInfo] but no return value with [AvailabilityTestResult]:
            // That does not make sense, but we need to do something graceful.
            // There is no telling what will run first: this method, or CreateAvailabilityTelemetryAsyncCollector(..) above.
            // From here we cannot call _availabilityTestRegistry.Functions.Register(..), becasue the attribute type we get
            // here does not contain any configuration.
            // We will attach a raw test info object to this invocation.
            // If a test-RESULT-attribute is attached to this function later, it will supply configuration eventually.
            // If not, the test info will remain raw and we must remember to clear the invocation from the registry in the post-function filter.

            Validate.NotNull(attribute, nameof(attribute));
            Validate.NotNull(valueBindingContext, nameof(valueBindingContext));

            string functionName = valueBindingContext.FunctionContext.MethodName;

            using (_log.BeginScope(LogMonikers.Scopes.CreateForTestInvocation(functionName)))
            {
                // Register this particular invocation of this function:
                Guid functionInstanceId = valueBindingContext.FunctionInstanceId;
                AvailabilityTestInvocationState invocationState = _availabilityTestRegistry.Invocations.GetOrRegister(functionInstanceId, _log);

                // Create the test info:
                var testInfo = new AvailabilityTestInfo();

                // If the test scope is already set (out-of-proc function), then use it to initialize the test info:
                bool isTestScopeInitialized = invocationState.TryGetTestScope(out AvailabilityTestScope testScope);
                if (isTestScopeInitialized)
                {
                    testInfo.CopyFrom(testScope.CreateAvailabilityTestInfo());
                }

                // Attach the test info to the invocation state bag:
                invocationState.AttachTestInfo(testInfo);

                // Done:
                return(Task.FromResult(testInfo));
            }
        }
示例#4
0
        public static async Task <ResourceGroup> Load(this ResourceGroup resourceGroup, CsmWrapper <CsmResourceGroup> csmResourceGroup = null, IEnumerable <CsmWrapper <object> > resources = null, bool loadSubResources = true)
        {
            Validate.ValidateCsmResourceGroup(resourceGroup);

            if (csmResourceGroup == null)
            {
                var csmResourceGroupResponse = await csmClient.HttpInvoke(HttpMethod.Get, ArmUriTemplates.ResourceGroup.Bind(resourceGroup));

                await csmResourceGroupResponse.EnsureSuccessStatusCodeWithFullError();

                csmResourceGroup = await csmResourceGroupResponse.Content.ReadAsAsync <CsmWrapper <CsmResourceGroup> >();
            }

            //Not sure what to do at this point TODO
            Validate.NotNull(csmResourceGroup.tags, "csmResorucegroup.tags");

            resourceGroup.Tags = csmResourceGroup.tags;

            if (resources == null)
            {
                var csmResourceGroupResourcesResponse = await csmClient.HttpInvoke(HttpMethod.Get, ArmUriTemplates.ResourceGroupResources.Bind(resourceGroup));

                await csmResourceGroupResourcesResponse.EnsureSuccessStatusCodeWithFullError();

                resources = (await csmResourceGroupResourcesResponse.Content.ReadAsAsync <CsmArrayWrapper <object> >()).value;
            }



            if (loadSubResources)
            {
                await Task.WhenAll(LoadSites(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.Web/sites", StringComparison.OrdinalIgnoreCase))),
                                   LoadApiApps(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.AppService/apiapps", StringComparison.OrdinalIgnoreCase))),
                                   LoadGateways(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.AppService/gateways", StringComparison.OrdinalIgnoreCase))),
                                   LoadLogicApps(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.Logic/workflows", StringComparison.OrdinalIgnoreCase))),
                                   LoadServerFarms(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.Web/serverFarms", StringComparison.OrdinalIgnoreCase))),
                                   LoadStorageAccounts(resourceGroup, resources.Where(r => r.type.Equals("Microsoft.Storage/storageAccounts", StringComparison.OrdinalIgnoreCase))));
            }

            return(resourceGroup);
        }
示例#5
0
        public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
        {
            Validate.NotNull(INJECTION_OPERAND);

            List <CodeInstruction> instructionList = instructions.ToList();

            bool shouldInject = false;

            /**
             * When placing some modules in multiplayer it throws an exception because it tries to validate
             * that the current player is in the subroot.  We want to skip over this code if we are placing
             * a multiplayer piece:
             *
             * if (main == null || main.currentSub == null || !main.currentSub.isBase)
             *
             * Injected code:
             *
             * if (!MultiplayerBuilder.isPlacing && (main == null || main.currentSub == null || !main.currentSub.isBase))
             *
             */
            for (int i = 0; i < instructionList.Count; i++)
            {
                CodeInstruction instruction = instructionList[i];
                yield return(instruction);

                if (shouldInject)
                {
                    shouldInject = false;

                    // First fetch the place we want to jump... this will be the same place as !main.currentSub.isBase
                    CodeInstruction jumpInstruction = GetJumpInstruction(instructionList, i);

                    yield return(new CodeInstruction(OpCodes.Call, typeof(MultiplayerBuilder).GetMethod("get_isPlacing", BindingFlags.Public | BindingFlags.Static)));

                    yield return(new CodeInstruction(OpCodes.Brtrue_S, jumpInstruction.operand)); // copy the jump location
                }

                // We want to inject just after Player main = Player.main... if this is that instruction then we'll inject after the next opcode (stfld)
                shouldInject = (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND));
            }
        }
        private static void SetupListening()
        {
            ConsoleWrite.LineLine("Starting setting up DiagnosticSource listening.");

            if (!DiagnosticSourceSafeExtensions.SubscribeToAllSourcesSafe(ObserverAdapter.OnNextHandler(
                                                                              (DiagnosticListenerStub diagnosticListener) =>
            {
                diagnosticListener.GetNameSafe(out string diagnosticListenerName, out _);
                ConsoleWrite.Line($"Subscriber called: diagnosticSourceObserver(diagnosticListener.Name: \"{diagnosticListenerName}\")");

                if (diagnosticListenerName.Equals("DemoXxx.UseDiagnosticSource.Name1", StringComparison.Ordinal))
                {
                    if (!diagnosticListener.SubscribeToEventsSafe(
                            ObserverAdapter.OnNextHandler((KeyValuePair <string, object> eventInfo) =>
                    {
                        ConsoleWrite.Line($"Event Handler called: eventObserver(eventName: \"{eventInfo.Key}\", payloadValue: {(eventInfo.Value ?? "<null>")})");
                    }),
                            (string eventName, object arg1, object arg2) =>
                    {
                        Validate.NotNull(eventName, nameof(eventName));
                        bool res = eventName.StartsWith("EventXyzName", StringComparison.OrdinalIgnoreCase) &&
                                   (arg1 == null || !(arg1 is Int32 arg1Val) || arg1Val >= 0);
                        ConsoleWrite.Line($"Filter called: isEventEnabledFilter(eventName: \"{eventName}\", arg1: {(arg1 ?? "<null>")}, arg2: {(arg2 ?? "<null>")})."
                                          + $" Returning: {res}.");
                        return(res);
                    },
                            out IDisposable eventSubscription,
                            out _))
                    {
                        ConsoleWrite.LineLine("Could not set up an events subscription. Likely no events will be received. Error has been logged.");
                    }
                }
            }),
                                                                          out IDisposable listenerSubscription,
                                                                          out _))
            {
                ConsoleWrite.LineLine("Could not set up an all-sources-subscription. Likely no events will be received. Error has been logged.");
            }

            ConsoleWrite.Line("Finished setting up DiagnosticSource listening.");
        }
示例#7
0
        /// <summary>Remove a list of allowed attributes from a tag.</summary>
        /// <remarks>
        /// Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.)
        /// <para />
        /// E.g.: <code>removeAttributes("a", "href", "class")</code> disallows <code>href</code> and <code>class</code>
        /// attributes on <code>a</code> tags.
        /// <para />
        /// To make an attribute invalid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
        /// <code>removeAttributes(":all", "class")</code>.
        /// </remarks>
        /// <param name="tag">The tag the attributes are for.</param>
        /// <param name="keys">List of invalid attributes for the tag</param>
        /// <returns>this (for chaining)</returns>
        public virtual iText.StyledXmlParser.Jsoup.Safety.Whitelist RemoveAttributes(String tag, params String[] keys
                                                                                     )
        {
            Validate.NotEmpty(tag);
            Validate.NotNull(keys);
            Validate.IsTrue(keys.Length > 0, "No attributes supplied.");
            Whitelist.TagName tagName = Whitelist.TagName.ValueOf(tag);
            ICollection <Whitelist.AttributeKey> attributeSet = new HashSet <Whitelist.AttributeKey>();

            foreach (String key in keys)
            {
                Validate.NotEmpty(key);
                attributeSet.Add(Whitelist.AttributeKey.ValueOf(key));
            }
            if (tagNames.Contains(tagName) && attributes.ContainsKey(tagName))
            {
                // Only look in sub-maps if tag was allowed
                ICollection <Whitelist.AttributeKey> currentSet = attributes.Get(tagName);
                currentSet.RemoveAll(attributeSet);
                if (currentSet.IsEmpty())
                {
                    // Remove tag from attribute map if no attributes are allowed for tag
                    attributes.JRemove(tagName);
                }
            }
            if (tag.Equals(":all"))
            {
                // Attribute needs to be removed from all individually set tags
                foreach (Whitelist.TagName name in attributes.Keys)
                {
                    ICollection <Whitelist.AttributeKey> currentSet = attributes.Get(name);
                    currentSet.RemoveAll(attributeSet);
                    if (currentSet.IsEmpty())
                    {
                        // Remove tag from attribute map if no attributes are allowed for tag
                        attributes.JRemove(name);
                    }
                }
            }
            return(this);
        }
示例#8
0
        public int Add(IncomeParam param)
        {
            int id = 0;

            Validate.NotNull(param.IncomeName, "Income name is required.");

            var budget = _budgetRepository.Get(param.BudgetId);

            Validate.NotNull(budget, "Budget name is not found.");

            isExist(param.IncomeName, param.IncomeDate);
            using (_unitOfWork)
            {
                Income model = new Income(param.IncomeName, param.Definition, param.IncomeDate, param.Amount, budget, param.CreatedBy, param.CreatedDate);
                _incomeRepository.Insert(model);

                _unitOfWork.Commit();
                id = model.Id;
            }
            return(id);
        }
        private ProfilerEngine(IProductConfiguration config)
        {
            Validate.NotNull(config, nameof(config));

            _versionInfo = ProfilerEngineVersionInfo.CreateNewInstance();

            _profiledThreadInfoProvider = new ProfiledThreadInfoProvider();
            _profiledAppDomainProvider  = new ProfiledAppDomainProvider();

            _enqueueStackSnapshotBufferSegmentForExport = NativeCallback_EnqueueStackSnapshotBufferSegmentForExport;
            _tryShutdownCurrentManagedProfilerEngine    = NativeCallback_TryShutdownCurrentManagedProfilerEngine;

            _completedStackSnapshots = new StackSnapshotsBufferSegmentCollection();

            _pprofBuilder = new PProfBuilder();

            RegisterReversePInvokeCallbacks();

            _resolveAndExportStacksBackgroundLoop = new ResolveAndExportStacksBackgroundLoop(this, config);
            _resolveAndExportStacksBackgroundLoop.Start();
        }
        public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
        {
            Validate.NotNull(INJECTION_OPERAND);

            foreach (CodeInstruction instruction in instructions)
            {
                yield return(instruction);

                if (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND))
                {
                    /*
                     * ArmsController.Reconfigure(null);
                     */
                    yield return(new ValidatedCodeInstruction(OpCodes.Ldarg_0));

                    yield return(new ValidatedCodeInstruction(OpCodes.Ldnull));

                    yield return(new ValidatedCodeInstruction(OpCodes.Call, TARGET_CLASS.GetMethod("Reconfigure", BindingFlags.NonPublic | BindingFlags.Instance)));
                }
            }
        }
示例#11
0
        public void CreateVehicle(TechType techType, NitroxId id, Vector3 position, Quaternion rotation, IEnumerable <InteractiveChildObjectIdentifier> interactiveChildIdentifiers, Optional <NitroxId> dockingBayId, string name, Vector3[] hsb, Vector3[] colours, float health)
        {
            try
            {
                if (techType == TechType.Cyclops)
                {
                    LightmappedPrefabs.main.RequestScenePrefab("cyclops", (go) => OnVehiclePrefabLoaded(techType, go, id, position, rotation, interactiveChildIdentifiers, dockingBayId, name, hsb, colours, health));
                }
                else
                {
                    GameObject techPrefab = CraftData.GetPrefabForTechType(techType, false);
                    Validate.NotNull(techPrefab, $"{nameof(Vehicles)}: No prefab for tech type: {techType}");

                    OnVehiclePrefabLoaded(techType, techPrefab, id, position, rotation, interactiveChildIdentifiers, dockingBayId, name, hsb, colours, health);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"{nameof(Vehicles)}: Error while creating a vehicle {techType} {id}", ex);
            }
        }
示例#12
0
        /// <summary>
        /// Gets the named property value of type <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T">The type of the property value to get.</typeparam>
        /// <param name="object">The <see cref="PSObject"/> that may contain the named property.</param>
        /// <param name="propertyName">The name of the property to get.</param>
        /// <param name="default">
        /// Optional default value to return if the property is not defined.
        /// The default parameter value is the default value of type <typeparamref name="T"/>.
        /// </param>
        /// <returns>The value of the named property if defined; otherwise, the <paramref name="default"/> value.</returns>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is an empty string.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="object"/> or <paramref name="propertyName"/> is null.</exception>
        public static T GetPropertyValue <T>(this PSObject @object, string propertyName, T @default = default(T))
        {
            Validate.NotNull(@object, nameof(@object));
            Validate.NotNullOrEmpty(propertyName, nameof(propertyName));

            var property = @object.Properties.Match(propertyName, PSMemberTypes.Properties).FirstOrDefault();

            if (property != null)
            {
                if (property.Value is T)
                {
                    return((T)property.Value);
                }
                else
                {
                    return((T)LanguagePrimitives.ConvertTo(property.Value, typeof(T)));
                }
            }

            return(@default);
        }
示例#13
0
        private static void SpawnBabiesIfSimulating(IncubatorEgg egg)
        {
            SimulationOwnership simulationOwnership = NitroxServiceLocator.LocateService <SimulationOwnership>();

            NitroxEntity serverKnownParent = egg.GetComponentInParent <NitroxEntity>();

            Validate.NotNull(serverKnownParent, "Could not find a server known parent for incubator egg");

            // Only spawn the babies if we are simulating the main incubator platform.
            if (simulationOwnership.HasAnyLockType(serverKnownParent.Id))
            {
                GameObject baby = UnityEngine.Object.Instantiate <GameObject>(egg.seaEmperorBabyPrefab);
                baby.transform.position      = egg.attachPoint.transform.position;
                baby.transform.localRotation = Quaternion.identity;

                NitroxId babyId = NitroxEntity.GetId(baby);

                Entity entity = new(baby.transform.position.ToDto(), baby.transform.rotation.ToDto(), baby.transform.localScale.ToDto(), TechType.SeaEmperorBaby.ToDto(), 3, "09883a6c-9e78-4bbf-9561-9fa6e49ce766", true, babyId, null);
                NitroxServiceLocator.LocateService <Entities>().BroadcastEntitySpawnedByClient(entity);
            }
        }
示例#14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LinguisticVariable"/> class.
        /// </summary>
        /// <param name="label">
        /// The label.
        /// </param>
        /// <param name="inputSets">
        /// The input sets.
        /// </param>
        /// <param name="lowerBound">
        /// The lower bound for the <see cref="LinguisticVariable"/>.
        /// </param>
        /// <param name="upperBound">
        /// The upper bound for the <see cref="LinguisticVariable"/>.
        /// </param>
        public LinguisticVariable(
            string label,
            IList <FuzzySet> inputSets,
            double lowerBound = double.MinValue,
            double upperBound = double.MaxValue)
        {
            Validate.NotNull(label, nameof(label));
            Validate.CollectionNotNullOrEmpty(inputSets, nameof(inputSets));
            Validate.NotOutOfRange(lowerBound, nameof(lowerBound));
            Validate.NotOutOfRange(upperBound, nameof(upperBound));
            Validate.FuzzySetCollection(inputSets, lowerBound, upperBound);

            this.Subject    = Label.Create(label);
            this.LowerBound = lowerBound;
            this.UpperBound = upperBound;

            foreach (var set in inputSets)
            {
                this.fuzzySets.Add(set.State, set);
            }
        }
            public MultipartFormPostRequest(HttpClient httpPoster, string url, MemoryStream reuseableContent, Action <MemoryStream> releaseReuseableContent)
            {
                Validate.NotNull(httpPoster, nameof(httpPoster));
                Validate.NotNull(releaseReuseableContent, nameof(releaseReuseableContent));

                _httpPoster = httpPoster;
                _url        = url;
                _releaseContentBufferStreamForReuseDelegate = releaseReuseableContent;

                if (reuseableContent != null)
                {
                    reuseableContent.Position = 0;
                    _content = reuseableContent;
                }
                else if (reuseableContent == null)
                {
                    _content = new MemoryStream();
                }

                InitHttpPosterAgnosticData();
            }
示例#16
0
        public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
        {
            Validate.NotNull(INJECTION_OPERAND);

            foreach (CodeInstruction instruction in instructions)
            {
                yield return(instruction);

                if (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND))
                {
                    /*
                     * TransientLocalObjectManager.Add(TransientLocalObjectManager.TransientObjectType.CONSTRUCTOR_INPUT_CRAFTED_GAMEOBJECT, gameObject);
                     */
                    yield return(new CodeInstruction(OpCodes.Ldc_I4_0));

                    yield return(original.Ldloc <GameObject>(0));

                    yield return(new CodeInstruction(OpCodes.Call, Reflect.Method(() => Add(default(TransientObjectType), default(object)))));
                }
            }
        }
示例#17
0
        public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
        {
            Validate.NotNull(INJECTION_OPERAND);

            foreach (CodeInstruction instruction in instructions)
            {
                yield return(instruction);

                if (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND))
                {
                    /*
                     * TransientLocalObjectManager.Add(TransientLocalObjectManager.TransientObjectType.CONSTRUCTOR_INPUT_CRAFTED_GAMEOBJECT, gameObject);
                     */
                    yield return(new ValidatedCodeInstruction(OpCodes.Ldc_I4_0));

                    yield return(original.Ldloc <GameObject>(0));

                    yield return(new ValidatedCodeInstruction(OpCodes.Call, typeof(TransientLocalObjectManager).GetMethod("Add", BindingFlags.Static | BindingFlags.Public, null, new Type[] { TransientObjectType.CONSTRUCTOR_INPUT_CRAFTED_GAMEOBJECT.GetType(), typeof(object) }, null)));
                }
            }
        }
示例#18
0
        /// <summary>
        /// Determines if the results of the <paramref name="selector"/> applied to the <paramref name="source"/> enumerable
        /// contain all the elements from the <paramref name="keys"/>.
        /// </summary>
        /// <typeparam name="T">The type of the source enumerable.</typeparam>
        /// <typeparam name="TKey">The type of the keys.</typeparam>
        /// <param name="source">The source enumerable to check.</param>
        /// <param name="selector">The selector to apply to the <paramref name="source"/> enumerable.</param>
        /// <param name="keys">The keys to check if all are in the <paramref name="source"/> enumerable.</param>
        /// <param name="comparer">The comparer to use. The default is <see cref="EqualityComparer{T}.Default"/>.</param>
        /// <returns>
        /// True if the results of the <paramref name="selector"/> applied to the <paramref name="source"/> enumerable
        /// contain all the elements from the <paramref name="keys"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">One or more parameters are null.</exception>
        public static bool ContainsAll <T, TKey>(this IEnumerable <T> source, Func <T, TKey> selector, IEnumerable <TKey> keys, IEqualityComparer <TKey> comparer = null)
        {
            Validate.NotNull(source, nameof(source));
            Validate.NotNull(selector, nameof(selector));
            Validate.NotNull(keys, nameof(keys));

            comparer = comparer ?? EqualityComparer <TKey> .Default;

            var e     = source.Select(selector);
            var items = new HashSet <TKey>(e, comparer);

            foreach (var key in keys)
            {
                if (!items.Contains(key))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#19
0
        public Player PlayerConnected(NitroxConnection connection, string reservationKey, out bool wasBrandNewPlayer)
        {
            PlayerContext playerContext = reservations[reservationKey];

            Validate.NotNull(playerContext);
            ConnectionAssets assetPackage = assetsByConnection[connection];

            Validate.NotNull(assetPackage);

            wasBrandNewPlayer = playerContext.WasBrandNewPlayer;

            Player player;

            if (!allPlayersByName.TryGetValue(playerContext.PlayerName, out player))
            {
                player = new Player(playerContext.PlayerId,
                                    playerContext.PlayerName,
                                    false,
                                    playerContext,
                                    connection,
                                    NitroxVector3.Zero,
                                    new NitroxId(),
                                    Optional.Empty,
                                    Perms.PLAYER,
                                    defaultPlayerStats,
                                    new List <EquippedItemData>(),
                                    new List <EquippedItemData>());
                allPlayersByName[playerContext.PlayerName] = player;
            }

            // TODO: make a ConnectedPlayer wrapper so this is not stateful
            player.PlayerContext = playerContext;
            player.connection    = connection;

            assetPackage.Player         = player;
            assetPackage.ReservationKey = null;
            reservations.Remove(reservationKey);

            return(player);
        }
示例#20
0
        public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
        {
            Validate.NotNull(INJECTION_OPCODE);
            Validate.NotNull(INJECTION_OPERAND);

            foreach (CodeInstruction instruction in instructions)
            {
                yield return(instruction);

                if (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND))
                {
                    /*
                     * Multiplayer.PacketSender.BuildItem(Enum.GetName(typeof(TechType), CraftData.GetTechType(Builder.prefab)), Builder.ghostModel.transform.position, Builder.placeRotation);
                     */
                    yield return(new ValidatedCodeInstruction(OpCodes.Ldsfld, typeof(Multiplayer).GetField("PacketSender", BindingFlags.Static | BindingFlags.Public)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Ldtoken, typeof(TechType)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(RuntimeTypeHandle) }, null)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Ldsfld, typeof(Builder).GetField("prefab", BindingFlags.Static | BindingFlags.NonPublic)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Call, typeof(CraftData).GetMethod("GetTechType", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(GameObject) }, null)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Box, typeof(TechType)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Call, typeof(System.Enum).GetMethod("GetName")));

                    yield return(new ValidatedCodeInstruction(OpCodes.Ldsfld, typeof(Builder).GetField("ghostModel", BindingFlags.Static | BindingFlags.NonPublic)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Callvirt, typeof(GameObject).GetMethod("get_transform")));

                    yield return(new ValidatedCodeInstruction(OpCodes.Callvirt, typeof(Transform).GetMethod("get_position")));

                    yield return(new ValidatedCodeInstruction(OpCodes.Ldsfld, typeof(Builder).GetField("placeRotation", BindingFlags.Static | BindingFlags.NonPublic)));

                    yield return(new ValidatedCodeInstruction(OpCodes.Callvirt, typeof(PacketSender).GetMethod("BuildItem")));
                }
            }
        }
        /// <summary>
        /// In addition to forwarding all calls from the underlying Diagnostic Listener to the specified <c>eventObserver</c>,
        /// the <c>eventObserver</c>'s <c>OnCompleted()</c> handler will be called if the DiagnosticSource-assembly is unloaded
        /// or dynamically swapped for another version. This allows subscribers to know that no more events are coming.
        /// To handle such case, it is recommended to give up on the existing subscription and to schedule a from-scratch
        /// re-subscription on a timer after a short time period. Such delay ensures that the new assembly version is loaded by then.
        /// Notably, a few events will be lost. This is an explicit design decision in the context of the fact that assembly
        /// unloads are extremely rare.
        /// If the IDisposable returned by this method is disposed, then the above-described notification will not be delivered.
        /// </summary>
        /// <remarks>
        /// Consider using <c>Datadog.Util.ObserverAdapter</c> in shared sources to conveniently create observers suitable for this API.
        /// </remarks>
        public IDisposable SubscribeToEvents(IObserver <KeyValuePair <string, object> > eventObserver, Func <string, object, object, bool> isEventEnabledFilter)
        {
            if (_diagnosticListenerInstance == null)
            {
                return(NoOpSingeltons.EventSubscription);
            }

            Validate.NotNull(eventObserver, nameof(eventObserver));
            // isEventEnabledFilter may be null

            DynamicInvoker_DiagnosticListener invoker = null;

            try
            {
                invoker = _dynamicInvokerHandle.GetInvoker();
                IDisposable eventsSubscription = invoker.Call.Subscribe(_diagnosticListenerInstance, eventObserver, isEventEnabledFilter);

                Action <DiagnosticSourceAssembly.IDynamicInvoker> invokerInvalidatedAction = (invkr) =>
                {
                    // DiagnosticListener does NOT call OnCompleted when the subscription is disposed. So we DO need to call it here:
                    eventObserver.OnCompleted();
                    eventsSubscription.Dispose();
                };

                DynamicInvokerHandle <DynamicInvoker_DiagnosticListener> invokerHandle = _dynamicInvokerHandle;
                IDisposable invokerInvalidatedActionSub = invokerHandle.SubscribeInvalidatedListener(invokerInvalidatedAction);

                IDisposable eventsSubscriptionWrapper = new Disposables.Action(() =>
                {
                    invokerInvalidatedActionSub.Dispose();
                    eventsSubscription.Dispose();
                });

                return(eventsSubscriptionWrapper);
            }
            catch (Exception ex)
            {
                throw LogAndRethrowStubInvocationError(ex, nameof(DynamicInvoker_DiagnosticListener.StubbedApis.Subscribe), isStaticApi: false, invoker?.TargetType);
            }
        }
示例#22
0
        public RemotePlayer Create(PlayerContext playerContext, Optional <NitroxId> subRootId, List <TechType> equippedTechTypes, List <Pickupable> inventoryItems)
        {
            Validate.NotNull(playerContext);

            if (playersById.ContainsKey(playerContext.PlayerId))
            {
                throw new Exception("The playerId has already been used.");
            }

            GameObject   remotePlayerBody = CloneLocalPlayerBodyPrototype();
            RemotePlayer remotePlayer;

            using (packetSender.Suppress <ItemContainerAdd>())
            {
                remotePlayer = new RemotePlayer(remotePlayerBody, playerContext, equippedTechTypes, inventoryItems, playerModelManager);
            }

            if (subRootId.HasValue)
            {
                Optional <GameObject> sub = NitroxEntity.GetObjectFrom(subRootId.Value);
                if (sub.HasValue && sub.Value.TryGetComponent(out SubRoot subRoot))
                {
                    Log.Debug($"Found sub root for {playerContext.PlayerName}. Will add him and update animation.");
                    remotePlayer.SetSubRoot(subRoot);
                }
                else if (sub.HasValue && sub.Value.TryGetComponent(out EscapePod escapePod))
                {
                    Log.Debug($"Found EscapePod for {playerContext.PlayerName}.");
                    remotePlayer.SetEscapePod(escapePod);
                }
                else
                {
                    Log.Error($"Found neither SubRoot component nor EscapePod on {subRootId.Value} for {playerContext.PlayerName}.");
                }
            }

            playersById.Add(remotePlayer.PlayerId, remotePlayer);

            return(remotePlayer);
        }
示例#23
0
        /// <summary>Execute a query agains a database.</summary>
        /// <param name="database">The name of the database.</param>
        /// <param name="query">The query to execute. For language specification please see
        /// <a href="https://influxdb.com/docs/v0.9/concepts/reading_and_writing_data.html">InfluxDb documentation</a>.</param>
        /// <returns>A list of Series which matched the query.</returns>
        /// <exception cref="InfluxDbApiException"></exception>
        public async Task <List <Serie> > QueryAsync(string database, string query)
        {
            InfluxDbApiResponse response = await _influxDbClient.Query(NoErrorHandlers, database, query);

            var queryResult = response.ReadAs <QueryResult>();

            Validate.NotNull(queryResult, "queryResult");
            Validate.NotNull(queryResult.Results, "queryResult.Results");

            // Apparently a 200 OK can return an error in the results
            // https://github.com/influxdb/influxdb/pull/1813
            var error = queryResult.Results.Single().Error;

            if (error != null)
            {
                throw new InfluxDbApiException(System.Net.HttpStatusCode.BadRequest, error);
            }

            var result = queryResult.Results.Single().Series;

            return(result != null?result.ToList() : new List <Serie>());
        }
        /// <summary>
        /// Returns an <c>XContainer</c> containing the same elements and attributes as the specified <c>XContainer</c> but with all namespaces removed.
        /// </summary>
        /// <param name="xContainer">An <c>XElement</c> or <c>XDocument</c> containing the namespaces to be removed.</param>
        /// <returns>An instance of the same type as <see cref="xContainer"/>.</returns>
        public static T RemoveAllNamespaces <T>(this T xContainer) where T : XContainer
        {
            Validate.NotNull(xContainer, nameof(xContainer));

            XElement RemoveAllNamespacesRecursive(XElement xmlDocument)
            {
                object value = null;

                if (xmlDocument.HasElements)
                {
                    value = xmlDocument.Elements().Select(RemoveAllNamespacesRecursive);
                }
                else if (!String.IsNullOrWhiteSpace(xmlDocument.Value))
                {
                    value = xmlDocument.Value;
                }

                return(new XElement(xmlDocument.Name.LocalName,
                                    xmlDocument.Attributes().Where(attr => !attr.IsNamespaceDeclaration),
                                    value));
            }

            var container = xContainer as XDocument;

            if (container != null)
            {
                return(new XDocument(container.Declaration,
                                     RemoveAllNamespacesRecursive(container.Root)) as T);
            }

            var element = xContainer as XElement;

            if (element != null)
            {
                return(RemoveAllNamespacesRecursive(element) as T);
            }

            throw new ArgumentException($"Unhandled implementation of XContainer: {xContainer.GetType().Name}", nameof(xContainer));
        }
示例#25
0
        public static bool TryCreateAndStart(IProductConfiguration config, out ProfilerEngine runningProfilerEngine)
        {
            Validate.NotNull(config, nameof(config));

            runningProfilerEngine = _currentEngine;
            if (runningProfilerEngine != null)
            {
                return(false);
            }

            lock (_singletonAccessLock)
            {
                runningProfilerEngine = _currentEngine;
                if (runningProfilerEngine != null)
                {
                    return(false);
                }

                CreateAndStart(config, out runningProfilerEngine);
                return(runningProfilerEngine != null);
            }
        }
        public bool TryGetInvokerHandleForInstance(object diagnosticSourceInstance, out DynamicInvokerHandle <DynamicInvoker_DiagnosticSource> handle)
        {
            Validate.NotNull(diagnosticSourceInstance, nameof(diagnosticSourceInstance));

            Type actualType = diagnosticSourceInstance.GetType();

            if (_diagnosticSourceType == actualType || _diagnosticSourceType.Equals(actualType))
            {
                handle = _handle;
                return(true);
            }

            // Is IsSubclassOf(..) too restrictive? Consider using 'if (_diagnosticSourceType.IsAssignableFrom(actualType)) {..}' instead.
            if (actualType.IsSubclassOf(_diagnosticSourceType))
            {
                handle = _handle;
                return(true);
            }

            handle = null;
            return(false);
        }
示例#27
0
        public Player CreatePlayer(Connection connection, string reservationKey, out bool wasBrandNewPlayer)
        {
            lock (assetsByConnection)
            {
                ConnectionAssets assetPackage  = assetsByConnection[connection];
                PlayerContext    playerContext = reservations[reservationKey];
                Validate.NotNull(playerContext);

                wasBrandNewPlayer = playerContext.WasBrandNewPlayer;

                // Load previously persisted data for this player.
                Vector3           position    = playerData.GetPosition(playerContext.PlayerName);
                Optional <string> subRootGuid = playerData.GetSubRootGuid(playerContext.PlayerName);

                Player player = new Player(playerContext, connection, position, subRootGuid);
                assetPackage.Player         = player;
                assetPackage.ReservationKey = null;
                reservations.Remove(reservationKey);

                return(player);
            }
        }
        public IDisposable SubscribeListener(TAction action, object state)
        {
            Validate.NotNull(action, nameof(action));

            var subscription = new Subscription(action, state, this);

            AddSubscriptionToList(subscription);

            try
            {
                if (GetMustImmediatelyInvokeNewSubscription(subscription, out TSource source))
                {
                    InvokeOne(subscription, source);
                }
            }
            catch (Exception ex)
            {
                Log.Error(_logComponentMoniker, ex);
            }

            return(subscription);
        }
示例#29
0
        public void Create(PlayerContext playerContext)
        {
            Validate.NotNull(playerContext);

            if (playersById.ContainsKey(playerContext.PlayerId))
            {
                throw new Exception("The playerId has already been used.");
            }

            GameObject   remotePlayerBody = CloneLocalPlayerBodyPrototype();
            RemotePlayer player           = new RemotePlayer(remotePlayerBody, playerContext);

            PlayerModelDirector playerModelDirector = new PlayerModelDirector(player);

            playerModelDirector
            .AddPing()
            .AddDiveSuit();

            playerModelDirector.Construct();

            playersById.Add(player.PlayerId, player);
        }
示例#30
0
        public async Task GenerateRandomizedDataForGenericBank(GenerateDataDTO dto)
        {
            var bankAccount = await _bankAccountRepository.GetById(dto.BankAccountId);

            Validate.NotNull(bankAccount);
            Validate.IsTrue(bankAccount.Code == BankCode.GENERICBANK.Value, "Access Denied");

            Validate.IsTrue(bankAccount.UserId == dto.UserId, "Access Denied");

            var fakeTransactions = new Faker <Transaction>()
                                   .RuleFor(t => t.BankAccountId, dto.BankAccountId)
                                   .RuleFor(t => t.Date, f => new DateTime(dto.Year, dto.Month, f.Random.Int(1, 27)))
                                   .RuleFor(t => t.Category, f => f.PickRandom <Category>())
                                   .RuleFor(t => t.Amount, f => f.Finance.Amount())
                                   .RuleFor(t => t.Origin, f => f.Company.CompanyName())
                                   .RuleFor(t => t.Metadata, f => $"GenericBank_{Guid.NewGuid()}")
                                   .Generate(dto.Quantity);

            _transactionRepository.InsertRange(fakeTransactions);

            Validate.IsTrue(await _uow.CommitAsync(), "Ocorreu um problema na criação das transações");
        }