protected IDictionary <Type, IList <IObjRelation> > BucketSortObjRels(IList <IObjRelation> orisToLoad) { IDictionary <Type, IList <IObjRelation> > sortedIObjRefs = new Dictionary <Type, IList <IObjRelation> >(); for (int i = orisToLoad.Count; i-- > 0;) { IObjRelation orelToLoad = orisToLoad[i]; Type typeOfContainerBO = orelToLoad.RealType; IEntityMetaData metaData = EntityMetaDataProvider.GetMetaData(typeOfContainerBO); Member relationMember = metaData.GetMemberByName(orelToLoad.MemberName); Type type = relationMember.ElementType; IList <IObjRelation> objRefs = DictionaryExtension.ValueOrDefault(sortedIObjRefs, type); if (objRefs == null) { objRefs = new List <IObjRelation>(); sortedIObjRefs.Add(type, objRefs); } objRefs.Add(orelToLoad); } return(sortedIObjRefs); }
/// <summary> /// Records event with parameters /// </summary> /// <param name="area">Telemetry area name such as 'Toolbox'.</param> /// <param name="eventName">Event name.</param> /// <param name="parameters"> /// Either string/object dictionary or anonymous /// collection of string/object pairs. /// </param> public void ReportEvent(string area, string eventName, object parameters = null) { if (string.IsNullOrEmpty(area)) { throw new ArgumentException(nameof(area)); } if (string.IsNullOrEmpty(eventName)) { throw new ArgumentException(nameof(eventName)); } string completeEventName = MakeEventName(area, eventName); if (parameters == null) { this.TelemetryRecorder.RecordEvent(completeEventName); } else if (parameters is string) { this.TelemetryRecorder.RecordEvent(completeEventName, parameters as string); } else { IDictionary <string, object> dict = DictionaryExtension.FromAnonymousObject(parameters); IDictionary <string, object> dictWithPrefix = new Dictionary <string, object>(); foreach (KeyValuePair <string, object> kvp in dict) { if (string.IsNullOrEmpty(kvp.Key)) { throw new ArgumentException("parameterName"); } dictWithPrefix[this.PropertyNamePrefix + area.ToString() + "." + kvp.Key] = kvp.Value ?? string.Empty; } this.TelemetryRecorder.RecordEvent(completeEventName, dictWithPrefix); } }
public IList <IObjRef> GetChangeRefs(Type type) { if (typeToOriDict != null) { return(DictionaryExtension.ValueOrDefault(typeToOriDict, type)); } typeToOriDict = new Dictionary <Type, IList <IObjRef> >(); for (int a = AllChangeORIs.Count; a-- > 0;) { IObjRef ori = AllChangeORIs[a]; Type realType = ori.RealType; IList <IObjRef> modList = DictionaryExtension.ValueOrDefault(typeToOriDict, realType); if (modList == null) { modList = new List <IObjRef>(); typeToOriDict.Add(realType, modList); } modList.Add(ori); } return(DictionaryExtension.ValueOrDefault(typeToOriDict, type)); }
public IList <IChangeContainer> GetChanges(Type type) { if (typeToModDict != null) { return(DictionaryExtension.ValueOrDefault(typeToModDict, type)); } typeToModDict = new Dictionary <Type, IList <IChangeContainer> >(); for (int a = AllChanges.Count; a-- > 0;) { IChangeContainer changeContainer = AllChanges[a]; Type realType = changeContainer.Reference.RealType; IList <IChangeContainer> modList = DictionaryExtension.ValueOrDefault(typeToModDict, realType); if (modList == null) { modList = new List <IChangeContainer>(); typeToModDict.Add(realType, modList); } modList.Add(changeContainer); } return(DictionaryExtension.ValueOrDefault(typeToModDict, type)); }
public IDictionary ReadDictionaryBB() { if (_readStream.ShiftRight <bool>()) { var length = _readStream.ShiftRight <ushort>(); var keyTypeCode = (TypeCode)_readStream.ShiftRight <byte>(); var valueTypeCode = (TypeCode)_readStream.ShiftRight <byte>(); var dicts = DictionaryExtension.MakeDictionary( keyTypeCode.GetBaseType(), valueTypeCode.GetBaseType()); for (var i = 0; i < length; i++) { dicts.Add(Read(), Read()); } return(dicts); } return(null); }
protected IDictionary <Type, ISet <IObjectFuture> > BucketSortObjectFutures(IList <IObjectCommand> objectCommands) { IDictionary <Type, ISet <IObjectFuture> > sortedObjectFutures = new Dictionary <Type, ISet <IObjectFuture> >((int)(objectCommands.Count / 0.75)); for (int i = 0, size = objectCommands.Count; i < size; i++) { IObjectCommand objectCommand = objectCommands[i]; IObjectFuture objectFuture = objectCommand.ObjectFuture; if (objectFuture != null) { Type type = objectFuture.GetType(); ISet <IObjectFuture> objectFutures = DictionaryExtension.ValueOrDefault(sortedObjectFutures, type); if (objectFutures == null) { objectFutures = new HashSet <IObjectFuture>(); sortedObjectFutures.Add(type, objectFutures); } objectFutures.Add(objectFuture); } } return(sortedObjectFutures); }
/// <summary> /// Records event with parameters /// </summary> public void RecordEvent(string eventName, object parameters = null) { if (this.IsEnabled) { TelemetryEvent telemetryEvent = new TelemetryEvent(eventName); if (parameters != null) { var stringParameter = parameters as string; if (stringParameter != null) { telemetryEvent.Properties["Value"] = stringParameter; } else { IDictionary <string, object> dict = DictionaryExtension.FromAnonymousObject(parameters); foreach (KeyValuePair <string, object> kvp in dict) { telemetryEvent.Properties[kvp.Key] = kvp.Value; } } } _session.PostEvent(telemetryEvent); } }
/// <summary> /// Gets called by the ObjectCopierState on custom / default behavior switches /// </summary> internal T CloneRecursive <T>(T source, ObjectCopierState ocState) { // Don't clone a null object or immutable objects. Return the identical reference in these cases if (source == null || ImmutableTypeSet.IsImmutableType(source.GetType())) { return(source); } Type objType = source.GetType(); IdentityDictionary <Object, Object> objectToCloneDict = ocState.objectToCloneDict; Object clone = DictionaryExtension.ValueOrDefault(ocState.objectToCloneDict, source); if (clone != null) { // Object has already been cloned. Cycle detected - we are finished here return((T)clone); } if (objType.IsArray) { return((T)CloneArray(source, ocState)); } if (source is IEnumerable && !(source is String)) { return((T)CloneCollection(source, ocState)); } // Check whether the object will be copied by custom behavior IObjectCopierExtension extension = extensions.GetExtension(objType); if (extension != null) { clone = extension.DeepClone(source, ocState); objectToCloneDict.Add(source, clone); return((T)clone); } // Copy by default behavior return((T)CloneDefault(source, ocState)); }
public IList <ILoadContainer> GetEntities(IList <IObjRef> orisToLoad) { readLock.Lock(); try { List <ILoadContainer> loadContainers = new List <ILoadContainer>(); for (int a = orisToLoad.Count; a-- > 0;) { IObjRef oriToLoad = orisToLoad[a]; ILoadContainer loadContainer = DictionaryExtension.ValueOrDefault(refToObjectDict, oriToLoad); if (loadContainer != null) { loadContainers.Add(loadContainer); } } return(loadContainers); } finally { readLock.Unlock(); } }
private IEnumerator SendingMail() { yield return(new WaitForSeconds(2)); UIEmail emailPanel = DictionaryExtension.TryGet <UIPanelType, BasePanel>(UIManager.Instance.PanelDict, UIPanelType.Email) as UIEmail; emailPanel.SetInputEmpty(); switch (Global.returnCode) { case ReturnCode.Success: UIManager.Instance.PopPanel(); UIManager.Instance.PopPanel(); UIManager.Instance.PopPanel(); UIManager.Instance.PushPanel(UIPanelType.Success); break; case ReturnCode.Failure: UIManager.Instance.PopPanel(); UIManager.Instance.PopPanel(); UIManager.Instance.PushPanel(UIPanelType.Failure); break; } }
public bool ContainsKey(K key) { int hashKey = key.GetHashCode(); List <WeakReference> list = DictionaryExtension.ValueOrDefault(dic, hashKey); if (list == null) { return(false); } for (int a = list.Count; a-- > 0;) { WeakReference p = list[a]; Object target = p.Target; if (target == null) { continue; } if (AreKeysEqual((K)target, key)) { return(true); } } return(false); }
public IObjRef GetCreateObjRef(Object obj, MergeHandle mergeHandle) { if (obj == null) { return(null); } IObjRef ori = null; IDictionary <Object, IObjRef> objToOriDict = mergeHandle != null ? mergeHandle.objToOriDict : null; if (objToOriDict != null) { ori = DictionaryExtension.ValueOrDefault(objToOriDict, obj); } if (ori != null) { return(ori); } if (obj is IObjRef) { return((IObjRef)obj); } if (!(obj is IEntityMetaDataHolder)) { return(null); } IEntityMetaData metaData = ((IEntityMetaDataHolder)obj).Get__EntityMetaData(); Object keyValue; if (obj is AbstractCacheValue) { keyValue = ((AbstractCacheValue)obj).Id; } else { keyValue = metaData.IdMember.GetValue(obj, false); } if (keyValue == null || mergeHandle != null && mergeHandle.HandleExistingIdAsNewId) { IDirectObjRef dirOri = new DirectObjRef(metaData.EntityType, obj); if (keyValue != null) { dirOri.Id = keyValue; } ori = dirOri; } else { Object version; if (obj is AbstractCacheValue) { version = ((AbstractCacheValue)obj).Version; } else { Member versionMember = metaData.VersionMember; version = versionMember != null?versionMember.GetValue(obj, true) : null; } ori = ObjRefFactory.CreateObjRef(metaData.EntityType, ObjRef.PRIMARY_KEY_INDEX, keyValue, version); } if (objToOriDict != null) { objToOriDict.Add(obj, ori); IDictionary <IObjRef, Object> oriToObjDict = mergeHandle != null ? mergeHandle.oriToObjDict : null; if (oriToObjDict != null && !oriToObjDict.ContainsKey(ori)) { oriToObjDict.Add(ori, obj); } } return(ori); }
public Rights MergeRights([NotNull] List <Rights> allRights) { var platformAccesses = allRights.Select(right => right.PlatformAccesses).ToList(); var productAccesses = allRights.Select(right => right.ProductAccesses).ToList(); var mergedPlatformAccesses = DictionaryExtension.MergeDictionaries(platformAccesses, EnumExtension.Max); var mergedProductAccesses = DictionaryExtension.MergeDictionaries(productAccesses, (roles1, roles2) => DictionaryExtension.MergeDictionaries( new List <Dictionary <string, Role> > { roles1, roles2 }, EnumExtension.Max)); return(new Rights(mergedPlatformAccesses, mergedProductAccesses)); }
public Type GetEnhancedType(Type typeToEnhance, String newTypeNamePrefix, IEnhancementHint hint) { Type extendedType = GetEnhancedTypeIntern(typeToEnhance, hint); if (extendedType != null) { return(extendedType); } lock (writeLock) { // Concurrent thread may have been faster extendedType = GetEnhancedTypeIntern(typeToEnhance, hint); if (extendedType != null) { return(extendedType); } if (Log.InfoEnabled) { Log.Info("Enhancing " + typeToEnhance + " with hint: " + hint); } ValueType valueType = DictionaryExtension.ValueOrDefault(typeToExtendedType, typeToEnhance); if (valueType == null) { valueType = new ValueType(); typeToExtendedType.Add(typeToEnhance, valueType); } else { valueType.AddChangeCount(); newTypeNamePrefix += "_O" + valueType.ChangeCount; } List <IBytecodeBehavior> pendingBehaviors = new List <IBytecodeBehavior>(); IBytecodeBehavior[] extensions = bytecodeBehaviorExtensions.GetExtensions(); pendingBehaviors.AddRange(extensions); Type enhancedType; if (pendingBehaviors.Count > 0) { enhancedType = EnhanceTypeIntern(typeToEnhance, newTypeNamePrefix, pendingBehaviors, hint); } else { enhancedType = typeToEnhance; } WeakReference entityTypeR = typeToExtendedType.GetWeakReferenceEntry(typeToEnhance); if (entityTypeR == null) { throw new Exception("Must never happen"); } hardRefToTypes.Add(enhancedType); hardRefToTypes.Add(typeToEnhance); if (TraceDir != null) { LogBytecodeOutput(enhancedType.FullName, BytecodeClassLoader.ToPrintableBytecode(enhancedType)); } else if (Log.DebugEnabled) { // note that this intentionally will only be logged to the console if the traceDir is NOT specified already Log.Debug(BytecodeClassLoader.ToPrintableBytecode(enhancedType)); } try { CheckEnhancedTypeConsistency(enhancedType); } catch (Exception e) { if (Log.ErrorEnabled) { Log.Error(BytecodeClassLoader.ToPrintableBytecode(enhancedType), e); } BytecodeClassLoader.Save(); throw; } WeakReference enhancedEntityTypeR = new WeakReference(enhancedType); valueType.Put(hint, enhancedEntityTypeR); extendedTypeToType.Add(enhancedType, entityTypeR); if (Log.InfoEnabled) { Log.Info("Enhancement finished successfully with type: " + enhancedType); } return(enhancedType); } }
public EynySettingsForm(DictionaryExtension<string, string> configuration) { _configuration = configuration; InitializeComponent(); }
public virtual void DataChanged(IDataChange dataChange, DateTime dispatchTime, long sequenceId) { dataChange = dataChange.Derive(InterestedEntityTypes); if (dataChange.IsEmpty) { return; } ISet <Object> directObjectsToDelete = null; ISet <Type> requestedTypes = new HashSet <Type>(); IDictionary <Type, IEntityMetaData> typeToMetaDataDict = new Dictionary <Type, IEntityMetaData>(); GuiThreadHelper.InvokeInGuiAndWait(delegate() { IList <T> entities = Model.Objects; for (int i = entities.Count; i-- > 0;) { Object entity = entities[i]; requestedTypes.Add(entity.GetType()); } }); IList <IDataChangeEntry> dataChangeEntries = dataChange.Inserts; for (int a = dataChangeEntries.Count; a-- > 0;) { requestedTypes.Add(dataChangeEntries[a].EntityType); } dataChangeEntries = dataChange.Updates; for (int a = dataChangeEntries.Count; a-- > 0;) { requestedTypes.Add(dataChangeEntries[a].EntityType); } dataChangeEntries = dataChange.Deletes; for (int a = dataChangeEntries.Count; a-- > 0;) { requestedTypes.Add(dataChangeEntries[a].EntityType); } IList <IEntityMetaData> metaDatas = EntityMetaDataProvider.GetMetaData(ListUtil.ToList(requestedTypes)); foreach (IEntityMetaData metaData in metaDatas) { typeToMetaDataDict[metaData.EntityType] = metaData; } bool consistsOnlyOfDirectDeletes = false; if (dataChange.Deletes.Count > 0) { consistsOnlyOfDirectDeletes = true; foreach (IDataChangeEntry deleteEntry in dataChange.Deletes) { if (deleteEntry is DirectDataChangeEntry) { if (directObjectsToDelete == null) { directObjectsToDelete = new IdentityHashSet <Object>(); } directObjectsToDelete.Add(((DirectDataChangeEntry)deleteEntry).Entry); } else { consistsOnlyOfDirectDeletes = false; } } } IList <T> interestingEntities = null; Object[] contextInformation = GetContextInformation(); IFilterDescriptor filterDescriptor = GetFilterDescriptor(); IList <ISortDescriptor> sortDescriptors = GetSortDescriptors(); IPagingRequest pagingRequest = GetPagingRequest(); IPagingResponse pagingResponse = null; List <IDataChangeEntry> modifiedEntries = new List <IDataChangeEntry>(); modifiedEntries.AddRange(dataChange.All); if (!consistsOnlyOfDirectDeletes) { interestingEntities = CacheContext.ExecuteWithCache(CacheProvider.GetCurrentCache(), delegate() { ConfigureCacheWithEagerLoads(Cache); if (Refresher is IPagingRefresher <T> ) { interestingEntities = new List <T>(); pagingResponse = ((IPagingRefresher <T>)Refresher).Refresh(modifiedEntries, filterDescriptor, sortDescriptors, pagingRequest, contextInformation); foreach (Object obj in pagingResponse.Result) { interestingEntities.Add((T)obj); } return(interestingEntities); } else { if (filterDescriptor != null || sortDescriptors != null) { contextInformation = new Object[2]; contextInformation[0] = filterDescriptor; contextInformation[1] = sortDescriptors; } return(((IRefresher <T>)Refresher).Refresh(modifiedEntries, contextInformation)); } }); } GuiThreadHelper.InvokeInGuiAndWait(delegate() { IList <T> entities = Model.Objects; ISet <T> entitiesToAdd = null; ISet <T> entitiesToRemove = null; IDictionary <T, T> entitiesToReplace = null; IDictionary <IObjRef, T> oldObjRefToOldEntityMap = null; bool mergeModel = false; if (interestingEntities != null && interestingEntities.Count > 0) { entitiesToAdd = new IdentityHashSet <T>(interestingEntities); entitiesToRemove = new IdentityHashSet <T>(entities); entitiesToReplace = new IdentityDictionary <T, T>(); oldObjRefToOldEntityMap = new Dictionary <IObjRef, T>(); mergeModel = true; } for (int i = entities.Count; i-- > 0;) { T oldEntity = entities[i]; if (directObjectsToDelete != null && directObjectsToDelete.Contains(oldEntity)) { if (entitiesToRemove != null) { entitiesToRemove.Remove(oldEntity); } Model.RemoveAt(i); continue; } Type oldEntityType = ProxyHelper.GetRealType(oldEntity.GetType()); PrimitiveMember idMember = typeToMetaDataDict[oldEntityType].IdMember; Object oldEntityId = idMember.GetValue(oldEntity, false); if (oldEntityId == null) { if (entitiesToRemove != null) { entitiesToRemove.Remove(oldEntity); } // Unpersisted object. This object should not be removed // only because of a background DCE continue; } bool entryRemoved = false; foreach (IDataChangeEntry deleteEntry in dataChange.Deletes) { if (deleteEntry is DirectDataChangeEntry) { continue; } Object id = deleteEntry.Id; if (!EqualsItems(oldEntityType, oldEntityId, deleteEntry.EntityType, id)) { continue; } if (entitiesToRemove != null) { entitiesToRemove.Remove(oldEntity); } Model.RemoveAt(i); entryRemoved = true; break; } if (entryRemoved) { continue; } if (mergeModel) { IObjRef oldObjRef = new ObjRef(oldEntityType, ObjRef.PRIMARY_KEY_INDEX, oldEntityId, null); T existingOldEntity = DictionaryExtension.ValueOrDefault(oldObjRefToOldEntityMap, oldObjRef); if (existingOldEntity == null) { oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity); } else if (!Object.ReferenceEquals(existingOldEntity, oldEntity)) { // Force duplicate key exception oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity); } } } if (oldObjRefToOldEntityMap != null && oldObjRefToOldEntityMap.Count > 0) { IDictionary <IObjRef, T> newObjRefToNewEntityMap = new Dictionary <IObjRef, T>(); for (int a = interestingEntities.Count; a-- > 0;) { T newEntity = interestingEntities[a]; Type newEntityType = ProxyHelper.GetRealType(newEntity.GetType()); PrimitiveMember idMember = typeToMetaDataDict[newEntityType].IdMember; Object newEntityId = idMember.GetValue(newEntity, false); IObjRef newObjRef = new ObjRef(newEntityType, ObjRef.PRIMARY_KEY_INDEX, newEntityId, null); newObjRefToNewEntityMap.Add(newObjRef, newEntity); } DictionaryExtension.Loop(oldObjRefToOldEntityMap, delegate(IObjRef objRef, T oldEntity) { T newEntity = DictionaryExtension.ValueOrDefault(newObjRefToNewEntityMap, objRef); if (newEntity == null) { // Nothing to do if current oldEntity has no corresponding newEntity return; } entitiesToAdd.Remove(newEntity); if (!Object.ReferenceEquals(oldEntity, newEntity) && (dataChange.IsLocalSource || !(oldEntity is IDataObject) || !((IDataObject)oldEntity).ToBeUpdated)) { entitiesToReplace[oldEntity] = newEntity; } entitiesToRemove.Remove(oldEntity); }); } if (mergeModel) { for (int a = entities.Count; a-- > 0;) { T item = entities[a]; if (entitiesToRemove.Contains(item)) { Model.RemoveAt(a); continue; } T replacingItem = DictionaryExtension.ValueOrDefault(entitiesToReplace, item); if (replacingItem != null) { Model.Replace(a, replacingItem); continue; } } IEnumerator <T> enumerator = entitiesToAdd.GetEnumerator(); while (enumerator.MoveNext()) { T entityToAdd = enumerator.Current; Model.Add(entityToAdd); } if (hasPagedViewModel) { UpdatePagingInformation(pagingResponse); } UpdateAfterDCE(); } }); }
public Type GetMemberType(String memberName) { return(DictionaryExtension.ValueOrDefault(memberTypes, memberName)); }
public Member GetMemberByName(String memberName) { return(DictionaryExtension.ValueOrDefault(nameToMemberDict, memberName)); }
public virtual void AfterPropertiesSet(IBeanContextFactory beanContextFactory) { ParamChecker.AssertNotNull(RevertChangesHelper, "RevertChangesHelper"); ParamChecker.AssertNotNull(SharedData, "SharedData"); ParamChecker.AssertNotNull(SharedDataHandOnExtendable, "SharedDataHandOnExtendable"); //TODO: inject Uri as bean #if SILVERLIGHT Uri uri = HtmlPage.Document.DocumentUri; #else Uri uri = null; if (uri == null) { throw new NotSupportedException("This code has to be compatible with .NET first"); } #endif ISet <String> allBeanNames = new HashSet <String>(); if (BeansToConsume != null) { allBeanNames.UnionWith(BeansToConsume.Keys); } IDictionary <String, IModelContainer> data = null; if (Token != null) { data = SharedData.Read(Token); } if (data == null) { // Clear token to suppress handsOn in afterStarted() Token = null; data = new Dictionary <String, IModelContainer>(); } IModelMultiContainer <Uri> uriList = (IModelMultiContainer <Uri>)DictionaryExtension.ValueOrDefault(data, SourceUriBeanName); if (uriList != null) { //Url-list is avaliable uriList.Values.Add(uri); } allBeanNames.UnionWith(data.Keys); if (!allBeanNames.Contains(SourceUriBeanName)) { //Url-list is not avaliable beanContextFactory.RegisterBean <ModelMultiContainer <Uri> >(SourceUriBeanName).PropertyValue("Value", uri); } IdentityHashSet <Object> allProvidedBusinessObjects = new IdentityHashSet <Object>(); foreach (String nameInOwnContext in allBeanNames) { //Proecess the input IModelContainer dataContainer = DictionaryExtension.ValueOrDefault(data, nameInOwnContext); if (dataContainer != null) { if (dataContainer is IModelMultiContainer) { IEnumerable businessObjects = ((IModelMultiContainer)dataContainer).ValuesData; if (businessObjects != null) { allProvidedBusinessObjects.AddAll(businessObjects.Cast <object>()); } } else if (dataContainer is IModelSingleContainer) { Object businessObject = ((IModelSingleContainer)dataContainer).ValueData; if (businessObject != null) { allProvidedBusinessObjects.Add(businessObject); } } //By copying only the data, listeners are unregistered //beanContextFactory.registerBean(name, dataContainer.GetType()).propertyValue("Data", dataContainer.Data); beanContextFactory.RegisterExternalBean(nameInOwnContext, dataContainer); continue; } if (!BeansToConsume.ContainsKey(nameInOwnContext)) { continue; } //Process default-beans String aliasToDefaultBean = BeansToConsume[nameInOwnContext]; if (aliasToDefaultBean == null) { //Mandatory parameter was not present in data throw new Exception("The new Screen has not all mandatory information: \"" + nameInOwnContext + "\" is missing."); } if (!nameInOwnContext.Equals(aliasToDefaultBean)) { beanContextFactory.RegisterAlias(nameInOwnContext, aliasToDefaultBean); } } if (allProvidedBusinessObjects.Count > 0) { IRevertChangesSavepoint savepoint = RevertChangesHelper.CreateSavepoint(allProvidedBusinessObjects); beanContextFactory.RegisterExternalBean(savepoint).Autowireable <IRevertChangesSavepoint>(); } }
public MethodInfo[] getAddRemoveMethods(Type extendableInterface, Object[] arguments, out Object[] linkArguments) { ParamChecker.AssertParamNotNull(extendableInterface, "extendableInterface"); if (arguments == null) { // This is expected to be an .NET event link linkArguments = new Object[1]; return(getAddRemoveMethodsForEvent(extendableInterface)); } linkArguments = createArgumentArray(arguments); int expectedParamCount = arguments.Length + 1; MethodInfo[] addRemoveMethods; KeyItem keyItem = new KeyItem(extendableInterface, null, expectedParamCount); lock (typeToAddRemoveMethodsMapOld) { addRemoveMethods = DictionaryExtension.ValueOrDefault(typeToAddRemoveMethodsMapOld, keyItem); if (addRemoveMethods != null) { return(addRemoveMethods); } } MethodInfo[] methods = extendableInterface.GetMethods(); MethodInfo addMethod = null, removeMethod = null; foreach (MethodInfo method in methods) { ParameterInfo[] paramInfos = method.GetParameters(); if (paramInfos.Length != expectedParamCount) { continue; } String methodName = method.Name.ToLower(); if (methodName.StartsWith("register") || methodName.StartsWith("add")) { bool match = true; for (int a = paramInfos.Length; a-- > 1;) { ParameterInfo paramInfo = paramInfos[a]; Object argument = arguments[a - 1]; if (argument != null && !paramInfo.ParameterType.IsAssignableFrom(argument.GetType())) { match = false; break; } } if (match) { addMethod = method; } } else if (methodName.StartsWith("unregister") || methodName.StartsWith("remove")) { bool match = true; for (int a = paramInfos.Length; a-- > 1;) { ParameterInfo paramInfo = paramInfos[a]; Object argument = arguments[a - 1]; if (argument != null && !paramInfo.ParameterType.IsAssignableFrom(argument.GetType())) { match = false; break; } } if (match) { removeMethod = method; } } } if (addMethod == null || removeMethod == null) { throw new ExtendableException("No extendable methods pair like 'add/remove' or 'register/unregister' found on interface " + extendableInterface.Name + " to add extension signature with exactly " + expectedParamCount + " argument(s)"); } addRemoveMethods = new MethodInfo[] { addMethod, removeMethod }; lock (typeToAddRemoveMethodsMapOld) { if (!typeToAddRemoveMethodsMapOld.ContainsKey(keyItem)) { typeToAddRemoveMethodsMapOld.Add(keyItem, addRemoveMethods); } } return(addRemoveMethods); }
protected MethodInfo FindMethodOnInterface(MethodInfo classMethod) { IDictionary <MethodInfo, MethodInfo> externToInternMethodDict = externToInternMethodDictTL.Value; MethodInfo interfaceMethod = DictionaryExtension.ValueOrDefault(externToInternMethodDict, classMethod); if (interfaceMethod != null) { return(interfaceMethod); } ParameterInfo[] classMethodParams = classMethod.GetParameters(); Type[] classMethodTypes = GetTypes(classMethodParams); List <Type> remainingInterfaces = new List <Type>(); remainingInterfaces.Add(WCFInterfaceType); while (remainingInterfaces.Count > 0 && interfaceMethod == null) { Type currInterface = remainingInterfaces[0]; remainingInterfaces.RemoveAt(0); MethodInfo[] methods = currInterface.GetMethods(); foreach (MethodInfo method in methods) { if (!method.Name.StartsWith(classMethod.Name)) { continue; } String nameSuffix = method.Name.Substring(classMethod.Name.Length); if (!String.IsNullOrEmpty(nameSuffix)) { try { int suffixId = Int32.Parse(nameSuffix); } catch (Exception) { // Intended blank continue; } } // This is a method candidate tested by its name. The question is now how the arguments are typed bool paramFails = false; ParameterInfo[] paramInfos = method.GetParameters(); if (paramInfos.Length != classMethodTypes.Length) { continue; } for (int a = paramInfos.Length; a-- > 0;) { Type parameterType = paramInfos[a].ParameterType; Type classMethodType = classMethodTypes[a]; if (!classMethodType.Equals(parameterType) && !classMethodParams[a].ParameterType.Equals(parameterType)) { paramFails = true; break; } } if (paramFails) { continue; } interfaceMethod = method; break; } if (interfaceMethod == null) { remainingInterfaces.AddRange(currInterface.GetInterfaces()); } } //interfaceMethod = WCFInterfaceType.GetMethod(classMethod.Name, types); if (interfaceMethod == null) { throw new NotSupportedException("Class method: '" + classMethod + "' can not be mapped to a method of interface '" + WCFInterfaceType + "'"); } externToInternMethodDict.Add(classMethod, interfaceMethod); return(interfaceMethod); }
public override void OnInit() { base.OnInit(); place = new UIPlaces(); place.LoadPlace(DictionaryExtension.TryGet <GameFabs, string>(GamefabPathDict, GameFabs.Cube)); }
/// <summary> /// Appends a value to TempData, meant to be displayed on the very _next_ request. /// </summary> /// <param name="tempData"></param> /// <param name="key">key of the value</param> /// <param name="value">The value to be added to the collection</param> public static void Append(this TempDataDictionary tempData, String key, Object value) { DictionaryExtension.Append(tempData, key, value); }
protected MethodInfo[] getAddRemoveMethodsForEvent(Type targetType) { ParamChecker.AssertParamNotNull(targetType, "targetType"); MethodInfo[] addRemoveMethods; EventKeyItem keyItem = new EventKeyItem(targetType, null); lock (typeToAddRemoveMethodsMapOld) { addRemoveMethods = DictionaryExtension.ValueOrDefault(typeToAddRemoveMethodsMapOld, keyItem); if (addRemoveMethods != null) { return(addRemoveMethods); } } MethodInfo[] methods = targetType.GetMethods(); MethodInfo addMethod = null, removeMethod = null; foreach (MethodInfo method in methods) { if (!method.IsSpecialName) { // Look for special methods autogenerated by the 'event' keyword continue; } ParameterInfo[] paramInfos = method.GetParameters(); if (paramInfos.Length != 1) { // The autogenerated methods by the 'event' keyword always have exactly 1 argument continue; } String methodName = method.Name; if (methodName.StartsWith("add_")) { if (addMethod != null) { throw new ExtendableException("Autogenerated event methods not uniquely resolvable. Maybe there are more than exactly 1 members like 'public event <EventType> <EventName>;' on type " + targetType.FullName + "?"); } addMethod = method; } else if (methodName.StartsWith("remove_")) { if (removeMethod != null) { throw new ExtendableException("Autogenerated event methods not uniquely resolvable. Maybe there are more than exactly 1 members like 'public event <EventType> <EventName>;' on type " + targetType.FullName + "?"); } removeMethod = method; } } if (addMethod == null || removeMethod == null) { throw new ExtendableException("No autogenerated event methods found. Looked for a member like 'public event <EventType> <EventName>;' on type " + targetType.FullName); } addRemoveMethods = new MethodInfo[] { addMethod, removeMethod }; lock (typeToAddRemoveMethodsMapOld) { if (!typeToAddRemoveMethodsMapOld.ContainsKey(keyItem)) { typeToAddRemoveMethodsMapOld.Add(keyItem, addRemoveMethods); } } return(addRemoveMethods); }
public Object GetServiceIntern(String serviceName, Type serviceType, SearchType searchType) { String realServiceName = serviceName; bool factoryContentRequest = true, parentOnlyRequest = false; while (true) { if (realServiceName[0] == '&') { realServiceName = realServiceName.Substring(1); factoryContentRequest = false; continue; } else if (realServiceName[0] == '*') { realServiceName = realServiceName.Substring(1); parentOnlyRequest = true; continue; } // No escape character found, realServiceName is now resolved break; } if (realServiceName.Length == 0) { throw new ArgumentException("Bean name '" + serviceName + "' not valid"); } IDictionary <String, String> beanNameToAliasesMap = beanContextFactory.GetAliasToBeanNameMap(); if (beanNameToAliasesMap != null) { String realBeanName = DictionaryExtension.ValueOrDefault(beanNameToAliasesMap, realServiceName); if (realBeanName != null) { realServiceName = realBeanName; serviceName = (factoryContentRequest ? "" : "&") + (parentOnlyRequest ? "*" : "") + realBeanName; } } Object service = null; if (!parentOnlyRequest && !SearchType.PARENT.Equals(searchType) && nameToServiceDict != null) { service = nameToServiceDict.Get(realServiceName); } if (service is IFactoryBean && factoryContentRequest) { Object factoryResult = ((IFactoryBean)service).GetObject(); if (factoryResult == null) { throw new BeanContextInitException("Factory bean '" + serviceName + "' of type " + service.GetType().FullName + " returned null for service type " + serviceType.FullName + ". Possibly a cyclic relationship from the factory to its cascaded dependencies and back"); } service = factoryResult; } else if (service == null && parent != null) { if (parentOnlyRequest) { // Reconstruct factory bean prefix if necessary return(parent.GetService(factoryContentRequest ? "&" + realServiceName : realServiceName, false)); } else if (!SearchType.CURRENT.Equals(searchType)) { return(parent.GetService(serviceName, false)); } } if (service != null && !serviceType.IsAssignableFrom(service.GetType())) { throw new Exception("Bean with name '" + serviceName + "' not assignable to type '" + serviceType.FullName + "'"); } return(service); }
public void RemoveObject(IObjRef objRef) { writeLock.Lock(); try { ILoadContainer deletedContainer = refToObjectDict[objRef]; refToObjectDict.Remove(objRef); Type deletedType = objRef.RealType; IEntityMetaData metaData = EntityMetaDataProvider.GetMetaData(deletedType); if (metaData.TypesRelatingToThis.Length == 0) { return; } ISet <Type> typesRelatingToThis = new HashSet <Type>(metaData.TypesRelatingToThis); DictionaryExtension.Loop(refToObjectDict, delegate(IObjRef key, ILoadContainer value) { if (!typesRelatingToThis.Contains(key.RealType)) { // This object does not refer to instances of deleted type } IEntityMetaData typeRelatingMetaData = EntityMetaDataProvider.GetMetaData(key.RealType); RelationMember[] relationMembers = typeRelatingMetaData.RelationMembers; for (int a = relationMembers.Length; a-- > 0;) { RelationMember relationMember = relationMembers[a]; if (!deletedType.Equals(relationMember.ElementType)) { continue; } IObjRef[] relationsOfMember = value.Relations[a]; if (relationsOfMember.Length == 0) { continue; } bool contains = false; for (int b = relationsOfMember.Length; b-- > 0;) { IObjRef relationOfMember = relationsOfMember[b]; if (objRef.Equals(relationOfMember)) { contains = true; break; } } if (!contains) { continue; } if (relationsOfMember.Length == 1) { value.Relations[a] = ObjRef.EMPTY_ARRAY; continue; } List <IObjRef> newRelationsOfMember = new List <IObjRef>(); for (int b = relationsOfMember.Length; b-- > 0;) { IObjRef relationOfMember = relationsOfMember[b]; if (!objRef.Equals(relationOfMember)) { newRelationsOfMember.Add(relationOfMember); } } value.Relations[a] = newRelationsOfMember.ToArray(); } }); } finally { writeLock.Unlock(); } }
protected void GetData <V, R>(IDictionary <ICacheRetriever, IList <V> > assignedArguments, IList <R> result, GetDataDelegate <V, R> getDataDelegate) { if (ThreadPool == null || assignedArguments.Count == 1) { // Serialize GetEntities() requests DictionaryExtension.Loop(assignedArguments, delegate(ICacheRetriever cacheRetriever, IList <V> arguments) { IList <R> partResult = getDataDelegate.Invoke(cacheRetriever, arguments); foreach (R partItem in partResult) { result.Add(partItem); } }); return; } int remainingResponses = assignedArguments.Count; Exception routedException = null; // Execute CacheRetrievers in parallel DictionaryExtension.Loop(assignedArguments, delegate(ICacheRetriever cacheRetriever, IList <V> arguments) { ThreadPool.Queue(delegate() { try { IList <R> partResult = getDataDelegate.Invoke(cacheRetriever, arguments); lock (result) { foreach (R partItem in partResult) { result.Add(partItem); } } } catch (Exception e) { routedException = e; } finally { lock (result) { remainingResponses--; Monitor.Pulse(result); } } }); }); lock (result) { while (remainingResponses > 0 && routedException == null) { Monitor.Wait(result); } } if (routedException != null) { throw new Exception("Error occured while retrieving entities", routedException); } }
public ITypeInfoItem[] GetMembersOfType(Type type) { return(DictionaryExtension.ValueOrDefault(typeToMemberMap, type)); }
private void Application_Startup(object sender, StartupEventArgs e) { String configFolder = "config"; String fileName = "Minerva.properties"; String filePath = configFolder + "\\" + fileName; IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite(); Stream primaryPropertyStream = null; try { storage.CreateDirectory("config"); primaryPropertyStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, storage); } catch (IsolatedStorageException) { // Intended blank } catch (FileNotFoundException) { // Intended blank } String urlString = "/Minerva.Client;component/" + filePath; StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative)); if (streamResourceInfo == null) { #if DEVELOP urlString = "/Minerva.Client;component/" + configFolder + "/Osthus.properties"; #else urlString = "/Minerva.Client;component/" + configFolder + "/Osthus_Production.properties"; #endif streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative)); } Properties properties = Properties.Application; if (streamResourceInfo != null) { properties.Load(streamResourceInfo.Stream); } String servicePort = DictionaryExtension.ValueOrDefault(e.InitParams, "serviceport"); String serviceHost = DictionaryExtension.ValueOrDefault(e.InitParams, "servicehost"); DictionaryExtension.Loop(e.InitParams, delegate(String key, String value) { properties.Set(key, value); }); if (servicePort != null) { properties[ServiceConfigurationConstants.ServiceHostPort] = servicePort; } if (serviceHost != null) { properties[ServiceConfigurationConstants.ServiceHostName] = serviceHost; } properties.Load(primaryPropertyStream); Properties.System[ServiceWCFConfigurationConstants.TransferObjectsScope] = ".+"; Properties.System[EventConfigurationConstants.PollingActive] = "true"; Properties.System[ServiceConfigurationConstants.NetworkClientMode] = "true"; Properties.System[ServiceConfigurationConstants.GenericTransferMapping] = "false"; Properties.System[ServiceConfigurationConstants.IndependentMetaData] = "false"; properties[ServiceConfigurationConstants.ServiceBaseUrl] = "${" + ServiceConfigurationConstants.ServiceProtocol + "}://" + "${" + ServiceConfigurationConstants.ServiceHostName + "}" + ":" + "${" + ServiceConfigurationConstants.ServiceHostPort + "}" + "${" + ServiceConfigurationConstants.ServicePrefix + "}"; properties[ServiceConfigurationConstants.ServiceProtocol] = "http"; properties[ServiceConfigurationConstants.ServiceHostName] = "localhost."; properties[ServiceConfigurationConstants.ServiceHostPort] = "9080"; properties[ServiceConfigurationConstants.ServicePrefix] = "/helloworld"; LoggerFactory.LoggerType = typeof(De.Osthus.Ambeth.Log.ClientLogger); Log = LoggerFactory.GetLogger(typeof(App), properties); if (Log.InfoEnabled) { ISet <String> allPropertiesSet = properties.CollectAllPropertyKeys(); List <String> allPropertiesList = new List <String>(allPropertiesSet); allPropertiesList.Sort(); Log.Info("Property environment:"); foreach (String property in allPropertiesList) { Log.Info("Property " + property + "=" + properties[property]); } } Type type = storage.GetType(); PropertyInfo propertyInfo = null; while (type != null) { propertyInfo = type.GetProperty("RootDirectory", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public); if (propertyInfo != null) { break; } type = type.BaseType; } AssemblyHelper.RegisterAssemblyFromType(typeof(BytecodeModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBytecodeModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(CacheDataChangeBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(DataChangeBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(EventBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(IocBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(MergeBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(CompositeIdModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(PrivilegeBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(SecurityBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(ServiceBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(MethodDescription)); AssemblyHelper.RegisterAssemblyFromType(typeof(MinervaCoreBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(RESTBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(XmlBootstrapModule)); AssemblyHelper.RegisterAssemblyFromType(typeof(FilterDescriptor)); AssemblyHelper.RegisterAssemblyFromType(typeof(HelloWorldModule)); AssemblyHelper.InitAssemblies("ambeth\\..+", "minerva\\..+"); properties[XmlConfigurationConstants.PackageScanPatterns] = @"De\.Osthus(?:\.Ambeth|\.Minerva)(?:\.[^\.]+)*(?:\.Transfer|\.Model|\.Service)\..+"; properties[CacheConfigurationConstants.FirstLevelCacheType] = "SINGLETON"; properties[CacheConfigurationConstants.OverwriteToManyRelationsInChildCache] = "false"; properties[CacheConfigurationConstants.UpdateChildCache] = "true"; properties[MinervaCoreConfigurationConstants.EntityProxyActive] = "true"; properties[ServiceConfigurationConstants.TypeInfoProviderType] = typeof(MergeTypeInfoProvider).FullName; // Set this to false, to test with mocks (offline) bool Online = true; properties[CacheConfigurationConstants.CacheServiceBeanActive] = Online.ToString(); properties[EventConfigurationConstants.EventServiceBeanActive] = Online.ToString(); properties[MergeConfigurationConstants.MergeServiceBeanActive] = Online.ToString(); properties[SecurityConfigurationConstants.SecurityServiceBeanActive] = Online.ToString(); properties[HelloWorldConfigurationConstants.HelloWorldServiceBeanActive] = Online.ToString(); properties[MergeConfigurationConstants.MergeServiceMockType] = typeof(HelloWorldMergeMock).FullName; //already default: properties[RESTConfigurationConstants.HttpAcceptEncodingZipped] = "true"; //already default: properties[RESTConfigurationConstants.HttpContentEncodingZipped] = "true"; //already default: properties[RESTConfigurationConstants.HttpUseClient] = "true"; IServiceContext bootstrapContext = BeanContextFactory.CreateBootstrap(properties); try { // Create child context and override root context BeanContext = bootstrapContext.CreateService(delegate(IBeanContextFactory bcf) { bcf.RegisterAnonymousBean <MainPageModule>(); bcf.RegisterAnonymousBean(typeof(HelloWorldModule)); AssemblyHelper.HandleTypesFromCurrentDomainWithAnnotation <FrameworkModuleAttribute>(delegate(Type bootstrapModuleType) { //if (!typeof(IInitializingBootstrapMockModule).IsAssignableFrom(bootstrapModuleType)) { if (Log.InfoEnabled) { Log.Info("Autoresolving bootstrap module: '" + bootstrapModuleType.FullName + "'"); } bcf.RegisterAnonymousBean(bootstrapModuleType); } }); bcf.RegisterExternalBean("app", this); }, typeof(RESTBootstrapModule)); FlattenHierarchyProxy.Context = BeanContext; BeanContext.GetService <IThreadPool>().Queue(delegate() { double result = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(5, "hallo"); double result2 = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(6, "hallo"); if (Math.Abs(result - result2) != 1) { throw new Exception("Process execution failed with unexpected result value: " + result + "/" + result2); } Log.Info("" + result); //Type enhancedType = BeanContext.GetService<IBytecodeEnhancer>().GetEnhancedType(typeof(TestEntity), EntityEnhancementHint.HOOK); //TestEntity instance = (TestEntity)Activator.CreateInstance(enhancedType); //instance.Id = 1; //IEntityMetaData metaData = BeanContext.GetService<IEntityMetaDataProvider>().GetMetaData(enhancedType); //IObjRelation result3 = ((IValueHolderContainer)instance).GetSelf("Relation"); //Object targetCache = ((IValueHolderContainer)instance).TargetCache; //((IValueHolderContainer)instance).TargetCache = new ChildCache(); //Console.WriteLine("TestT"); }); SynchronizationContext syncContext = BeanContext.GetService <SynchronizationContext>(); syncContext.Post((object state) => { RootVisual = BeanContext.GetService <UIElement>("mainPage"); }, null); } catch (Exception ex) { if (Log.ErrorEnabled) { Log.Error(ex); } throw; } }
public virtual void AfterStarted(IServiceContext beanContext) { if (Log.InfoEnabled) { IEnumerable <Type> types = FullServiceModelProvider.RegisterKnownTypes(null); #if !SILVERLIGHT SortedList <String, String> sortedTypes = new SortedList <String, String>(); SortedList <String, String> sortedListTypes = new SortedList <String, String>(); foreach (Type type in types) { String name = LogTypesUtil.PrintType(type, true); if (type.IsGenericType) { sortedListTypes.Add(name, name); } else { sortedTypes.Add(name, name); } } Log.Info(sortedTypes.Count + " data types"); Log.Info(sortedListTypes.Count + " collection types"); DictionaryExtension.Loop(sortedTypes, delegate(String key, String value) { Log.Info("Type: " + value); }); DictionaryExtension.Loop(sortedListTypes, delegate(String key, String value) { Log.Info("Type: " + value); }); #else List <String> sortedTypes = new List <String>(); List <String> sortedListTypes = new List <String>(); foreach (Type type in types) { String name = LogTypesUtil.PrintType(type, true); List <String> list; if (type.IsGenericType) { list = sortedListTypes; } else { list = sortedTypes; } bool inserted = false; for (int a = list.Count; a-- > 0;) { String item = list[a]; if (item.CompareTo(name) < 0) { list.Insert(a + 1, name); inserted = true; break; } } if (!inserted) { list.Insert(0, name); } } Log.Info(sortedTypes.Count + " data types"); Log.Info(sortedListTypes.Count + " collection types"); foreach (String value in sortedTypes) { Log.Info("Type: " + value); } foreach (String value in sortedListTypes) { Log.Info("Type: " + value); } #endif } }
public ITypeInfoItem GetMemberByXmlName(String xmlMemberName) { return(DictionaryExtension.ValueOrDefault(nameToXmlMemberDict, xmlMemberName)); }