/// <summary> /// This method accepts a day of the week and returns the corresponding date depending on what the preposition is. /// </summary> /// <param name="preposition">The prefix specifying how many weeks to add to the next found day.</param> /// <param name="desiredDay">The required day.</param> /// <returns>Date on which the <var>preposition</var> <var>desiredDay</var> is found.</returns> private static DateTime GetDateFromDay(ContextType preposition, DayOfWeek desiredDay) { DateTime startDate; DateTime todayDate = DateTime.Today; int daysToAdd = GetDaysToAdd(todayDate.DayOfWeek, desiredDay); switch (preposition) { case ContextType.CURRENT: break; case ContextType.NEXT: Logger.Info("preposition is NEXT", "GetDateFromDay::TokenDay"); daysToAdd += 7; break; case ContextType.FOLLOWING: Logger.Info("preposition is FOLLOWING", "GetDateFromDay::TokenDay"); daysToAdd += 14; break; default: Logger.Error("Fell through preposition switch statement.", "GetDateFromDay::TokenDay"); Debug.Assert(false, "Fell through switch statement in GetDateFromDay!"); break; } startDate = todayDate.AddDays(daysToAdd); Logger.Info("Updated startDate", "GetDateFromDay::TokenDay"); return startDate; }
// constructors internal BsonBinaryReaderContext(BsonBinaryReaderContext parentContext, ContextType contextType, int startPosition, int size) { this.parentContext = parentContext; this.contextType = contextType; this.startPosition = startPosition; this.size = size; }
/// <summary> /// Get Configuration data for selected context. /// </summary> /// <param name="context">Context for using.</param> /// <returns></returns> public ISolutionEvents getConfig(ContextType context) { if(configs.ContainsKey(context)) { return configs[context]; } return new SolutionEvents(); }
public void WriteContextInitialization(ContextType contextType) { _transport.SendOperation(OperationCode.SetupContext, new Dictionary<byte, object> { [(byte) OperationParameterCode.ContextType] = contextType }); }
public IFiber GetContext(ContextType contextType) { IFiber fiber = null; switch (contextType) { case ContextType.New: fiber = new PoolFiber(); fiber.Start(); //poolfibers.Add(fiber); break; case ContextType.Gui: //if(formFiber == null) //{ // if (marshaler == null) marshaler = new MarshalingControl(); // formFiber = new FormFiber(marshaler, new BatchAndSingleExecutor()); // formFiber.Start(); //} //fiber = formFiber; fiber = GetStartedGuiFiber(); break; } return fiber; }
internal JsonReaderContext( JsonReaderContext parentContext, ContextType contextType ) { this.parentContext = parentContext; this.contextType = contextType; }
/// <summary> /// Get User-Configuration data for selected context. /// </summary> /// <param name="context">Context for using.</param> /// <returns></returns> public IUserData getUserConfig(ContextType context) { if(userConfigs.ContainsKey(context)) { return userConfigs[context]; } return new UserData(); }
public ParserContext(bool objectsAllowed, LineTypes.Property[] properties, LineTypes.Component[] components, ContextType type) { this.ObjectsAllowed = objectsAllowed; this.Properties = properties; this.Components = components; this.Type = type; }
public NotifierRule(HotItem item, RuleType type, int value, ContextType contextType, INotificationHost host) { this.Host = host; this.Money = new Money(0, 0, value) { Name = "Rule" }; this.Item = item; this.SelectedRuleType = type; this.ContextType = contextType; }
// used by Clone private BsonDocumentReaderContext(BsonDocumentReaderContext parentContext, ContextType contextType, BsonDocument document, BsonArray array, int index) { _parentContext = parentContext; _contextType = contextType; _document = document; _array = array; _index = index; }
// used by Clone private BsonDocumentReaderContext(BsonDocumentReaderContext parentContext, ContextType contextType, BsonDocument document, BsonArray array, int index) { this.parentContext = parentContext; this.contextType = contextType; this.document = document; this.array = array; this.index = index; }
public ChangePasswordController() { _domainDisplayName = ConfigurationManager.AppSettings["domainDisplayName"]; _contextType = (ContextType)Enum.Parse(typeof(ContextType), ConfigurationManager.AppSettings["contextType"], true); _domain = ConfigurationManager.AppSettings["domain"]; _container = ConfigurationManager.AppSettings["container"]; _identityType = (IdentityType)Enum.Parse(typeof(IdentityType), ConfigurationManager.AppSettings["identityType"], true); }
public DurableInstanceContextReplyChannel(ChannelManagerBase channelManager, ContextType contextType, IReplyChannel innerChannel) : base(channelManager, innerChannel) { this.contextType = contextType; this.innerReplyChannel = innerChannel; }
public ContextSpan(int start, int end, Context context, Context parentContext, ContextType type) { Start = start; End = end; Context = context; ParentContext = parentContext; Type = type; }
internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, BsonDocument document ) { this.parentContext = parentContext; this.contextType = contextType; this.document = document; }
// constructors internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, BsonDocument document) { _parentContext = parentContext; _contextType = contextType; _document = document; }
internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, BsonArray array) { _parentContext = parentContext; _contextType = contextType; _array = array; }
internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, string code) { _parentContext = parentContext; _contextType = contextType; _code = code; }
internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, string code ) { this.parentContext = parentContext; this.contextType = contextType; this.code = code; }
// constructors internal BsonBinaryWriterContext( BsonBinaryWriterContext parentContext, ContextType contextType, int startPosition) { _parentContext = parentContext; _contextType = contextType; _startPosition = startPosition; }
internal BsonDocumentWriterContext( BsonDocumentWriterContext parentContext, ContextType contextType, BsonArray array ) { this.parentContext = parentContext; this.contextType = contextType; this.array = array; }
public DurableInstanceContextReplySessionChannel(ChannelManagerBase channelManager, ContextType contextType, IReplySessionChannel innerChannel) : base(channelManager, innerChannel) { this.contextType = contextType; this.innerReplySessionChannel = innerChannel; this.isFirstMessage = true; this.stateLock = new object(); }
internal BsonBinaryWriterContext( BsonBinaryWriterContext parentContext, ContextType contextType, int startPosition ) { this.parentContext = parentContext; this.contextType = contextType; this.startPosition = startPosition; }
public override void ApplyConfiguration(BindingElement bindingElement) { base.ApplyConfiguration(bindingElement); DurableInstanceContextBindingElement typedBindingElement = (DurableInstanceContextBindingElement)bindingElement; this.contextStoreLocation = typedBindingElement.ContextStoreLocation; this.contextType = typedBindingElement.ContextType; }
public static DbContext GetContext(ContextType type) { switch (type) { case ContextType.AdventureWorks2012Context: return new AdventureWorks2012Entities(); default: return null; } }
internal ContextfulExpression( SymbolTable symbols, Expression expression, ContextType contextType ) : base(symbols) { this.Expression = expression; this.ContextType = contextType; this.SetPosition(expression); }
// constructors internal BsonBinaryReaderContext( BsonBinaryReaderContext parentContext, ContextType contextType, int startPosition, int size) { _parentContext = parentContext; _contextType = contextType; _startPosition = startPosition; _size = size; }
public PermissionsProvider(Permissions permissions, ContextType? activeDirectoryContextType = null) { this.permissions = permissions; this.requiredRights = ConsolidateRights(permissions.RequiredRights, permissions.RequiredRoles); this.restrictedRights = ConsolidateRights(permissions.RestrictedRights, permissions.RestrictedRoles); this.requiredRoles = GetManualRoles(permissions.RequiredRoles); this.restrictedRoles = GetManualRoles(permissions.RestrictedRoles); this.requiredActiveDirectoryRoles = GetActiveDirectoryRoles(permissions.RequiredRoles); this.restrictedActiveDirectoryRoles = GetActiveDirectoryRoles(permissions.RestrictedRoles); this.activeDirectoryContextType = activeDirectoryContextType; }
public DurableInstanceContextRequestChannel(ChannelManagerBase channelManager, ContextType contextType, IRequestChannel innerChannel, string contextStoreLocation) : base(channelManager, innerChannel) { this.contextType = contextType; this.innerRequestChannel = innerChannel; this.contextStoreLocation = contextStoreLocation; this.endpointAddress = innerChannel.RemoteAddress; }
Context(ContextType type) { PlatformServices.Initialize (); this.type = type; if (screen_create_context (out handle, type) != 0) { // TODO: read errno to describe problem throw new Exception ("Unable to create screen context"); } screen_request_events (handle); eventDomain = screen_get_domain (); PlatformServices.AddEventHandler (eventDomain, HandleEvent); }
/// <summary> /// Expand a mapped type /// </summary> /// <param name="source"></param> /// <param name="context"></param> /// <param name="includes"></param> /// <param name="visited">todo: describe visited parameter on ExpandDirectObject</param> /// <returns></returns> protected object ExpandDirectObject(object source, ContextType context, IEnumerable <PropertyReference> includes, HashSet <int> visited, Type destinationTypeHint) { visited = UniqueVisit(source, visited); Type sourceType = source.GetType(); // Figure out our destination type -- either one was passed in, we get the default, or try blind expansion. // The more complicated scenario is when we do get a type hint, but really we want to project to a derived version Type destType = destinationTypeHint; if (Mappings.ContainsKey(sourceType)) { // If we do have a mapping but no type hint was provided, use the default target type if (destType == null) { destType = Mappings[sourceType].DefaultDestinationType; } // If we have a type hint but it doesn't exist as an explicit destination type, then // we may need to create a derived class that can be assigned to that type instead. // This occurs if for example you use interfaces as your destination properties, or // polymorphism. else if (!Mappings[sourceType].Destinations.ContainsKey(destType)) { // Try to find a valid destination type that is something we can actually assign to the // requested type hint. destType = Mappings[sourceType].Destinations.Keys.FirstOrDefault(k => destType.GetTypeInfo().IsAssignableFrom(k)); if (destType == null) { throw new InvalidCastException($"Cannot find a mapper from {sourceType} to {destinationTypeHint}"); } } } includes = ConstructIncludes(includes, sourceType, destType); // Attempt to create a projection object we'll map the data into object destinationObject = CreateObjectInContext(context, sourceType, destType); // If the source is a dictionary we need to go through the keys to match the properties // TODO: Add Recursion for dictionaries that may contain lists of the object within if (sourceType.IsConstructedGenericType && sourceType.GetGenericTypeDefinition() == typeof(Dictionary <,>)) { var sourceDict = (Dictionary <string, object>)source; PropertyInfo[] properties = destinationObject.GetType().GetTypeInfo().GetProperties(); foreach (PropertyInfo property in properties) { if (!sourceDict.Any(x => x.Key.Equals(property.Name, StringComparison.OrdinalIgnoreCase))) { continue; } KeyValuePair <string, object> item = sourceDict.First(x => x.Key.Equals(property.Name, StringComparison.OrdinalIgnoreCase)); // Find which property type (int, string, double? etc) the CURRENT property is... Type propertyType = destinationObject.GetType().GetTypeInfo().GetProperty(property.Name).PropertyType; if (item.Value == null && Nullable.GetUnderlyingType(propertyType) != null) { destinationObject.GetType().GetTypeInfo().GetProperty(property.Name).SetValue(destinationObject, null, null); } else { // Fix nullables... Type newType = Nullable.GetUnderlyingType(propertyType) ?? propertyType; // ...and change the type object newA = Convert.ChangeType(item.Value, newType); destinationObject.GetType().GetTypeInfo().GetProperty(property.Name).SetValue(destinationObject, newA, null); } } return(destinationObject); } // Allow any actions to run ahead of mapping foreach (var action in Mappings[sourceType].BeforeExpansion) { action(destinationObject, source, context); } // Ok, we gots ourselves a conflict. // we try to match the source type to a mapped type var projectionConfiguration = Mappings[sourceType].DestinationForType(destType); // Iterate over only the requested properties foreach (var propertyReference in includes) { string propertyName = propertyReference.PropertyName; var translators = projectionConfiguration.Translators; var preparers = Mappings[sourceType].PrepareProperties; // if this property doesn't even exist on the destination object, cry about it var destinationProperty = projectionConfiguration.DestinationType.GetTypeInfo().GetProperty(propertyName); if (destinationProperty == null) { throw new ArgumentOutOfRangeException(propertyName); } // See if there's a propertyPreparer if (preparers.ContainsKey(propertyName)) { preparers[propertyName](destinationObject, destinationProperty, source, context); } // Transform the input value as needed var valueToAssign = GetSourceValue(source, context, propertyReference.PropertyName, translators); /// If authorization indicates this should not in fact be authorized, skip it if (!AuthorizeValue(source, context, valueToAssign)) { continue; } // Attempt to assign the property - this will expand the item if needed if (!SetValueToProperty(valueToAssign, destinationProperty, destinationObject, context, propertyReference, visited)) { // Couldn't map it, but it was explicitly requested, so throw an error throw new InvalidCastException(propertyReference.PropertyName); } } // Allow any actions to run after the mapping /// @Todo should this be in reverse order so we have a nested stack style FILO? foreach (var action in projectionConfiguration.AfterExpansion) { action(destinationObject, source, context); } return(destinationObject); }
public Context buildContext(string name, ContextType contextType, List <FieldNode> localVariables) { Context newContext = new Context(name, contextType, buildFieldsForLocalVariables(localVariables), null, null); return(newContext); }
private Task <IJSHandle> ScheduleRerunnableTaskAsync(Func <IFrameExecutionContext, Task <IJSHandle> > task, ContextType contextType, int?timeout, string title) { var data = _contextData[contextType]; var rerunnableTask = new RerunnableTask(data, task, timeout, title); data.RerunnableTasks.Add(rerunnableTask); if (data.Context != null) { _ = rerunnableTask.RerunAsync(data.Context); } return(rerunnableTask.Task); }
/// <summary> /// Take a complex object, and transfer properties requested into a dictionary /// </summary> /// <param name="source"></param> /// <param name="context"></param> /// <param name="includes"></param> /// <param name="visited"></param> /// <returns></returns> protected Dictionary <string, object> ExpandBlindObject(object source, ContextType context, IEnumerable <PropertyReference> includes, HashSet <int> visited) { visited = UniqueVisit(source, visited); Type sourceType = source.GetType(); includes = ValidateIncludes(includes, sourceType, null); // Attempt to create a projection object we'll map the data into var destinationObject = new Dictionary <string, object>(); MappingDefinition mappingDefinition = null; // Allow any actions to run ahead of mapping if (Mappings.ContainsKey(sourceType)) { foreach (var action in Mappings[sourceType].BeforeExpansion) { action(destinationObject, source, context); } mappingDefinition = Mappings[source.GetType()]; } // Iterate over only the requested properties foreach (var propertyReference in includes) { string propertyName = propertyReference.PropertyName; if (mappingDefinition != null) { var preparers = mappingDefinition.PrepareProperties; // See if there's a propertyPreparer if (preparers.ContainsKey(propertyName)) { preparers[propertyName](destinationObject, null, source, context); } } // Transform the input value as needed object valueToAssign = GetSourceValue(source, context, propertyName, mappingDefinition?.DefaultDestination()?.Translators); /// If authorization indicates this should not in fact be authorized, skip it if (!AuthorizeValue(source, context, valueToAssign)) { continue; } if (WillExpand(valueToAssign)) { valueToAssign = Expand(valueToAssign, context, propertyReference.Children, visited); } destinationObject[propertyName] = valueToAssign; } // Allow any actions to run after the mapping /// @Todo should this be in reverse order so we have a nested stack style FILO? if (Mappings.ContainsKey(sourceType)) { foreach (var action in Mappings[sourceType].DefaultDestination().AfterExpansion) { action(destinationObject, source, context); } } return(destinationObject); }
internal PixScopedEvent(ID3D12CommandQueue *context) { _context = context; _type = ContextType.Queue; }
public virtual async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } //var myUser = UserManager.Users.FirstOrDefault(u => u.UserName == model.Email.GetLogin() || // u.Email == model.Email); //if (myUser != null) //{ // //} if (!model.Email.Contains("@")) { ContextType authenticationType = ContextType.Domain; PrincipalContext principalContext = new PrincipalContext(authenticationType); var userprincipal = UserPrincipal.FindByIdentity(principalContext, model.Email); var identity = userprincipal.Sid.Translate(typeof(NTAccount)).ToString(); model.Email = userprincipal.EmailAddress; //model.Email= model.Email +"@" + identity.GetDomain() + ".com"; } if (!IsValidEmail(model.Email)) { ModelState.AddModelError("", "Invalid email address."); return(View(model)); } var user = await UserManager.FindByEmailAsync(model.Email); if (user != null) { // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: var claims = new Security.Claim.ClaimsManager(); claims.Authenticate(model.Email); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } } else { ModelState.AddModelError("", "Invalid username or password."); } return(View(model)); }
internal JsonReaderContext(JsonReaderContext parentContext, ContextType contextType) { _parentContext = parentContext; _contextType = contextType; }
public void Ctor_MachineAndNonNegotiateContextOptions_ThrowsArgumentException(ContextType contextType, ContextOptions options) { AssertExtensions.Throws <ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options)); AssertExtensions.Throws <ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options, "userName", "password")); }
internal AuthZSet(byte[] userSid, NetCred credentials, ContextOptions contextOptions, string flatUserAuthority, StoreCtx userStoreCtx, object userCtxBase) { this.currentGroup = -1; this.contexts = new Hashtable(); this.localMachineIsDC = null; this.userType = userStoreCtx.OwningContext.ContextType; this.userCtxBase = userCtxBase; this.userStoreCtx = userStoreCtx; this.credentials = credentials; this.contextOptions = contextOptions; this.flatUserAuthority = flatUserAuthority; this.contexts[flatUserAuthority] = userStoreCtx.OwningContext; IntPtr zero = IntPtr.Zero; IntPtr intPtr = IntPtr.Zero; IntPtr zero1 = IntPtr.Zero; try { try { UnsafeNativeMethods.LUID lUID = new UnsafeNativeMethods.LUID(); lUID.low = 0; lUID.high = 0; this.psMachineSid = new AuthZSet.SafeMemoryPtr(Utils.GetMachineDomainSid()); this.psUserSid = new AuthZSet.SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid)); int lastWin32Error = 0; bool flag = UnsafeNativeMethods.AuthzInitializeResourceManager(UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out intPtr); if (!flag) { lastWin32Error = Marshal.GetLastWin32Error(); } else { flag = UnsafeNativeMethods.AuthzInitializeContextFromSid(0, this.psUserSid.DangerousGetHandle(), intPtr, IntPtr.Zero, lUID, IntPtr.Zero, out zero); if (!flag) { lastWin32Error = Marshal.GetLastWin32Error(); } else { int num = 0; flag = UnsafeNativeMethods.AuthzGetInformationFromContext(zero, 2, 0, out num, IntPtr.Zero); if (flag || num <= 0 || Marshal.GetLastWin32Error() != 122) { lastWin32Error = Marshal.GetLastWin32Error(); } else { zero1 = Marshal.AllocHGlobal(num); flag = UnsafeNativeMethods.AuthzGetInformationFromContext(zero, 2, num, out num, zero1); if (!flag) { lastWin32Error = Marshal.GetLastWin32Error(); } else { UnsafeNativeMethods.TOKEN_GROUPS structure = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(zero1, typeof(UnsafeNativeMethods.TOKEN_GROUPS)); int num1 = structure.groupCount; UnsafeNativeMethods.SID_AND_ATTR[] sIDANDATTRArray = new UnsafeNativeMethods.SID_AND_ATTR[num1]; IntPtr intPtr1 = new IntPtr(zero1.ToInt64() + (long)Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - (long)Marshal.SizeOf(typeof(IntPtr))); for (int i = 0; i < num1; i++) { sIDANDATTRArray[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(intPtr1, typeof(UnsafeNativeMethods.SID_AND_ATTR)); intPtr1 = new IntPtr(intPtr1.ToInt64() + (long)Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR))); } this.groupSidList = new SidList(sIDANDATTRArray); } } } } if (flag) { this.psBuffer = new AuthZSet.SafeMemoryPtr(zero1); zero1 = IntPtr.Zero; } else { object[] objArray = new object[1]; objArray[0] = lastWin32Error; throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.AuthZFailedToRetrieveGroupList, objArray)); } } catch (Exception exception1) { Exception exception = exception1; if (this.psBuffer != null && !this.psBuffer.IsInvalid) { this.psBuffer.Close(); } if (this.psUserSid != null && !this.psUserSid.IsInvalid) { this.psUserSid.Close(); } if (this.psMachineSid != null && !this.psMachineSid.IsInvalid) { this.psMachineSid.Close(); } if (exception as DllNotFoundException == null) { if (exception as EntryPointNotFoundException == null) { throw; } else { throw new NotSupportedException(StringResources.AuthZNotSupported, exception); } } else { throw new NotSupportedException(StringResources.AuthZNotSupported, exception); } } } finally { if (zero != IntPtr.Zero) { UnsafeNativeMethods.AuthzFreeContext(zero); } if (intPtr != IntPtr.Zero) { UnsafeNativeMethods.AuthzFreeResourceManager(intPtr); } if (zero1 != IntPtr.Zero) { Marshal.FreeHGlobal(zero1); } } }
/// <summary> /// Fill the specified contextType /// </summary> public ContextFillerAttribute(ContextType type) { contextType = type; }
/// <summary> /// Place this function at path in the specified contextType /// </summary> public ContextEntryAttribute(ContextType type, string path) { contextType = type; contextPath = path; }
/// <summary> /// Fills the contextMenu of the specified contextType with the inputInfo /// </summary> private static void FillContextMenu(NodeEditorInputInfo inputInfo, GenericMenu contextMenu, ContextType contextType) { foreach (KeyValuePair <ContextEntryAttribute, MenuFunctionData> contextEntry in contextEntries) { // Add all registered menu entries for the specified type to the contextMenu if (contextEntry.Key.contextType == contextType) { contextMenu.AddItem(new GUIContent(contextEntry.Key.contextPath), false, contextEntry.Value, inputInfo); } } object[] fillerParams = new object[] { inputInfo, contextMenu }; foreach (KeyValuePair <ContextFillerAttribute, Delegate> contextFiller in contextFillers) { // Let all registered menu fillers for the specified type add their entries to the contextMenu if (contextFiller.Key.contextType == contextType) { contextFiller.Value.DynamicInvoke(fillerParams); } } }
/// <summary> /// Expand a mapped type /// </summary> /// <param name="source"></param> /// <param name="context"></param> /// <param name="includes"></param> /// <param name="visited">todo: describe visited parameter on ExpandDirectObject</param> /// <returns></returns> protected object ExpandDirectObject(object source, ContextType context, IEnumerable <PropertyReference> includes, HashSet <int> visited, Type destinationTypeHint) { visited = UniqueVisit(source, visited); Type sourceType = source.GetType(); // Figure out our destination type -- either one was passed in, we get the default, or try blind expansion. // The more complicated scenario is when we do get a type hint, but really we want to project to a derived version Type destType = destinationTypeHint; if (Mappings.ContainsKey(sourceType)) { // If we do have a mapping but no type hint was provided, use the default target type if (destType == null) { destType = Mappings[sourceType].DefaultDestinationType; } // If we have a type hint but it doesn't exist as an explicit destination type, then // we may need to create a derived class that can be assigned to that type instead. // This occurs if for example you use interfaces as your destination properties, or // polymorphism. else if (!Mappings[sourceType].Destinations.ContainsKey(destType)) { // Try to find a valid destination type that is something we can actually assign to the // requested type hint. destType = Mappings[sourceType].Destinations.Keys.FirstOrDefault(k => destType.GetTypeInfo().IsAssignableFrom(k)); if (destType == null) { throw new InvalidCastException($"Cannot find a mapper from {sourceType} to {destinationTypeHint}"); } } } includes = ValidateIncludes(includes, sourceType, destType); // Attempt to create a projection object we'll map the data into object destinationObject = CreateObjectInContext(context, sourceType, destType); // Allow any actions to run ahead of mapping foreach (var action in Mappings[sourceType].BeforeExpansion) { action(destinationObject, source, context); } // Ok, we gots ourselves a conflict. // we try to match the source type to a mapped type var projectionConfiguration = Mappings[sourceType].DestinationForType(destType); // Iterate over only the requested properties foreach (var propertyReference in includes) { string propertyName = propertyReference.PropertyName; var translators = projectionConfiguration.Translators; var preparers = Mappings[sourceType].PrepareProperties; // if this property doesn't even exist on the destination object, cry about it var destinationProperty = projectionConfiguration.DestinationType.GetTypeInfo().GetProperty(propertyName); if (destinationProperty == null) { throw new ArgumentOutOfRangeException(propertyName); } // See if there's a propertyPreparer if (preparers.ContainsKey(propertyName)) { preparers[propertyName](destinationObject, destinationProperty, source, context); } // Transform the input value as needed var valueToAssign = GetSourceValue(source, context, propertyReference.PropertyName, translators); /// If authorization indicates this should not in fact be authorized, skip it if (!AuthorizeValue(source, context, valueToAssign)) { continue; } // Attempt to assign the property - this will expand the item if needed if (!SetValueToProperty(valueToAssign, destinationProperty, destinationObject, context, propertyReference, visited)) { // Couldn't map it, but it was explicitly requested, so throw an error throw new InvalidCastException(propertyReference.PropertyName); } } // Allow any actions to run after the mapping /// @Todo should this be in reverse order so we have a nested stack style FILO? foreach (var action in projectionConfiguration.AfterExpansion) { action(destinationObject, source, context); } return(destinationObject); }
public static void SavePointerPosition(int pointerId, Vector2 position, IPanel panel, ContextType contextType) { switch (contextType) { case ContextType.Editor: default: s_EditorPointerLocations[pointerId].SetLocation(position, panel); break; case ContextType.Player: s_PlayerPointerLocations[pointerId].SetLocation(position, panel); break; } }
/// <summary> /// Retrieve a value to be assigned to a property on the projection. /// This may mean invoking a translator, retrieving a property, or executing a method. /// </summary> /// <param name="source"></param> /// <param name="context"></param> /// <param name="propertyName"></param> /// <param name="translators"></param> /// <returns></returns> private static object GetSourceValue(object source, ContextType context, string propertyName, Dictionary <string, Func <object, ContextType, object> > translators = null) { object valueToAssign = null; Type sourceType = source.GetType(); var matchingProperty = sourceType.GetTypeInfo().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public); var matchingMethod = sourceType.GetTypeInfo().GetMethod(propertyName, BindingFlags.Instance | BindingFlags.Public); // Check if the value is marked as InternalOnly InternalOnlyAttribute[] attributes = new InternalOnlyAttribute[2]; attributes[0] = matchingProperty?.GetCustomAttribute <InternalOnlyAttribute>(); attributes[1] = matchingMethod?.GetCustomAttribute <InternalOnlyAttribute>(); string[] names = new string[2]; names[0] = matchingProperty?.Name + " property"; names[1] = matchingMethod?.Name + " method"; for (int i = 0; i < attributes.Length; i++) { var internalOnlyAttr = attributes[i]; if (internalOnlyAttr == null) { continue; } if (internalOnlyAttr.ThrowException) { throw new InternalOnlyViolationException( string.Format("Expand: {0} inside {1} class is marked [InternalOnly]", names[i], sourceType.Name)); } return(null); } // if there's a custom entry for this, it gets first crack if (translators != null && translators.ContainsKey(propertyName)) { valueToAssign = translators[propertyName](source, context); } // if there's an existing property on the source, try to blind-assign it else if (matchingProperty != null) { valueToAssign = matchingProperty.GetValue(source); } // If there's a simple method we can call, invoke it and assign the results else if (matchingMethod != null && matchingMethod.ReturnType != null && matchingMethod.ReturnType != typeof(void) && !matchingMethod.GetParameters().Any()) { valueToAssign = matchingMethod.Invoke(source, new object[] { }); } else { // Couldn't map it, but it was explicitly requested, so throw an error throw new InvalidCastException(propertyName); } return(valueToAssign); }
public void Flush1(ContextType contextType, WaitHandle waitHandle) { Flush1(contextType, waitHandle.SafeWaitHandle.DangerousGetHandle()); }
internal PixScopedEvent(ID3D12GraphicsCommandList *context) { _context = context; _type = ContextType.List; }
/// <summary> /// Restore configuration data from backup using specific context. /// </summary> protected void backupRestore(ContextType context) { CfgManager.getConfigFor(context).load(backup.getConfig(context).CloneBySerializationWithType <ISolutionEvents, SolutionEvents>()); CfgManager.getUserConfigFor(context).load(backup.getUserConfig(context).CloneBySerializationWithType <IData, Data>()); }
// constructors internal InternalJsonWriterContext(InternalJsonWriterContext parentContext, ContextType contextType, string indentChars) { _parentContext = parentContext; _contextType = contextType; _indentation = (parentContext == null) ? indentChars : parentContext.Indentation + indentChars; }
protected void ContextTesterEditButton_Click(object sender, EventArgs e) { ContextType contextType = CurrentContextType; EditContext(contextType); }
internal PixScopedEvent(CtorDummy dummy) { _context = null; _type = ContextType.None; }
/// <summary> Requires the command to be invoked in the specified context. </summary> /// <param name="contexts">The type of context the command can be invoked in. Multiple contexts can be specified by ORing the contexts together.</param> /// <example> /// <code language="cs"> /// [Command("secret")] /// [RequireContext(ContextType.DM | ContextType.Group)] /// public Task PrivateOnlyAsync() /// { /// return ReplyAsync("shh, this command is a secret"); /// } /// </code> /// </example> public RequireContextAttribute(ContextType contexts) { Contexts = contexts; }
public override int GetHashCode() { return(ContextType.GetHashCode() + ContextKey.GetHashCode()); }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <param name="queryStream"></param> /// <param name="isFormData"></param> /// <param name="referer"></param> /// <param name="proxy"></param> /// <param name="certPath"></param> /// <param name="certPassword"></param> /// <returns></returns> public static HttpWebRequest BuildWebRequest(string url, Stream queryStream, ContextType isFormData, string referer, string proxy, string certPath = null, string certPassword = null) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "get"; if (!string.IsNullOrEmpty(referer)) { req.Referer = referer; } if (!string.IsNullOrEmpty(proxy)) { req.Proxy = new WebProxy(proxy); } if (!string.IsNullOrEmpty(certPath) && File.Exists(certPath)) { X509Certificate2 cert; var ext = Path.GetExtension(certPath); { switch (ext.ToLower()) { case "hccert": { var base64 = IO.FileHelper.ReadAllText(certPath); var bytes = Serialization.Base64Serialzier.FromBase64String(base64); cert = new X509Certificate2(); cert.Import(bytes); break; } default: { cert = new X509Certificate2(certPath, certPassword); break; } } } req.ClientCertificates.Add(cert); } if (queryStream != null && queryStream.Length > 0) { req.Method = "post"; req.ContentLength = queryStream.Length; InitContentType(isFormData, req); using (var reqStream = req.GetRequestStream()) { if (queryStream.CanSeek) { queryStream.Position = 0; } queryStream.CopyTo(reqStream); reqStream.Flush(); } } return(req); }
/// <summary> /// Clone configuration from specific context into current. /// </summary> /// <param name="from">Clone from this context.</param> public void cloneCfg(ContextType from) { CfgManager.Config.load(CfgManager.getConfigFor(from).Data.CloneBySerializationWithType <ISolutionEvents, SolutionEvents>()); CfgManager.UserConfig.load(CfgManager.getUserConfigFor(from).Data.CloneBySerializationWithType <IData, Data>()); }
public SetContextEvent(ContextType type, AssetType assetType, int assetId) { Type = type; AssetType = assetType; AssetId = assetId; }
/// <summary> /// Updating of deep copies from configuration data using specific context. /// </summary> protected void backupUpdate(ContextType context) { backup.update(CfgManager.getConfigFor(context).Data.CloneBySerializationWithType <ISolutionEvents, SolutionEvents>(), context); backup.update(CfgManager.getUserConfigFor(context).Data.CloneBySerializationWithType <IData, Data>(), context); }
public DemoBaseRepository(IDataBaseUnitOfWork unitOfWork, ContextType contextType) : base(unitOfWork, contextType) { }
/// <summary> /// Given a value, attempt to set it to a property on a destination object. This may involve changing the object, /// such as converting an int to a double, or an int to an int?, or expanding an object into its projection /// </summary> /// <param name="originalValue"></param> /// <param name="destinationProperty"></param> /// <param name="destinationObject"></param> /// <param name="context"></param> /// <param name="propertyReference"></param> /// <param name="visited">todo: describe visited parameter on SetValueToProperty</param> /// <returns></returns> private bool SetValueToProperty(object originalValue, PropertyInfo destinationProperty, object destinationObject, ContextType context, PropertyReference propertyReference, HashSet <int> visited) { // If it is null then just do a direct assignment if (originalValue == null) { destinationProperty.SetValue(destinationObject, null); return(true); } // Try to do an assignment including any conversion needed if (destinationProperty.TrySetValueHandleConvert(destinationObject, originalValue)) { return(true); } if (WillExpand(originalValue)) { IEnumerable <PropertyReference> propertySubReferences = CreatePropertyReferenceList(destinationProperty, propertyReference); var expandedValue = Expand(originalValue, context, propertySubReferences, visited, destinationProperty.PropertyType); if (destinationProperty.TrySetValueHandleConvert(destinationObject, expandedValue)) { return(true); } } return(false); }
/// <summary> /// 对Http地址发起post请求,并直接获取响应对象 /// </summary> /// <returns></returns> public static HttpWebResponse PostResponse(string url, Stream queryStream, ContextType isFormData = ContextType.Unknown, string referer = null, string proxy = null) { HttpWebResponse res = (HttpWebResponse)BuildWebRequest(url, queryStream, isFormData, referer, proxy).GetResponse(); return(res); }