public ContentControllerMetaData Resolve(Type contentType) { var reflectionUtility = new ReflectionUtility(); foreach (var controller in _controllers.Value) { var layoutAttributes = reflectionUtility.GetAttributesForType<ContentControllerAttribute>(controller); if (layoutAttributes != null) { foreach (var layoutAttribute in layoutAttributes) { if (layoutAttribute.ContentType == contentType) { return new ContentControllerMetaData(controller, layoutAttribute.Action); } } } } var nameMatchingControllerType = _controllers.Value.FirstOrDefault(t => t.Name.Equals(string.Concat(contentType.Name, "Controller"), StringComparison.InvariantCultureIgnoreCase)); if (nameMatchingControllerType == null) { return null; } return new ContentControllerMetaData(nameMatchingControllerType); }
private static List<Type> InitializeTypes() { var contentDataType = typeof(IContentData); var reflectionHelper = new ReflectionUtility(); var contentTypes = reflectionHelper.GetTypesImplementing(contentDataType); return contentTypes; }
static void BuildPlayer() { if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android) { Debug.LogError("请选择 Android 平台后,再次打包!!!"); return; } // 将 meta 设置为 text 模式 if (SerializationMode.ForceText != EditorSettings.serializationMode) { Debug.LogError("请将 Edit->Project Setting->Asset Serialization->Mode 设置项设置为 ForceText"); return; //EditorSettings.serializationMode = SerializationMode.ForceText; } string gplayConfigPath = Application.streamingAssetsPath + "/GPlayConfig.xml"; if (File.Exists(gplayConfigPath)) { File.Delete(gplayConfigPath); } #region 得到需要打包的场景 List <string> buildScenes = new List <string>(); foreach (var buildScene in EditorBuildSettings.scenes) { if (buildScene.enabled) { buildScenes.Add(buildScene.path); } } if (buildScenes.Count == 0) { UnityEngine.SceneManagement.Scene activeScene = EditorSceneManager.GetActiveScene(); if (string.IsNullOrEmpty(activeScene.path)) { //EditorApplication.ExecuteMenuItem("File/BuildSettings"); EditorWindow.GetWindow(ReflectionUtility.GetType("UnityEditor.BuildPlayerWindow"), true, "Build Settings"); Debug.Log("请在BuildSetting中添加要打包的场景"); return; } else { buildScenes.Add(activeScene.path); } } #endregion #region 生成配置文件 if (!Directory.Exists(Application.streamingAssetsPath)) { Directory.CreateDirectory(Application.streamingAssetsPath); } var gplayConfig = new GPlayConfig() { unityVersion = Application.unityVersion }; // 生成资源配置信息 gplayConfig.resConfig = ResourceConfigUtility.Generate(buildScenes); SerializeUtility.XmlSerializeToFile <GPlayConfig>(gplayConfig, Application.streamingAssetsPath + "/GPlayConfig.xml"); AssetDatabase.Refresh(); //processWindow.Close(); #endregion //// 设置为非开发模式 //EditorUserBuildSettings.development = false; //ReflectionUtility.BuildPlayerWithDefaultSettings(true, BuildOptions.ShowBuiltPlayer); //// 删除配置文件 //AssetDatabase.DeleteAsset("Assets/StreamingAssets/GPlayConfig.xml"); #region comment //string path = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", ""); //path = Path.Combine(path, GetBuildFileName()); //BuildOptions options = BuildOptions.None; //if (EditorUserBuildSettings.allowDebugging && EditorUserBuildSettings.development) // options |= BuildOptions.AllowDebugging; //if (EditorUserBuildSettings.development) // options |= BuildOptions.Development; //if (EditorUserBuildSettings.connectProfiler) // options |= BuildOptions.ConnectWithProfiler; //BuildPipeline.BuildPlayer(buildScenes.ToArray(), path, EditorUserBuildSettings.activeBuildTarget, options); #endregion }
public void IsIntegralType_BasicNonIntegralTypes() { Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(float))); Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(double))); Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(decimal))); }
/// <summary> /// Gets the types contained within the specified <paramref name="assembly"/>. /// </summary> /// <param name="assembly">The <see cref="Assembly"/> to search the types from.</param> /// <param name="namespaceFilter">The namespace filter to apply on the types in the <paramref name="assembly"/>.</param> /// <param name="typeFilter">The type filter to apply on the types in the <paramref name="assembly"/>.</param> /// <returns>A sequence of <see cref="Type"/> elements, matching the applied filters, from the specified <paramref name="assembly"/>.</returns> public static IEnumerable <Type> GetAssemblyTypes(this Assembly assembly, string namespaceFilter, Type typeFilter) { return(ReflectionUtility.GetAssemblyTypes(assembly, namespaceFilter, typeFilter)); }
public void IsIntegralType_NullableNonIntegralTypes() { Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(float?))); Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(double?))); Assert.IsFalse(ReflectionUtility.IsIntegralType(typeof(decimal?))); }
public void IsBooleanType_NullableBooleanType() { Assert.IsTrue(ReflectionUtility.IsBooleanType(typeof(bool?))); }
protected override List <Type> FindObjects(bool searchProjectFolder) { return(ReflectionUtility.GetAllTypesThatImplement(_type, true).Where(o => _ignoreTypes.Contains(o) == false).ToList()); }
public override void ProcessClass(Type classType, ClassDefinition classDef) { MethodInfo[] remoteMethods = remoteType.GetMethods(); bool isServer = !classType.IsSubclassOf(typeof(ClientScope)); // create and setup writer ClassDefinition fakeRemoteClass = new ClassDefinition(string.Format("Remote{0}", remoteType.Name)); { fakeRemoteClass.imports.Add("System.Collections.Generic"); fakeRemoteClass.imports.Add("NetworkScopes"); fakeRemoteClass.imports.Add("UnityEngine.Networking"); // add interface sender field fakeRemoteClass.AddField("_netSender", "INetworkSender", false); // add constructor method MethodDefinition ctor = new MethodDefinition(fakeRemoteClass.Name); ctor.IsConstructor = true; ctor.parameters.Add(new ParameterDefinition("netSender", "INetworkSender")); fakeRemoteClass.methods.Add(ctor); // assign it in the body ctor.instructions.AddInstruction("_netSender = netSender;"); } // find remote methods with "Signal" attribute; the SEND methods bool didCreateAnySendMethods = false; foreach (MethodInfo remoteMethod in remoteMethods) { if (ReflectionUtility.ContainsAttribute <Signal>(remoteMethod)) { // create send remote method MethodDefinition fakeMethodDef = CreateSendMethod(remoteMethod); // if method call wasn't found, mark it invalid if (fakeMethodDef == null) { classDef.IsInvalid = true; continue; } // otherwise add it to the list of methods in the inner remote class fakeRemoteClass.methods.Add(fakeMethodDef); // flag that send methods were created to allow the class to be created in a future check didCreateAnySendMethods = true; } } // find local methods with "Signal" attribute; the RECEIVE methods foreach (MethodInfo localMethod in classType.GetMethods()) { if (ReflectionUtility.ContainsAttribute <Signal>(localMethod)) { // create send remote method MethodDefinition localMethodDef = CreateReceiveMethod(localMethod); // if method call wasn't found, mark it invalid if (localMethodDef == null) { classDef.IsInvalid = true; } // otherwise add it to the lsit of methods within the partial class else { classDef.methods.Add(localMethodDef); } } } // add SEND-specific code - ONLY if there's any any send methods generated earlier if (didCreateAnySendMethods) { classDef.classes.Add(fakeRemoteClass); if (isServer) { string peerTypeName = classType.BaseType.GetGenericArguments()[0].FullName; classDef.AddField("_Remote", fakeRemoteClass.Name, false); // send method (single-peer) MethodDefinition sendPeerMethod = new MethodDefinition("SendToPeer"); sendPeerMethod.ReturnType = fakeRemoteClass.Name; sendPeerMethod.parameters.Add(new ParameterDefinition("targetPeer", peerTypeName)); sendPeerMethod.instructions.AddInlineIfCheck("_Remote == null", string.Format("_Remote = new {0}(this);", fakeRemoteClass.Name)); sendPeerMethod.instructions.AddInstruction("TargetPeer = targetPeer;"); sendPeerMethod.instructions.AddInstruction("return _Remote;"); classDef.methods.Add(sendPeerMethod); // reply method (single-peer - last sender) sendPeerMethod = new MethodDefinition("ReplyToPeer"); sendPeerMethod.ReturnType = fakeRemoteClass.Name; sendPeerMethod.instructions.AddInlineIfCheck("_Remote == null", string.Format("_Remote = new {0}(this);", fakeRemoteClass.Name)); sendPeerMethod.instructions.AddInstruction("TargetPeer = SenderPeer;"); sendPeerMethod.instructions.AddInstruction("return _Remote;"); classDef.methods.Add(sendPeerMethod); // send method (multi-peer) sendPeerMethod = new MethodDefinition("SendToPeers"); sendPeerMethod.ReturnType = fakeRemoteClass.Name; sendPeerMethod.parameters.Add(new ParameterDefinition("targetPeerGroup", string.Format("IEnumerable<{0}>", peerTypeName))); sendPeerMethod.instructions.AddInlineIfCheck("_Remote == null", string.Format("_Remote = new {0}(this);", fakeRemoteClass.Name)); sendPeerMethod.instructions.AddInstruction("TargetPeerGroup = targetPeerGroup;"); sendPeerMethod.instructions.AddInstruction("return _Remote;"); classDef.methods.Add(sendPeerMethod); } else { // add the 'Server' property by that type classDef.AddField("_Remote", fakeRemoteClass.Name, false); var prop = classDef.AddProperty("SendToServer", fakeRemoteClass.Name); prop.getterBody = new MethodBodyDefinition(); prop.getterBody.AddInlineIfCheck("_Remote == null", string.Format("_Remote = new {0}(this);", fakeRemoteClass.Name)); prop.getterBody.AddInstruction("return _Remote;"); } } }
public ReflectionUtilityTests() { this.reflectionUtility = new ReflectionUtility(); }
private TResult ApplyScalarMethods <TResult, TDocument>(SolrCompositeQuery compositeQuery, SolrSearchResults <TDocument> processedResults, SolrQueryResults <Dictionary <string, object> > results) { var method = compositeQuery.Methods.First(); object result; switch (method.MethodType) { case QueryMethodType.All: result = true; break; case QueryMethodType.Any: result = processedResults.Any(); break; case QueryMethodType.Count: result = processedResults.Count(); break; case QueryMethodType.ElementAt: if (((ElementAtMethod)method).AllowDefaultValue) { result = processedResults.ElementAtOrDefault(((ElementAtMethod)method).Index); } else { result = processedResults.ElementAt(((ElementAtMethod)method).Index); } break; case QueryMethodType.First: if (((FirstMethod)method).AllowDefaultValue) { result = processedResults.FirstOrDefault(); } else { result = processedResults.First(); } break; case QueryMethodType.Last: if (((LastMethod)method).AllowDefaultValue) { result = processedResults.LastOrDefault(); } else { result = processedResults.Last(); } break; case QueryMethodType.Single: if (((SingleMethod)method).AllowDefaultValue) { result = processedResults.SingleOrDefault(); } else { result = processedResults.Single(); } break; case QueryMethodType.GetResults: var resultList = processedResults.GetSearchHits(); var facets = this.FormatFacetResults(processedResults.GetFacets(), compositeQuery.FacetQueries); result = ReflectionUtility.CreateInstance(typeof(TResult), resultList, processedResults.NumberFound, facets); // Create instance of SearchResults<TDocument> break; case QueryMethodType.GetFacets: result = this.FormatFacetResults(processedResults.GetFacets(), compositeQuery.FacetQueries); break; default: throw new InvalidOperationException("Invalid query method"); } return((TResult)System.Convert.ChangeType(result, typeof(TResult))); }
public ActionResult <Create> Insert([FromBody] Create param) { if (param == null) { param = new Create(); param._message = _localizer["No parameters."]; return(BadRequest(param)); } if (!TryValidateModel(param)) { param._message = _localizer["The input is incorrect."]; return(BadRequest(param)); } try { var storeModel = new Exam(); ReflectionUtility.Model2Model(param, storeModel); storeModel.ExamId = (Guid.NewGuid()).ToString(); //storeModel.ExamCategoryIds = string.Join(",", model.ExamCategoryIds); storeModel.Owner = HttpContext.User.Identity.Name; storeModel.Registed = DateTime.Now; storeModel.Updated = DateTime.Now; storeModel.Version = 1; //登録 _context.Exams.Add(storeModel); //_context.SaveChanges(); if (param.CategoryIds != null) { foreach (var r in param.CategoryIds) { var m = new ExamCategory { ExamCategoryId = (Guid.NewGuid()).ToString(), ExamId = storeModel.ExamId, CategoryId = r.ToString(), Owner = HttpContext.User.Identity.Name, Registed = DateTime.Now, Updated = DateTime.Now, Version = 1 }; //登録 _context.ExamCategories.Add(m); } } _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); return(Ok(param)); } catch (Exception ex) { param._message = _localizer["System error Please inform system personnel.({0})", ex.Message]; return(BadRequest(param)); } }
public ActionResult <Edit> Update([FromBody] Edit param) { if (param == null) { param = new Edit(); param._message = _localizer["No parameters."]; return(BadRequest(param)); } if (!TryValidateModel(param)) { param._message = _localizer["The input is incorrect."]; return(BadRequest(param)); } try { //更新前データを取得する var storeModel = (from a in _context.Exams where a.ExamId.Equals(param.ExamId) select a).FirstOrDefault(); if (storeModel == null) { param._message = _localizer["It has already been deleted."]; return(BadRequest(param)); } if (storeModel.Version != param.Version) { param._message = _localizer["Other people have been updated."]; return(BadRequest(param)); } ReflectionUtility.Model2Model(param, storeModel); storeModel.Updated = DateTime.Now; storeModel.Version += 1; //更新 _context.Exams.Update(storeModel); //_context.SaveChanges(); //更新前データを取得する var ec = from a in _context.ExamCategories where a.ExamId.Equals(param.ExamId) select a; //削除 _context.ExamCategories.RemoveRange(ec); if (param.CategoryIds != null) { foreach (var r in param.CategoryIds) { var m = new ExamCategory { ExamCategoryId = (Guid.NewGuid()).ToString(), ExamId = storeModel.ExamId, CategoryId = r.ToString(), Owner = HttpContext.User.Identity.Name, Registed = DateTime.Now, Updated = DateTime.Now, Version = 1 }; //登録 _context.ExamCategories.Add(m); } } _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); return(Ok(param)); } catch (Exception ex) { param._message = _localizer["System error Please inform system personnel.({0})", ex.Message]; return(BadRequest(param)); } }
public ActionResult <CategoryCrud> Store([FromBody] CategoryCrud param) { if (param == null) { param = new CategoryCrud(); param._message = _localizer["No parameters."]; return(BadRequest(param)); } if (!TryValidateModel(param)) { param._message = _localizer["The input is incorrect."]; return(BadRequest(param)); } //新規の場合 if (param.CategoryId == null || param.CategoryId.Length == 0) { var storeModel = new Category(); ReflectionUtility.Model2Model(param, storeModel); storeModel.CategoryId = (Guid.NewGuid()).ToString(); storeModel.Owner = HttpContext.User.Identity.Name; storeModel.Registed = DateTime.Now; storeModel.Updated = DateTime.Now; storeModel.Version = 1; //登録 _context.Categories.Add(storeModel); _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); } else { var storeModel = (from a in _context.Categories where a.CategoryId.Equals(param.CategoryId) select a).FirstOrDefault(); if (storeModel == null) { param._message = _localizer["It has already been deleted."]; return(BadRequest(param)); } storeModel.CategoryName = param.CategoryName; storeModel.ExamineeId = param.ExamineeId; storeModel.OrderBy = param.OrderBy; storeModel.Updated = DateTime.Now; storeModel.Version += 1; //登録 _context.Categories.Update(storeModel); _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); } //オプション情報取得 var options = (from a in _context.Categories where a.ExamineeId.Equals(param.ExamineeId) orderby a.OrderBy ascending select new { Value = a.CategoryId, Text = a.CategoryName }).ToList(); param.Options["categoryIds"] = options; return(Ok(param)); }
protected override void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(rect, label, property); DropdownAttribute dropdownAttribute = (DropdownAttribute)attribute; object target = PropertyUtility.GetTargetObjectWithProperty(property); object valuesObject = GetValues(property, dropdownAttribute.ValuesName); FieldInfo dropdownField = ReflectionUtility.GetField(target, property.name); if (AreValuesValid(valuesObject, dropdownField)) { if (valuesObject is IList && dropdownField.FieldType == GetElementType(valuesObject)) { // Selected value object selectedValue = dropdownField.GetValue(target); // Values and display options IList valuesList = (IList)valuesObject; object[] values = new object[valuesList.Count]; string[] displayOptions = new string[valuesList.Count]; for (int i = 0; i < values.Length; i++) { object value = valuesList[i]; values[i] = value; displayOptions[i] = value == null ? "<null>" : value.ToString(); } // Selected value index int selectedValueIndex = Array.IndexOf(values, selectedValue); if (selectedValueIndex < 0) { selectedValueIndex = 0; } NaughtyEditorGUI.Dropdown( rect, property.serializedObject, target, dropdownField, label.text, selectedValueIndex, values, displayOptions); } else if (valuesObject is IDropdownList) { // Current value object selectedValue = dropdownField.GetValue(target); // Current value index, values and display options int index = -1; int selectedValueIndex = -1; List <object> values = new List <object>(); List <string> displayOptions = new List <string>(); IDropdownList dropdown = (IDropdownList)valuesObject; using (IEnumerator <KeyValuePair <string, object> > dropdownEnumerator = dropdown.GetEnumerator()) { while (dropdownEnumerator.MoveNext()) { index++; KeyValuePair <string, object> current = dropdownEnumerator.Current; if (current.Value?.Equals(selectedValue) == true) { selectedValueIndex = index; } values.Add(current.Value); if (current.Key == null) { displayOptions.Add("<null>"); } else if (string.IsNullOrWhiteSpace(current.Key)) { displayOptions.Add("<empty>"); } else { displayOptions.Add(current.Key); } } } if (selectedValueIndex < 0) { selectedValueIndex = 0; } NaughtyEditorGUI.Dropdown( rect, property.serializedObject, target, dropdownField, label.text, selectedValueIndex, values.ToArray(), displayOptions.ToArray()); } } else { string message = string.Format("Invalid values with name '{0}' provided to '{1}'. Either the values name is incorrect or the types of the target field and the values field/property/method don't match", dropdownAttribute.ValuesName, dropdownAttribute.GetType().Name); DrawDefaultPropertyAndHelpBox(rect, property, message, MessageType.Warning); } EditorGUI.EndProperty(); }
public ConditionGeoState() : base(ReflectionUtility.GetPropertyName <EvaluationContextBase>(x => x.GeoState)) { }
public void GetItemTypeOfClosedGenericIEnumerable_ArgumentIsIEnumerable() { Assert.That(ReflectionUtility.GetItemTypeOfClosedGenericIEnumerable(typeof(IEnumerable <int>), "x"), Is.SameAs(typeof(int))); Assert.That(ReflectionUtility.GetItemTypeOfClosedGenericIEnumerable(typeof(IEnumerable <IEnumerable <string> >), "x"), Is.SameAs(typeof(IEnumerable <string>))); }
public void GetMethod() { MethodInfo method = ReflectionUtility.GetMethod(() => "x".ToUpper()); Assert.That(method, Is.EqualTo(typeof(string).GetMethod("ToUpper", new Type[0]))); }
/// <summary> /// Create DataTable from entity list. /// </summary> public static DataTable ToDataTable <T>(this IEnumerable <T> source, List <string> propertyOrder = null) { DataTable table = new DataTable(); BindingFlags binding = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty; PropertyReflectionOptions options = PropertyReflectionOptions.IgnoreEnumerable | PropertyReflectionOptions.IgnoreIndexer; Type stringType = typeof(string); List <PropertyInfo> properties = ReflectionUtility.GetProperties <T>(binding, options) .Where(p => p.PropertyType == stringType || !p.PropertyType.IsClass) .ToList(); if (propertyOrder != null) { properties = properties.Where(p => propertyOrder.Contains(p.Name)).ToList(); properties = propertyOrder.Join(properties, k => k, m => m.Name, (k, i) => i) .ToList(); } foreach (PropertyInfo property in properties) { if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { Type nestedNullableType = property.PropertyType.GetGenericArguments()[0]; table.Columns.Add(property.Name, nestedNullableType); } else if (property.PropertyType.IsEnum) { table.Columns.Add(property.Name, typeof(int)); } else { table.Columns.Add(property.Name, property.PropertyType); } } foreach (T item in source) { List <object> rowValues = new List <object>(); for (int i = 0; i < properties.Count; i++) { object propValue = properties[i].GetValue(item, null); if (propValue == null) { rowValues.Add(DBNull.Value); } else if (properties[i].PropertyType.IsEnum) { rowValues.Add((int)propValue); } else { rowValues.Add(propValue); } } table.Rows.Add(rowValues.ToArray()); } return(table); }
public void GetMethod_PropertyAccess() { MethodInfo method = ReflectionUtility.GetMethod(() => "x".Length); Assert.That(method, Is.EqualTo(typeof(string).GetMethod("get_Length", new Type[0]))); }
public GenericSearchResult <Subscription> SearchSubscriptions(SubscriptionSearchCriteria criteria) { var retVal = new GenericSearchResult <Subscription>(); using (var repository = _subscriptionRepositoryFactory()) { var query = repository.Subscriptions; if (!string.IsNullOrEmpty(criteria.Number)) { query = query.Where(x => x.Number == criteria.Number); } else if (criteria.Keyword != null) { query = query.Where(x => x.Number.Contains(criteria.Keyword)); } if (criteria.CustomerId != null) { query = query.Where(x => x.CustomerId == criteria.CustomerId); } if (criteria.Statuses != null && criteria.Statuses.Any()) { query = query.Where(x => criteria.Statuses.Contains(x.Status)); } if (criteria.StoreId != null) { query = query.Where(x => criteria.StoreId == x.StoreId); } if (criteria.StartDate != null) { query = query.Where(x => x.CreatedDate >= criteria.StartDate); } if (criteria.EndDate != null) { query = query.Where(x => x.CreatedDate <= criteria.EndDate); } if (!string.IsNullOrEmpty(criteria.CustomerOrderId)) { var order = _customerOrderService.GetByIds(new[] { criteria.CustomerOrderId }).FirstOrDefault(); if (order != null && !string.IsNullOrEmpty(order.SubscriptionId)) { query = query.Where(x => x.Id == order.SubscriptionId); } else { query = query.Where(x => false); } } if (criteria.OuterId != null) { query = query.Where(x => x.OuterId == criteria.OuterId); } var sortInfos = criteria.SortInfos; if (sortInfos.IsNullOrEmpty()) { sortInfos = new[] { new SortInfo { SortColumn = ReflectionUtility.GetPropertyName <Subscription>(x => x.CreatedDate), SortDirection = SortDirection.Descending } }; } query = query.OrderBySortInfos(sortInfos); retVal.TotalCount = query.Count(); var subscriptionsIds = query.Skip(criteria.Skip) .Take(criteria.Take) .ToArray() .Select(x => x.Id) .ToArray(); //Load subscriptions with preserving sorting order retVal.Results = GetByIds(subscriptionsIds, criteria.ResponseGroup).OrderBy(x => Array.IndexOf(subscriptionsIds, x.Id)).ToArray(); return(retVal); } }
public void GetMethod_InvalidExpression() { ReflectionUtility.GetMethod(() => "x"); }
private ClassDefinition CreateStaticSerializerClass(Type paramType) { string serializerClassName = string.Format("{0}Serializer", paramType.FullName.Replace(".", string.Empty)); // see if it exists in the serializer class ClassDefinition serializerClassDef = NetworkScopeUtility.SerializerClass.classes.Find(cd => cd.Name == serializerClassName); if (serializerClassDef != null) { return(serializerClassDef); } NetworkSerialization serializationAttr = null; if (serializerClassDef == null && (serializationAttr = ReflectionUtility.GetAttribute <NetworkSerialization>(paramType)) != null) { // create and add the serializer class for this type serializerClassDef = new ClassDefinition(serializerClassName); serializerClassDef.IsStatic = true; NetworkScopeUtility.SerializerClass.classes.Add(serializerClassDef); // serializer method { MethodDefinition serializerMethod = new MethodDefinition("NetworkSerialize"); serializerMethod.IsStatic = true; serializerMethod.parameters.Add(new ParameterDefinition("value", paramType)); serializerMethod.parameters.Add(new ParameterDefinition("writer", typeof(UnityEngine.Networking.NetworkWriter))); serializerClassDef.methods.Add(serializerMethod); FieldInfo[] serializeFields; PropertyInfo[] serializeProps; serializationAttr.GetSerializedMembers(paramType, out serializeFields, out serializeProps); if (serializeFields != null) { foreach (FieldInfo field in serializeFields) { if (!field.Name.EndsWith("k__BackingField")) // ignore property backing fields { AddSerializeCode(serializerMethod, string.Format("value.{0}", field.Name), field.FieldType); } } } if (serializeProps != null) { foreach (PropertyInfo prop in serializeProps) { AddSerializeCode(serializerMethod, string.Format("value.{0}", prop.Name), prop.PropertyType); } } } // deserializer method { MethodDefinition serializerMethod = new MethodDefinition("NetworkDeserialize"); serializerMethod.IsStatic = true; serializerMethod.parameters.Add(new ParameterDefinition("value", paramType)); serializerMethod.parameters.Add(new ParameterDefinition("reader", typeof(UnityEngine.Networking.NetworkReader))); serializerClassDef.methods.Add(serializerMethod); FieldInfo[] serializeFields; PropertyInfo[] serializeProps; serializationAttr.GetSerializedMembers(paramType, out serializeFields, out serializeProps); if (serializeFields != null) { foreach (FieldInfo field in serializeFields) { if (!field.Name.EndsWith("k__BackingField")) // ignore property backing fields { AddDeserializeCode(serializerMethod, string.Format("value.{0}", field.Name), field.FieldType, null); } } } if (serializeProps != null) { foreach (PropertyInfo prop in serializeProps) { AddDeserializeCode(serializerMethod, string.Format("value.{0}", prop.Name), prop.PropertyType, null); } } } return(serializerClassDef); } return(null); }
public void GetRuntimeMethodChecked_ExistingMethod_ReturnsMethodInfo() { MethodInfo method = ReflectionUtility.GetRuntimeMethodChecked(typeof(string), "Substring", new[] { typeof(int) }); Assert.That(method, Is.EqualTo(typeof(string).GetMethod("Substring", new[] { typeof(int) }))); }
public void IsBooleanType_BasicBooleanTypes() { Assert.IsTrue(ReflectionUtility.IsBooleanType(typeof(bool))); Assert.IsTrue(ReflectionUtility.IsBooleanType((true).GetType())); Assert.IsTrue(ReflectionUtility.IsBooleanType((false).GetType())); }
public void GetRuntimeMethodChecked_NonExistingMethod_ThrowsInvalidOperationException() { Assert.That( () => ReflectionUtility.GetRuntimeMethodChecked(typeof(string), "Substring", new[] { typeof(double) }), Throws.TypeOf <InvalidOperationException>().With.Message.EqualTo("Method 'Substring (Double)' was not found on type 'System.String'")); }
public void IsNumericType_EnumTypes() { Assert.IsTrue(ReflectionUtility.IsNumericType(typeof(EnumForTesting))); }
/// <summary> /// Get the metadata document as per sync specification for $metadata. /// </summary> /// <returns></returns> private XDocument GetMetadataDocument() { // We only have 1 scope for now. //Note: Currently this is read from the service configuration and * is not allowed anymore for the SetEnableScope method. string scopeName = _configuration.ScopeNames[0]; // Get the type list from the TypeToTableGlobalNameMapping key list. List <Type> typeList = _configuration.TypeToTableGlobalNameMapping.Keys.ToList(); var document = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); // Add Schema node // example: // <Edmx Namespace="http://schemas.microsoft.com/ado/2007/06/edmx"> // <DataServices Namespace="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> // <Schema Namespace="SyncServiceLibUnitTest" // Alias="Self" // xmlns="http://schemas.microsoft.com/ado/2009/08/edm" // xmlns:sync="http://schemas.microsoft.com/sync/2010/03/syncprotocol"> var edmxNode = new XElement(FormatterConstants.EdmxNamespace + "Edmx", new XAttribute("Version", "1.0"), new XAttribute(XNamespace.Xmlns + FormatterConstants.EdmxNsPrefix, FormatterConstants.EdmxNamespace)); var dataservicesNode = new XElement(FormatterConstants.EdmxNamespace + "DataServices", new XAttribute(FormatterConstants.ODataMetadataNamespace + "DataServiceVersion", "2.0"), new XAttribute(XNamespace.Xmlns + FormatterConstants.ODataMetadataNsPrefix, FormatterConstants.ODataMetadataNamespace)); var schemaNode = new XElement("Schema", new XAttribute(FormatterConstants.AtomPubXmlNsPrefix, _baseEdmNamespace), new XAttribute(XNamespace.Xmlns + FormatterConstants.SyncNsPrefix, FormatterConstants.SyncNamespace), new XAttribute("Namespace", _configuration.ServiceTypeNamespace), new XAttribute("Alias", "Self")); // Add entitycontainer node // example: // <EntityContainer Name="scope_name"> var entityContainerNode = new XElement(_baseEdmNamespace + "EntityContainer", new XAttribute("Name", scopeName)); schemaNode.Add(entityContainerNode); // Add each entry as an EntityType node. foreach (var type in typeList) { // Add the type to the entityContainer Node as an EntitySet node // example: // <EntitySet Name="ScheduleItem" EntityType="SyncServiceLibUnitTest.ScheduleItem" /> var entitySetNode = new XElement(_baseEdmNamespace + "EntitySet", new XAttribute("Name", type.Name), new XAttribute("EntityType", type.FullName)); entityContainerNode.Add(entitySetNode); // Create entity type node // example: <EntityType Name="ScheduleItem"> var entityType = new XElement(_baseEdmNamespace + "EntityType", new XAttribute("Name", type.Name)); schemaNode.Add(entityType); // Get the keys from the Key attribute applied on the entity classes. PropertyInfo[] keyList = ReflectionUtility.GetPrimaryKeysPropertyInfoMapping(type); if (keyList.Length > 0) { // create <Key> node var keyNode = new XElement(_baseEdmNamespace + "Key"); foreach (var key in keyList) { // add PropertyRef nodes // example: <PropertyRef Name="ScheduleItemID" /> var propertyRefNode = new XElement(_baseEdmNamespace + "PropertyRef", new XAttribute("Name", key.Name)); keyNode.Add(propertyRefNode); } entityType.Add(keyNode); } PropertyInfo[] entityProperties = ReflectionUtility.GetPropertyInfoMapping(type); foreach (var property in entityProperties) { // Check if the property has a SyncEntityPropertyNullable attribute. // Presence of this attribute indicates that the property is nullable/non-nullable in the underlying data store. // Some data types such as string are nullable in .NET but may or may not be nullable in the data store (such as a // SQL Server table in a database.) bool isNullable = (0 != property.GetCustomAttributes( SyncServiceConstants.SYNC_ENTITY_PROPERTY_NULLABLE_ATTRIBUTE_TYPE, false).ToList().Count); // create Property node // example: // <Property Name="ScheduleItemID" Type="Edm.Guid" Nullable="false" /> var propertyNode = new XElement(_baseEdmNamespace + "Property", new XAttribute("Name", property.Name), new XAttribute("Type", FormatterUtilities.GetEdmType(property.PropertyType)), new XAttribute("Nullable", isNullable)); entityType.Add(propertyNode); } } // Add filter parameter information to the document. if (_configuration.FilterParameters.Count > 0) { // Write the scynscopeparameters node. // example: <sync:SyncScopeParameters> var syncScopeParamsNode = new XElement(FormatterConstants.SyncNamespace + "SyncScopeParameters"); // We only want to add distinct filter parameters. A single parameter may be applied to many tables internally. var distinctFilterParams = new List <string>(); foreach (var filterParameter in _configuration.FilterParameters) { // Continue with the next filter parameter if we already processed the current one. if (distinctFilterParams.Contains(filterParameter.QueryStringKey)) { continue; } distinctFilterParams.Add(filterParameter.QueryStringKey); string edmType = FormatterUtilities.GetEdmType(filterParameter.ValueType); // The 'Name' of the parameter is the query string key configured in the InitializeService method using the // AddFilterParameterConfiguration method. // example: <sync:ScopeParameter Name="userid" Type="Edm.Guid" /> syncScopeParamsNode.Add( new XElement(FormatterConstants.SyncNamespace + "ScopeParameter", new XAttribute("Name", filterParameter.QueryStringKey), new XAttribute("Type", edmType))); } schemaNode.Add(syncScopeParamsNode); } dataservicesNode.Add(schemaNode); edmxNode.Add(dataservicesNode); document.Add(edmxNode); return(document); }
protected List <MappedProperty> GetPropertiesHierarchy(Type propertyType, List <string> parentPropertyNames) { if (parentPropertyNames.Count == 2) { throw new NotImplementedException("More than 1 level of Entity framework owned entities is not supported."); } List <MappedProperty> list = new List <MappedProperty>(); //Include all primitive properties BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; PropertyInfo[] allEntityProperties = propertyType.GetProperties(bindingFlags); List <PropertyInfo> primitiveProperties = allEntityProperties.Where( p => { Type underlying = Nullable.GetUnderlyingType(p.PropertyType); Type property = underlying ?? p.PropertyType; return(property.IsValueType == true || property.IsPrimitive || property == typeof(string)); }) .ToList(); //Exclude ignored properties IEntityType efEntityType = null; if (propertyType == _rootEntityType) { efEntityType = _efRootEntityType; } else { string propertyName = parentPropertyNames[0]; efEntityType = _context.GetOwnedProperty(_efRootEntityType, propertyName); } List <string> efMappedProperties = efEntityType.GetProperties() .Select(x => x.Name) .ToList(); primitiveProperties = primitiveProperties .Where(x => efMappedProperties.Contains(x.Name)) .ToList(); //Return all the rest properties foreach (PropertyInfo supportedProp in primitiveProperties) { List <string> namesHierarchy = parentPropertyNames.ToList(); namesHierarchy.Add(supportedProp.Name); string efDefaultName = ReflectionUtility.ConcatenateEfPropertyName(namesHierarchy); IProperty property = DbContextExtensions.GetPropertyMapping(_context, _rootEntityType, efDefaultName); list.Add(new MappedProperty { PropertyInfo = supportedProp, EfDefaultName = efDefaultName, EfMappedName = property.GetColumnName(), ConfiguredSqlType = property.GetColumnType() }); } //Add complex properties List <MappedProperty> complexProperties = GetComplexProperties(allEntityProperties, parentPropertyNames); list.AddRange(complexProperties); return(list); }
public void GetItemTypeOfClosedGenericIEnumerable_ArgumentImplementsIEnumerable() { Assert.That(ReflectionUtility.GetItemTypeOfClosedGenericIEnumerable(typeof(List <int>), "x"), Is.SameAs(typeof(int))); }
public void CheckTypeIsClosedGenericIEnumerable_ImplementsIEnumerable_DoesNotThrow() { Assert.That(() => ReflectionUtility.CheckTypeIsClosedGenericIEnumerable(typeof(List <int>), "x"), Throws.Nothing); }
public ActionResult <Edit> Store([FromBody] Edit param) { if (param == null) { param = new Edit(); param._message = _localizer["No parameters."]; return(BadRequest(param)); } if (!TryValidateModel(param)) { param._message = _localizer["The input is incorrect."]; return(BadRequest(param)); } //新規の場合 if (param.KintaiId == null) { try { var storeModel = new Kintai(); ReflectionUtility.Model2Model(param, storeModel); //時間の書式統一 storeModel.Sykjk = Hhmmformater(storeModel.Sykjk); storeModel.Tkjk = Hhmmformater(storeModel.Tkjk); storeModel.SykjkDkk = Hhmmformater(storeModel.SykjkDkk); storeModel.TkjkDkk = Hhmmformater(storeModel.TkjkDkk); storeModel.KykJkn = Hhmmformater(storeModel.KykJkn); storeModel.Zgyjkn = Hhmmformater(storeModel.Zgyjkn); storeModel.Zgyjkn36 = Hhmmformater(storeModel.Zgyjkn36); storeModel.KintaiId = (Guid.NewGuid()).ToString(); storeModel.Owner = HttpContext.User.Identity.Name; storeModel.Registed = DateTime.Now; storeModel.Updated = DateTime.Now; storeModel.Version = 1; //登録 _context.Kintais.Add(storeModel); _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); return(Ok(param)); } catch (Exception ex) { param._message = _localizer["System error Please inform system personnel.({0})", ex.Message]; return(BadRequest(param)); } } else { //更新の場合 try { //更新前データを取得する var storeModel = (from a in _context.Kintais where a.KintaiId.Equals(param.KintaiId) select a).FirstOrDefault(); if (storeModel == null) { param._message = _localizer["It has already been deleted."]; return(BadRequest(param)); } if (storeModel.Version != param.Version) { param._message = _localizer["Other people have been updated."]; return(BadRequest(param)); } ReflectionUtility.Model2Model(param, storeModel); //時間の書式統一 storeModel.Sykjk = Hhmmformater(storeModel.Sykjk); storeModel.Tkjk = Hhmmformater(storeModel.Tkjk); storeModel.SykjkDkk = Hhmmformater(storeModel.SykjkDkk); storeModel.TkjkDkk = Hhmmformater(storeModel.TkjkDkk); storeModel.KykJkn = Hhmmformater(storeModel.KykJkn); storeModel.Zgyjkn = Hhmmformater(storeModel.Zgyjkn); storeModel.Zgyjkn36 = Hhmmformater(storeModel.Zgyjkn36); storeModel.Updated = DateTime.Now; storeModel.Version += 1; //更新 _context.Kintais.Update(storeModel); _context.SaveChanges(); ReflectionUtility.Model2Model(storeModel, param); return(Ok(param)); } catch (Exception ex) { param._message = _localizer["System error Please inform system personnel.({0})", ex.Message]; return(BadRequest(param)); } } }