Ejemplo n.º 1
0
        public void Should_TypeId_NotContainNullValue()
        {
            var typeId = TypeId.Double;

            Assert.AreEqual(false, TypeUtil.IsNullValue(typeId));
        }
Ejemplo n.º 2
0
        public void TypeReference(TypeReference type, TypeReferenceContext context)
        {
            if (
                (context != null) &&
                (context.EnclosingType != null)
                )
            {
                if (TypeUtil.TypesAreEqual(type, context.EnclosingType))
                {
                    // Types can reference themselves, so this prevents recursive initialization.
                    if (Stubbed && Configuration.GenerateSkeletonsForStubbedAssemblies.GetValueOrDefault(false))
                    {
                    }
                    else
                    {
                        WriteRaw("$.Type");
                        return;
                    }
                }

                // The interface builder provides helpful shorthand for corlib type references.
                if (type.Scope.Name == "mscorlib" || type.Scope.Name == "CommonLanguageRuntimeLibrary")
                {
                    if (CorlibTypes.Contains(type.FullName))
                    {
                        WriteRaw("$.");
                        WriteRaw(type.Name);
                        return;
                    }
                }
            }

            if (type.FullName == "JSIL.Proxy.AnyType")
            {
                Value("JSIL.AnyType");
                return;
            }
            else if (type.FullName == "JSIL.Proxy.AnyType[]")
            {
                TypeReference(TypeUtil.GetTypeDefinition(type), context);
                Space();
                Comment("AnyType[]");
                return;
            }

            var byref = type as ByReferenceType;
            var gp    = type as GenericParameter;
            var at    = type as ArrayType;

            if (byref != null)
            {
                TypeReferenceInternal(byref, context);
            }
            else if (gp != null)
            {
                TypeReferenceInternal(gp, context);
            }
            else if (at != null)
            {
                TypeReferenceInternal(at, context);
            }
            else
            {
                TypeReferenceInternal(type, context);
            }
        }
Ejemplo n.º 3
0
        public JsonResult DoBaseUserList()
        {
            string text = TypeUtil.ObjectToString(base.Request["cid"]);
            int    num  = TypeUtil.ObjectToInt(base.Request["type"]);

            if (!string.IsNullOrEmpty(text))
            {
                switch (num)
                {
                default:
                    return(Json(new
                    {
                        IsOk = false,
                        Msg = "请选择操作"
                    }));

                case 1:
                    if (user != null)
                    {
                        AdminPermission adminPermission2 = new AdminPermission(user, user.MoudleID);
                        if (!adminPermission2.GetPermission(4L))
                        {
                            return(Json(new
                            {
                                IsOk = false,
                                Msg = "没有权限",
                                Url = "/NoPower/Index"
                            }));
                        }
                    }
                    try
                    {
                        FacadeManage.aidePlatformManagerFacade.ModifyUserNullity(text, true);
                        return(Json(new
                        {
                            IsOk = true,
                            Msg = "冻结成功"
                        }));
                    }
                    catch
                    {
                        return(Json(new
                        {
                            IsOk = false,
                            Msg = "冻结失败"
                        }));
                    }

                case 2:
                    if (user != null)
                    {
                        AdminPermission adminPermission3 = new AdminPermission(user, user.MoudleID);
                        if (!adminPermission3.GetPermission(4L))
                        {
                            return(Json(new
                            {
                                IsOk = false,
                                Msg = "没有权限",
                                Url = "/NoPower/Index"
                            }));
                        }
                    }
                    try
                    {
                        FacadeManage.aidePlatformManagerFacade.ModifyUserNullity(text, false);
                        return(Json(new
                        {
                            IsOk = true,
                            Msg = "解冻成功"
                        }));
                    }
                    catch
                    {
                        return(Json(new
                        {
                            IsOk = false,
                            Msg = "解冻失败"
                        }));
                    }

                case 3:
                {
                    if (user != null)
                    {
                        AdminPermission adminPermission = new AdminPermission(user, user.MoudleID);
                        if (!adminPermission.GetPermission(8L))
                        {
                            return(Json(new
                                {
                                    IsOk = false,
                                    Msg = "没有权限",
                                    Url = "/NoPower/Index"
                                }));
                        }
                    }
                    string userIDList = "WHERE UserID in (" + text + ")";
                    try
                    {
                        FacadeManage.aidePlatformManagerFacade.DeleteUser(userIDList);
                        return(Json(new
                            {
                                IsOk = true,
                                Msg = "删除成功"
                            }));
                    }
                    catch
                    {
                        return(Json(new
                            {
                                IsOk = false,
                                Msg = "删除失败"
                            }));
                    }
                }
                }
            }
            return(Json(new
            {
                IsOk = false,
                Msg = "没有选择操作项"
            }));

IL_0202:
            return(Json(new
            {
                IsOk = false,
                Msg = "没有进行任何操作"
            }));
        }
Ejemplo n.º 4
0
 /// <summary>
 /// 获取.Net Framework数据类型
 /// </summary>
 /// <param name="nativeType"></param>
 /// <returns></returns>
 public override DbType GetDbType(string nativeType)
 {
     return(TypeUtil.OracleDataType2DbType(nativeType));
 }
Ejemplo n.º 5
0
        public void MethodSignature(MethodReference method, MethodSignature signature, TypeReferenceContext context)
        {
            // The signature cache can cause problems inside methods for generic signatures.
            var cached = Configuration.Optimizer.CacheMethodSignatures.GetValueOrDefault(true);

            // We also don't want to use the cache for method definitions in skeletons.
            if (Stubbed && Configuration.GenerateSkeletonsForStubbedAssemblies.GetValueOrDefault(false))
            {
                cached = false;
            }

            if (cached && ((context.InvokingMethod != null) || (context.EnclosingMethod != null)))
            {
                if (TypeUtil.IsOpenType(signature.ReturnType))
                {
                    cached = false;
                }
                else if (signature.ParameterTypes.Any(TypeUtil.IsOpenType))
                {
                    cached = false;
                }
            }

            if (cached)
            {
                WriteRaw("$sig.get");
                LPar();

                Value(signature.ID);
                Comma();
            }
            else
            {
                LPar();

                WriteRaw("new JSIL.MethodSignature");
                LPar();
            }

            var oldSignature = context.SignatureMethod;

            context.SignatureMethod = method;

            try {
                if ((signature.ReturnType == null) || (signature.ReturnType.FullName == "System.Void"))
                {
                    WriteRaw("null");
                }
                else
                {
                    if ((context.EnclosingMethod != null) && !TypeUtil.IsOpenType(signature.ReturnType))
                    {
                        TypeIdentifier(signature.ReturnType as dynamic, context, false);
                    }
                    else
                    {
                        TypeReference(signature.ReturnType, context);
                    }
                }

                Comma();
                OpenBracket(false);

                CommaSeparatedListCore(
                    signature.ParameterTypes, (pt) => {
                    if ((context.EnclosingMethod != null) && !TypeUtil.IsOpenType(pt))
                    {
                        TypeIdentifier(pt as dynamic, context, false);
                    }
                    else
                    {
                        TypeReference(pt, context);
                    }
                }
                    );

                CloseBracket(false);

                if (signature.GenericParameterNames != null)
                {
                    Comma();
                    OpenBracket(false);
                    CommaSeparatedList(signature.GenericParameterNames, context, ListValueType.Primitive);
                    CloseBracket(false);
                }
            } finally {
                context.SignatureMethod = oldSignature;
            }

            RPar();

            if (!cached)
            {
                RPar();
            }
        }
Ejemplo n.º 6
0
 public void GetType_NoThrowOnError()
 {
     Assert.Null(TypeUtil.GetType("Mxyzptlk", throwOnError: false));
 }
        private object ReduceTarget(object triggerArg)
        {
            var targ = _target;

            if (targ is IProxy)
            {
                targ = (targ as IProxy).GetTarget(triggerArg) as UnityEngine.Object;
            }

            switch (_find)
            {
            case FindCommand.Direct:
            {
                object obj = (_configured) ? targ : triggerArg;
                if (obj == null)
                {
                    return(null);
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return(obj);

                case ResolveByCommand.WithTag:
                    return(GameObjectUtil.GetGameObjectFromSource(obj).HasTag(_queryString) ? obj : null);

                case ResolveByCommand.WithName:
                    return(GameObjectUtil.GetGameObjectFromSource(obj).CompareName(_queryString) ? obj : null);

                case ResolveByCommand.WithType:
                    return(ObjUtil.GetAsFromSource(TypeUtil.FindType(_queryString), GameObjectUtil.GetGameObjectFromSource(obj)) != null ? obj : null);
                }
            }
            break;

            case FindCommand.FindParent:
            {
                Transform trans = GameObjectUtil.GetTransformFromSource((_configured) ? targ : triggerArg);
                if (trans == null)
                {
                    return(null);
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return(trans.parent);

                case ResolveByCommand.WithTag:
                    return(trans.FindParentWithTag(_queryString));

                case ResolveByCommand.WithName:
                    return(trans.FindParentWithName(_queryString));

                case ResolveByCommand.WithType:
                {
                    var tp = TypeUtil.FindType(_queryString);
                    foreach (var p in GameObjectUtil.GetParents(trans))
                    {
                        var o = ObjUtil.GetAsFromSource(tp, p);
                        if (o != null)
                        {
                            return(o);
                        }
                    }
                    return(null);
                }
                }
            }
            break;

            case FindCommand.FindInChildren:
            {
                Transform trans = GameObjectUtil.GetTransformFromSource((_configured) ? targ : triggerArg);
                if (trans == null)
                {
                    return(null);
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return((trans.childCount > 0) ? trans.GetChild(0) : null);

                case ResolveByCommand.WithTag:
                    if (trans.childCount > 0)
                    {
                        using (var lst = TempCollection.GetList <Transform>())
                        {
                            GameObjectUtil.GetAllChildren(trans, lst);
                            for (int i = 0; i < lst.Count; i++)
                            {
                                if (lst[i].HasTag(_queryString))
                                {
                                    return(lst[i]);
                                }
                            }
                        }
                    }
                    break;

                case ResolveByCommand.WithName:
                    if (trans.childCount > 0)
                    {
                        return(trans.FindByName(_queryString));
                    }
                    break;

                case ResolveByCommand.WithType:
                    if (trans.childCount > 0)
                    {
                        var tp = TypeUtil.FindType(_queryString);
                        using (var lst = TempCollection.GetList <Transform>())
                        {
                            GameObjectUtil.GetAllChildren(trans, lst);
                            for (int i = 0; i < lst.Count; i++)
                            {
                                var o = ObjUtil.GetAsFromSource(tp, lst[i]);
                                if (o != null)
                                {
                                    return(o);
                                }
                            }
                        }
                    }
                    break;
                }
            }
            break;

            case FindCommand.FindInEntity:
            {
                GameObject entity = GameObjectUtil.GetRootFromSource((_configured) ? targ : triggerArg);
                if (entity == null)
                {
                    return(null);
                }

                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return(entity);

                case ResolveByCommand.WithTag:
                    return(entity.FindWithMultiTag(_queryString));

                case ResolveByCommand.WithName:
                    return(entity.FindByName(_queryString));

                case ResolveByCommand.WithType:
                {
                    var tp = TypeUtil.FindType(_queryString);
                    foreach (var t in GameObjectUtil.GetAllChildrenAndSelf(entity))
                    {
                        var o = ObjUtil.GetAsFromSource(tp, t);
                        if (o != null)
                        {
                            return(o);
                        }
                    }
                    return(null);
                }
                }
            }
            break;

            case FindCommand.FindInScene:
            {
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return(GameObjectUtil.GetGameObjectFromSource((_configured) ? targ : triggerArg));

                case ResolveByCommand.WithTag:
                    return(GameObjectUtil.FindWithMultiTag(_queryString));

                case ResolveByCommand.WithName:
                    return(GameObject.Find(_queryString));

                case ResolveByCommand.WithType:
                    return(ObjUtil.Find(SearchBy.Type, _queryString));
                }
            }
            break;

            case FindCommand.FindEntityInScene:
            {
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    return(GameObjectUtil.GetGameObjectFromSource((_configured) ? targ : triggerArg));

                case ResolveByCommand.WithTag:
                {
                    var e = SPEntity.Pool.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if (e.Current.HasTag(_queryString))
                        {
                            return(e.Current);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    var e = SPEntity.Pool.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if (e.Current.CompareName(_queryString))
                        {
                            return(e.Current);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    var e  = SPEntity.Pool.GetEnumerator();
                    var tp = TypeUtil.FindType(_queryString);
                    while (e.MoveNext())
                    {
                        var o = e.Current.GetComponentInChildren(tp);
                        if (o != null)
                        {
                            return(o);
                        }
                    }
                }
                break;
                }
            }
            break;
            }

            return(null);
        }
        public ExperienceAnalyticsTableControlResponse Get(DateTime dateFrom, DateTime dateTo, string siteName)
        {
            Stopwatch sw = new Stopwatch();

            var    reportData = new ExperienceAnalyticsTableControlData <dynamic>();
            var    count      = 0;
            string cacheKey   = "contactListCache";

            //var reportCache = new Sitecore.Caching.Cache("ReportCache", 1024);
            //reportCache.Add("test", 12)

            try
            {
                sw.Start();
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : STOPWATCH - starts.", this);
                string   connectionString = ConfigurationManager.ConnectionStrings["analytics"].ConnectionString;
                MongoUrl mongoUrl         = new MongoUrl(connectionString);

                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : CONNECTION ESTABLISHED.", this);
                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : SiteName - {siteName}, DateFrom - {dateFrom.ToString("dd-MM-yy")}, DateTo - {dateTo.ToString("dd-MM-yy")}", this);

                var client = new MongoClient(connectionString);

                var database = client.GetServer().GetDatabase(mongoUrl.DatabaseName);

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - database fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                IMongoQuery interactionQuery = null;

                BsonRegularExpression urlFilter1 = "[^/.]/industries/electricity/discover-the-active-grid";
                BsonRegularExpression urlFilter2 = "[^/.]/industries/electricity/discover-the-active-grid/";

                if (string.Equals(siteName, "All", StringComparison.OrdinalIgnoreCase))
                {
                    interactionQuery = Query.And(
                        Query.Or(
                            Query.Matches("Pages.Url.Path", urlFilter1),
                            Query.Matches("Pages.Url.Path", urlFilter2)
                            ),
                        Query.GTE("StartDateTime", new BsonDateTime(dateFrom)),
                        Query.LTE("StartDateTime", new BsonDateTime(dateTo))
                        );
                }
                else
                {
                    interactionQuery = Query.And(
                        Query.Or(
                            Query.Matches("Pages.Url.Path", urlFilter1),
                            Query.Matches("Pages.Url.Path", urlFilter2)
                            ),
                        Query.GTE("StartDateTime", new BsonDateTime(dateFrom)),
                        Query.LTE("StartDateTime", new BsonDateTime(dateTo)),
                        Query.EQ("SiteName", siteName)
                        );
                }

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - search query built in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : BSON Dates = DateFrom - {new BsonDateTime(dateFrom).ToString()}, DateTo - {new BsonDateTime(dateTo).ToString()}", this);

                var interactions = database.GetCollection <Interaction>("Interactions").Find(interactionQuery);
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Interactions Query Executed.", this);

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Interactions fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                var customReportCache = Sitecore.Caching.CacheManager.FindCacheByName("CustomReportCache");
                if (customReportCache == null)
                {
                    customReportCache = new Sitecore.Caching.Cache("CustomReportCache", 1000000);
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Pushing CustomReportCache into Cache.", this);
                }
                else
                {
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Reading CustomReportCache from Cache.", this);
                }
                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - CustomReportCache fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                if (interactions != null && interactions.Any())
                {
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are {interactions.Count().ToString()} filtered interactions ", this);
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Interaction String  - {interactions.ToJson()}", this);
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Interactions found, working on getting contact ids.", this);

                    IMongoQuery contactQuery = null;

                    BsonArray contactidBsonArray = new BsonArray(interactions.Select(x => x.ContactId));
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Contact Id String  - {contactidBsonArray.ToJson()}", this);
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts Ids fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Restart();

                    contactQuery = Query.In("_id", contactidBsonArray);
                    MongoCollection <User> contactsCollection = null;

                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Started working on Contacts.", this);

                    var cachedContacts = customReportCache.GetValue(cacheKey);


                    if (cachedContacts != null)
                    {
                        contactsCollection = (MongoCollection <User>)cachedContacts;
                        //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : {test}", this);

                        //contactsCollection = (MongoCollection<User>)customReportCache.GetValue(cacheKey);
                        Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Reading Contacts from Cache.", this);
                    }
                    else
                    {
                        contactsCollection = database.GetCollection <User>("Contacts");
                        customReportCache.Add(cacheKey, contactsCollection, TypeUtil.SizeOfObject(), DateTime.Now.AddHours(12));
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Pushing Contacts into Cache. Size is {customReportCache.Size}", this);
                    }

                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Restart();

                    var contacts = contactsCollection.Find(contactQuery);
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Contacts Query Executed.", this);

                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts filtered in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Stop();

                    if (contacts != null && contacts.Any())
                    {
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are {contacts.Count().ToString()} filtered contacts ", this);
                        int iteration = 1;
                        foreach (var contact in contacts)
                        {
                            if (!string.IsNullOrEmpty(contact.Personal.FirstName) && !string.IsNullOrEmpty(contact.Personal.Surname) && !string.IsNullOrEmpty(contact.Identifiers.Identifier))
                            {
                                var matchedInteraction = interactions.FirstOrDefault(x => x.ContactId.Equals(contact.id));

                                var item = new
                                {
                                    index          = iteration - 1,
                                    srn            = iteration,
                                    id             = contact.id,
                                    emailid        = contact.Identifiers.Identifier,
                                    fullname       = $"{contact.Personal.FirstName} {contact.Personal.Surname}",
                                    sitename       = matchedInteraction.SiteName,
                                    name           = $"{contact.Personal.FirstName} {contact.Personal.Surname}",
                                    activitydate   = matchedInteraction.EndDateTime.ToString("MM/dd/yyyy HH:mm:ss"),
                                    visitvalue     = matchedInteraction.Value,
                                    filtersitename = siteName
                                };

                                reportData.AddItem(item);
                                iteration++;
                            }
                        }
                    }
                    else
                    {
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are NO filtered contacts ", this);
                    }
                }
                else
                {
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are NO filtered interactions ", this);
                }
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : ACTIVITY COMPLETED", this);
            }
            catch (Exception e)
            {
                Sitecore.Diagnostics.Log.Error($" Custom Visitor Report : {e.Message}", this);
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : ACTIVITY ENDE DUE TO ERROR", this);
            }

            var content = new ExperienceAnalyticsTableControlResponse()
            {
                Data             = reportData,
                TotalRecordCount = count
            };

            return(content);
        }
Ejemplo n.º 9
0
        protected bool IsNullable(TypeReference type)
        {
            var git = TypeUtil.DereferenceType(type) as GenericInstanceType;

            return((git != null) && (git.Name == "Nullable`1"));
        }
Ejemplo n.º 10
0
        public void VisitNode(JSCastExpression ce)
        {
            var currentType = ce.Expression.GetActualType(TypeSystem);
            var targetType  = ce.NewType;

            JSExpression newExpression = null;

            if (targetType.FullName == "System.ValueType")
            {
                var replacement = ce.Expression;
                ParentNode.ReplaceChild(ce, replacement);
                VisitReplacement(replacement);
                return;
            }
            else if (
                TypeUtil.IsIntegralOrEnum(currentType) &&
                (targetType.MetadataType == MetadataType.Char)
                )
            {
                newExpression = JSInvocationExpression.InvokeStatic(
                    JS.fromCharCode, new[] { ce.Expression }, true
                    );
            }
            else if (
                (currentType.MetadataType == MetadataType.Char) &&
                TypeUtil.IsIntegral(targetType)
                )
            {
                newExpression = JSInvocationExpression.InvokeMethod(
                    JS.charCodeAt, ce.Expression, new[] { JSLiteral.New(0) }, true
                    );
            }
            else if (
                IntroduceEnumCasts.IsEnumOrNullableEnum(currentType)
                )
            {
                TypeInfo enumInfo;
                var      isNullable = TypeUtil.IsNullable(currentType);

                if (isNullable)
                {
                    int temp;
                    var git = (GenericInstanceType)TypeUtil.FullyDereferenceType(currentType, out temp);
                    enumInfo = TypeInfo.Get(git.GenericArguments[0]);
                }
                else
                {
                    enumInfo = TypeInfo.Get(currentType);
                }

                if (enumInfo == null)
                {
                    throw new InvalidOperationException("Unable to extract enum type from typereference " + currentType);
                }

                if (targetType.MetadataType == MetadataType.Boolean)
                {
                    newExpression = new JSBinaryOperatorExpression(
                        JSOperator.NotEqual,
                        JSCastExpression.New(ce.Expression, TypeSystem.Int32, TypeSystem, true, true),
                        new JSIntegerLiteral(0, typeof(Int32)),
                        TypeSystem.Boolean
                        );
                }
                else if (TypeUtil.IsNumeric(targetType))
                {
                    if (isNullable)
                    {
                        newExpression = JSIL.ValueOfNullable(
                            ce.Expression
                            );
                    }
                    else if (
                        ce.Expression is JSCastExpression &&
                        (((JSCastExpression)ce.Expression).Expression.GetActualType(TypeSystem).MetadataType == MetadataType.Int64 ||
                         ((JSCastExpression)ce.Expression).Expression.GetActualType(TypeSystem).MetadataType == MetadataType.UInt64)
                        )
                    {
                        newExpression = ce.Expression;
                    }
                    else
                    {
                        newExpression = JSInvocationExpression.InvokeMethod(
                            JS.valueOf(targetType), ce.Expression, null, true
                            );
                    }
                }
                else if (targetType.FullName == "System.Enum")
                {
                    newExpression = ce.Expression;
                }
                else
                {
                    // Debugger.Break();
                }
            }
            else if (
                (targetType.MetadataType == MetadataType.Boolean) &&
                (ce.Expression is JSAsExpression) &&
                ((JSAsExpression)ce.Expression).GetActualType(TypeSystem) is GenericParameter
                )
            {
                // C# expressions such as (t is T) (where T is a generic parameter). See issue #150.
                // Tested with AsWithGenericParameter.cs
                newExpression = new JSBinaryOperatorExpression(
                    JSBinaryOperator.NotEqual,
                    ce.Expression, new JSNullLiteral(currentType),
                    TypeSystem.Boolean
                    );
            }
            else if (
                (targetType.MetadataType == MetadataType.Boolean) &&
                // A cast from Object to Boolean can occur in two forms:
                // An implied conversion, where an object expression is treated as a boolean (logicnot operation, etc).
                //  In this case, we want to do 'obj != null' to make it a boolean.
                // An explicit conversion, where an object expression is unboxed to boolean.
                //  In this case we want to leave it as-is.
                (ce.IsCoercion || (currentType.FullName != "System.Object"))
                )
            {
                newExpression = new JSBinaryOperatorExpression(
                    JSBinaryOperator.NotEqual,
                    ce.Expression, new JSDefaultValueLiteral(currentType),
                    TypeSystem.Boolean
                    );
            }
            else if (
                TypeUtil.IsNumeric(targetType) &&
                TypeUtil.IsNumeric(currentType) &&
                !TypeUtil.TypesAreEqual(targetType, currentType, true)
                )
            {
                if (currentType.MetadataType == MetadataType.Int64)
                {
                    if (targetType.MetadataType == MetadataType.UInt64)
                    {
                        newExpression = JSInvocationExpression
                                        .InvokeMethod(
                            TypeSystem.Int64,
                            new JSFakeMethod("ToUInt64", TypeSystem.UInt64, new TypeReference[] { }, MethodTypeFactory),
                            ce.Expression);
                    }
                    else
                    {
                        newExpression = JSInvocationExpression
                                        .InvokeMethod(
                            TypeSystem.Int64,
                            new JSFakeMethod("ToNumber", targetType, new TypeReference[] { TypeSystem.Double, TypeSystem.Boolean }, MethodTypeFactory),
                            ce.Expression,
                            GetInt64ConversionArgs(targetType));
                    }
                }
                else if (currentType.MetadataType == MetadataType.UInt64)
                {
                    if (targetType.MetadataType == MetadataType.Int64)
                    {
                        newExpression = JSInvocationExpression
                                        .InvokeMethod(
                            TypeSystem.Int64,
                            new JSFakeMethod("ToInt64", TypeSystem.Int64, new TypeReference[] { }, MethodTypeFactory),
                            ce.Expression);
                    }
                    else
                    {
                        newExpression = JSInvocationExpression
                                        .InvokeMethod(
                            TypeSystem.Int64,
                            new JSFakeMethod("ToNumber", targetType, new TypeReference[] { TypeSystem.Double, TypeSystem.Boolean }, MethodTypeFactory),
                            ce.Expression,
                            GetInt64ConversionArgs(targetType));
                    }
                }
                else if (targetType.MetadataType == MetadataType.Int64)
                {
                    newExpression = JSInvocationExpression.InvokeStatic(
                        new JSType(TypeSystem.Int64),
                        new JSFakeMethod("FromNumber", TypeSystem.Int64, new[] { currentType }, MethodTypeFactory),
                        new[] { ce.Expression },
                        true);
                }
                else if (targetType.MetadataType == MetadataType.UInt64)
                {
                    newExpression = JSInvocationExpression.InvokeStatic(
                        new JSType(TypeSystem.UInt64),
                        new JSFakeMethod("FromNumber", TypeSystem.UInt64, new[] { currentType }, MethodTypeFactory),
                        new[] { ce.Expression },
                        true);
                }
                else if (
                    TypeUtil.IsIntegral(currentType) ||
                    !TypeUtil.IsIntegral(targetType))
                {
                    // Ensure that we don't eliminate casts that reduce the size of a value
                    if (TypeUtil.SizeOfType(currentType) < TypeUtil.SizeOfType(targetType))
                    {
                        newExpression = ce.Expression;
                    }
                }
                else
                {
                    newExpression = new JSTruncateExpression(ce.Expression);
                }
            }
            else
            {
                // newExpression = JSIL.Cast(ce.Expression, targetType);
            }

            if (newExpression != null)
            {
                ParentNode.ReplaceChild(ce, newExpression);
                VisitReplacement(newExpression);
            }
            else
            {
                // Debugger.Break();
                VisitChildren(ce);
            }
        }
Ejemplo n.º 11
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            this.Init(property);

            EditorGUI.BeginProperty(position, label, property);

            //################################
            //FIRST LINE
            var rect = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);

            rect = EditorGUI.PrefixLabel(rect, label);

            var targetProp = property.FindPropertyRelative(PROP_TARGET);

            var w0 = Mathf.Min(rect.width * 0.3f, 80f);
            var w1 = rect.width - w0;
            var r0 = new Rect(rect.xMin, rect.yMin, w0, rect.height);
            var r1 = new Rect(r0.xMax, rect.yMin, w1, rect.height);

            var searchProp = property.FindPropertyRelative(PROP_SEARCHBY);
            var queryProp  = property.FindPropertyRelative(PROP_QUERY);

            var eSearchBy = (SearchByAlt)searchProp.GetEnumValue <SearchBy>();

            EditorGUI.BeginChangeCheck();
            eSearchBy = (SearchByAlt)EditorGUI.EnumPopup(r0, eSearchBy);
            if (EditorGUI.EndChangeCheck())
            {
                searchProp.SetEnumValue((SearchBy)eSearchBy);
            }

            switch (eSearchBy)
            {
            case SearchByAlt.Direct:
            {
                var tp = (_configAttrib != null) ? _configAttrib.TargetType : typeof(UnityEngine.Object);
                targetProp.objectReferenceValue = EditorGUI.ObjectField(r1, targetProp.objectReferenceValue, tp, true);
            }
            break;

            case SearchByAlt.Tag:
            {
                queryProp.stringValue           = EditorGUI.TagField(r1, queryProp.stringValue);
                targetProp.objectReferenceValue = null;
            }
            break;

            case SearchByAlt.Name:
            {
                queryProp.stringValue           = EditorGUI.TextField(r1, queryProp.stringValue);
                targetProp.objectReferenceValue = null;
            }
            break;

            case SearchByAlt.Type:
            {
                var tp = TypeUtil.FindType(queryProp.stringValue);
                if (!TypeUtil.IsType(tp, typeof(UnityEngine.Object)))
                {
                    tp = null;
                }
                tp = SPEditorGUI.TypeDropDown(r1, GUIContent.none, typeof(UnityEngine.Object), tp);
                queryProp.stringValue           = (tp != null) ? tp.FullName : null;
                targetProp.objectReferenceValue = null;
            }
            break;
            }

            EditorGUI.EndProperty();
        }
Ejemplo n.º 12
0
        public JsonResult ValidateLogin()
        {
            //string a = TypeUtil.ObjectToString(base.Request["verifyCode"]);
            string     text           = TypeUtil.ObjectToString(base.Request["userName"]);
            string     password       = Utility.MD5(TypeUtil.ObjectToString(base.Request["password"]));
            Base_Users userByAccounts = FacadeManage.aidePlatformManagerFacade.GetUserByAccounts(text);

            if (userByAccounts == null)
            {
                return(Json(new
                {
                    IsOk = false,
                    Msg = "账号不存在"
                }));
            }
            if (userByAccounts.IsMobileNeed)
            {
                //if (a == "")
                //{
                //    return Json(new
                //    {
                //        IsOk = false,
                //        Msg = "请输入手机验证码"
                //    });
                //}
                if (base.Session["code"] == null)
                {
                    return(Json(new
                    {
                        IsOk = false,
                        Msg = "验证码不存在或已过期,请重新获取验证码"
                    }));
                }
                //if (a != base.Session["code"].ToString())
                //{
                //    if (base.Session["error"] == null)
                //    {
                //        base.Session["error"] = 1;
                //    }
                //    else
                //    {
                //        base.Session["error"] = Convert.ToInt32(base.Session["error"]) + 1;
                //    }
                //    if (Convert.ToInt32(base.Session["error"]) > 3)
                //    {
                //        base.Session["code"] = null;
                //        return Json(new
                //        {
                //            IsOk = false,
                //            Msg = "验证码错误多次,请重新获取!"
                //        });
                //    }
                //    return Json(new
                //    {
                //        IsOk = false,
                //        Msg = "验证码错误!"
                //    });
                //}
            }
            userByAccounts             = new Base_Users();
            userByAccounts.Username    = text;
            userByAccounts.Password    = password;
            userByAccounts.LastLoginIP = GameRequest.GetUserIP();
            Message message = FacadeManage.aidePlatformManagerFacade.UserLogon(userByAccounts);
            string  text2   = "";

            if (!message.Success)
            {
                switch (message.MessageID)
                {
                case 100:
                    text2 = "用户名或者密码错误";
                    break;

                case 101:
                    text2 = "IP错误";
                    break;

                case 102:
                    text2 = "没有此用户";
                    break;

                default:
                    text2 = "登录错误";
                    break;
                }
                return(Json(new
                {
                    IsOk = false,
                    Msg = text2
                }));
            }
            userByAccounts = (message.EntityList[0] as Base_Users);
            if (userByAccounts == null || (userByAccounts.UserID != 1 && userByAccounts.RoleID < 0))
            {
                return(Json(new
                {
                    IsOk = false,
                    Msg = "登录失败"
                }));
            }
            base.Session["code"]  = null;
            base.Session["error"] = null;
            return(Json(new
            {
                IsOk = true,
                Msg = "登录成功"
            }));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets the product filed value.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="column">The column.</param>
        /// <returns>The value of the field.</returns>
        protected virtual string GetProductFiledValue(T container, GridColumn column)
        {
            Assert.ArgumentNotNull(container, "container");
            Assert.ArgumentNotNull(column, "column");

            string[] value = { null };

            var matcher = Context.Entity.Resolve <MappingItemMatcher>();

            foreach (var info in container.GetType().GetProperties())
            {
                if (!string.IsNullOrEmpty(value[0]))
                {
                    break;
                }

                if (!info.CanRead)
                {
                    continue;
                }

                var names = matcher.GetFieldNames(info);
                var info1 = info;
                foreach (var instanceValue in from name in names.TakeWhile(name => string.IsNullOrEmpty(value[0])) where column.FieldName == name select info1.GetValue(container, null))
                {
                    value[0] = TypeUtil.TryParse(instanceValue, string.Empty);

                    if (!ID.IsID(value[0]))
                    {
                        continue;
                    }

                    var item = Sitecore.Context.Database.GetItem(value[0]) ?? Sitecore.Context.ContentDatabase.GetItem(value[0]);
                    if (item != null)
                    {
                        value[0] = item.DisplayName;
                    }
                }
            }

            if (value[0] == null)
            {
                var propertyInfo = container.GetType().GetProperty("Specifications");
                if (propertyInfo != null)
                {
                    var specification = propertyInfo.GetValue(container, null);

                    if (specification != null)
                    {
                        var methodInfo = specification.GetType().GetMethod("ContainsKey", new[] { typeof(string) });

                        if (true.Equals(methodInfo.Invoke(specification, new object[] { column.FieldName })))
                        {
                            propertyInfo = specification.GetType().GetProperty("Item", new[] { typeof(string) });

                            if (propertyInfo != null)
                            {
                                var rawValue = propertyInfo.GetValue(specification, new object[] { column.FieldName });

                                value[0] = TypeUtil.TryParse(rawValue, string.Empty);

                                if (ID.IsID(value[0]))
                                {
                                    var item = Sitecore.Context.Database.GetItem(value[0]) ?? Sitecore.Context.ContentDatabase.GetItem(value[0]);
                                    if (item != null)
                                    {
                                        value[0] = item.DisplayName;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (value[0] != null || !(container is IEntity))
            {
                return(value[0] ?? string.Empty);
            }

            var id = ((IEntity)container).Alias;

            if (string.IsNullOrEmpty(id))
            {
                return(value[0] ?? string.Empty);
            }

            var theItem = Sitecore.Context.Database.GetItem(id);

            if (theItem == null)
            {
                return(value[0] ?? string.Empty);
            }

            value[0] = theItem[column.FieldName];
            if (!ID.IsID(value[0]))
            {
                return(value[0] ?? string.Empty);
            }

            var linkedItem = theItem.Database.GetItem(value[0]);

            if (linkedItem != null)
            {
                value[0] = linkedItem.Name;
            }

            return(value[0] ?? string.Empty);
        }
Ejemplo n.º 14
0
        public static void OnSceneTreeReflectField(SceneExplorerState state, ReferenceChain refChain, object obj, FieldInfo field, TypeUtil.SmartType smartType = TypeUtil.SmartType.Undefined, int nameHighlightFrom = -1, int nameHighlightLength = 0)
        {
            if (!SceneExplorerCommon.SceneTreeCheckDepth(refChain))
            {
                return;
            }

            if (obj == null || field == null)
            {
                SceneExplorerCommon.OnSceneTreeMessage(refChain, "null");
                return;
            }

            GUILayout.BeginHorizontal(GUIWindow.HighlightStyle);
            SceneExplorerCommon.InsertIndent(refChain.Indentation);

            GUI.contentColor = Color.white;

            object value = null;

            try
            {
                value = field.GetValue(obj);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }

            if (value != null)
            {
                GUIExpander.ExpanderControls(state, refChain, field.FieldType);
            }

            if (field.IsInitOnly)
            {
                GUI.enabled = false;
            }

            if (MainWindow.Instance.Config.ShowModifiers)
            {
                GUI.contentColor = MainWindow.Instance.Config.ModifierColor;

                if (field.IsPublic)
                {
                    GUILayout.Label("public ");
                }
                else if (field.IsPrivate)
                {
                    GUILayout.Label("private ");
                }

                GUI.contentColor = MainWindow.Instance.Config.MemberTypeColor;

                GUILayout.Label("field ");

                if (field.IsStatic)
                {
                    GUI.contentColor = MainWindow.Instance.Config.KeywordColor;
                    GUILayout.Label("static ");
                }

                if (field.IsInitOnly)
                {
                    GUI.contentColor = MainWindow.Instance.Config.KeywordColor;
                    GUILayout.Label("const ");
                }
            }

            GUI.contentColor = MainWindow.Instance.Config.TypeColor;
            GUILayout.Label(field.FieldType + " ");

            GUIMemberName.MemberName(field, nameHighlightFrom, nameHighlightLength);

            GUI.contentColor = Color.white;
            GUILayout.Label(" = ");
            GUI.contentColor = MainWindow.Instance.Config.ValueColor;

            if (value == null || !TypeUtil.IsSpecialType(field.FieldType))
            {
                GUILayout.Label(value?.ToString() ?? "null");
            }
            else
            {
                try
                {
                    var newValue = GUIControls.EditorValueField(refChain.UniqueId, field.FieldType, value);
                    if (!newValue.Equals(value))
                    {
                        field.SetValue(obj, newValue);
                    }
                }
                catch (Exception)
                {
                    GUILayout.Label(value.ToString());
                }
            }

            GUI.enabled      = true;
            GUI.contentColor = Color.white;

            GUILayout.FlexibleSpace();

            GUIButtons.SetupCommonButtons(refChain, value, valueIndex: 0, smartType);
            object paste   = null;
            var    doPaste = !field.IsLiteral && !field.IsInitOnly;

            if (doPaste)
            {
                doPaste = GUIButtons.SetupPasteButon(field.FieldType, value, out paste);
            }

            if (value != null)
            {
                GUIButtons.SetupJumpButton(value, refChain);
            }

            GUILayout.EndHorizontal();
            if (value != null && !TypeUtil.IsSpecialType(field.FieldType) && state.ExpandedObjects.Contains(refChain.UniqueId))
            {
                GUIReflect.OnSceneTreeReflect(state, refChain, value, false, smartType);
            }

            if (doPaste)
            {
                try
                {
                    field.SetValue(obj, paste);
                }
                catch (Exception e)
                {
                    Logger.Warning(e.Message);
                }
            }
        }
Ejemplo n.º 15
0
 public void GetType_NoAssemblyQualifcation(string typeString, Type expectedType)
 {
     Assert.Equal(expectedType, TypeUtil.GetType(typeString, throwOnError: false));
 }
Ejemplo n.º 16
0
        public void VisitNode(JSInvocationExpression ie)
        {
            var type           = ie.JSType;
            var method         = ie.JSMethod;
            var thisExpression = ie.ThisReference;

            if (method != null)
            {
                if (
                    (type != null) &&
                    (type.Type.FullName == "System.Object")
                    )
                {
                    switch (method.Method.Member.Name)
                    {
                    case ".ctor": {
                        var replacement = new JSNullExpression();
                        ParentNode.ReplaceChild(ie, replacement);
                        VisitReplacement(replacement);

                        return;
                    }

                    case "ReferenceEquals": {
                        var lhs = ie.Arguments[0];
                        var rhs = ie.Arguments[1];

                        var lhsType = lhs.GetActualType(TypeSystem);
                        var rhsType = rhs.GetActualType(TypeSystem);

                        JSNode replacement;

                        // Structs can never compare equal with ReferenceEquals
                        if (TypeUtil.IsStruct(lhsType) || TypeUtil.IsStruct(rhsType))
                        {
                            replacement = JSLiteral.New(false);
                        }
                        else
                        {
                            replacement = new JSBinaryOperatorExpression(
                                JSBinaryOperator.Equal,
                                lhs, rhs,
                                TypeSystem.Boolean
                                );
                        }

                        ParentNode.ReplaceChild(ie, replacement);
                        VisitReplacement(replacement);

                        return;
                    }

                    case "GetType": {
                        JSNode replacement;

                        var thisType = JSExpression.DeReferenceType(thisExpression.GetActualType(TypeSystem), false);
                        if ((thisType is GenericInstanceType) && thisType.FullName.StartsWith("System.Nullable"))
                        {
                            var git = (GenericInstanceType)thisType;

                            replacement = new JSTernaryOperatorExpression(
                                new JSBinaryOperatorExpression(
                                    JSBinaryOperator.NotEqual,
                                    thisExpression, new JSNullLiteral(thisType),
                                    TypeSystem.Boolean
                                    ),
                                new JSTypeOfExpression(git.GenericArguments[0]),
                                JSIL.ThrowNullReferenceException(),
                                new TypeReference("System", "Type", TypeSystem.Object.Module, TypeSystem.Object.Scope, false)
                                );
                        }
                        else
                        {
                            replacement = JSIL.GetTypeOf(thisExpression);
                        }

                        ParentNode.ReplaceChild(ie, replacement);
                        VisitReplacement(replacement);

                        return;
                    }
                    }
                }
                else if (
                    (type != null) &&
                    (type.Type.FullName == "System.ValueType")
                    )
                {
                    switch (method.Method.Member.Name)
                    {
                    case "Equals": {
                        var replacement = JSIL.StructEquals(ie.ThisReference, ie.Arguments.First());
                        ParentNode.ReplaceChild(ie, replacement);
                        VisitReplacement(replacement);

                        return;
                    }
                    }
                }
                else if (
                    (type != null) &&
                    IsNullable(type.Type)
                    )
                {
                    var t        = (type.Type as GenericInstanceType).GenericArguments[0];
                    var @null    = JSLiteral.Null(t);
                    var @default = new JSDefaultValueLiteral(t);

                    switch (method.Method.Member.Name)
                    {
                    case ".ctor":
                        JSExpression value;
                        if (ie.Arguments.Count == 0)
                        {
                            value = @null;
                        }
                        else
                        {
                            value = ie.Arguments[0];
                        }

                        var boe = new JSBinaryOperatorExpression(
                            JSOperator.Assignment, ie.ThisReference, value, type.Type
                            );
                        ParentNode.ReplaceChild(ie, boe);
                        VisitReplacement(boe);

                        break;

                    case "GetValueOrDefault":
                        var isNull = new JSBinaryOperatorExpression(
                            JSOperator.Equal, ie.ThisReference, @null, TypeSystem.Boolean
                            );

                        JSTernaryOperatorExpression ternary;
                        if (ie.Arguments.Count == 0)
                        {
                            ternary = new JSTernaryOperatorExpression(
                                isNull, @default, ie.ThisReference, type.Type
                                );
                        }
                        else
                        {
                            ternary = new JSTernaryOperatorExpression(
                                isNull, ie.Arguments[0], ie.ThisReference, type.Type
                                );
                        }

                        if (ParentNode is JSResultReferenceExpression)
                        {
                            // HACK: Replacing the invocation inside a result reference is incorrect, so we need to walk up the stack
                            //  and replace the result reference with the ternary instead.
                            _ResultReferenceReplacement = ternary;
                        }
                        else
                        {
                            ParentNode.ReplaceChild(ie, ternary);
                            VisitReplacement(ternary);
                        }

                        break;

                    case "get_HasValue": {
                        var replacement = new JSBinaryOperatorExpression(
                            JSOperator.NotEqual, ie.ThisReference, @null, TypeSystem.Boolean
                            );
                        if (ParentNode is JSResultReferenceExpression)
                        {
                            _ResultReferenceReplacement = replacement;
                        }
                        else
                        {
                            ParentNode.ReplaceChild(ie, replacement);
                            VisitReplacement(replacement);
                        }

                        break;
                    }

                    case "get_Value":
                        if (ParentNode is JSResultReferenceExpression)
                        {
                            _ResultReferenceReplacement = ie.ThisReference;
                        }
                        else
                        {
                            ParentNode.ReplaceChild(ie, ie.ThisReference);
                            VisitReplacement(ie.ThisReference);
                        }

                        break;

                    case "Equals":
                        JSBinaryOperatorExpression equality = new JSBinaryOperatorExpression(JSOperator.Equal, ie.ThisReference, ie.Parameters.First().Value, type.Type);
                        ParentNode.ReplaceChild(ie, equality);
                        VisitReplacement(equality);
                        break;

                    default:
                        throw new NotImplementedException(method.Method.Member.FullName);
                    }

                    return;
                }
                else if (
                    (type != null) &&
                    TypeUtil.TypesAreEqual(TypeSystem.String, type.Type) &&
                    (method.Method.Name == "Concat")
                    )
                {
                    if (ie.Arguments.Count > 2)
                    {
                        if (ie.Arguments.All(
                                (arg) => TypeUtil.TypesAreEqual(
                                    TypeSystem.String, arg.GetActualType(TypeSystem)
                                    )
                                ))
                        {
                            var boe = JSBinaryOperatorExpression.New(
                                JSOperator.Add,
                                ie.Arguments,
                                TypeSystem.String
                                );

                            ParentNode.ReplaceChild(
                                ie,
                                boe
                                );

                            VisitReplacement(boe);
                        }
                    }
                    else if (
                        // HACK: Fix for #239, only convert concat call into + if both sides are non-null literals
                        (ie.Arguments.Count == 2)
                        )
                    {
                        var lhs = ie.Arguments[0];
                        var rhs = ie.Arguments[1];

                        var isAddOk = (lhs is JSStringLiteral) && (rhs is JSStringLiteral);

                        var lhsType = TypeUtil.DereferenceType(lhs.GetActualType(TypeSystem));
                        if (!(
                                TypeUtil.TypesAreEqual(TypeSystem.String, lhsType) ||
                                TypeUtil.TypesAreEqual(TypeSystem.Char, lhsType)
                                ))
                        {
                            lhs     = JSInvocationExpression.InvokeMethod(lhsType, JS.toString, lhs, null);
                            isAddOk = true;
                        }

                        var rhsType = TypeUtil.DereferenceType(rhs.GetActualType(TypeSystem));
                        if (!(
                                TypeUtil.TypesAreEqual(TypeSystem.String, rhsType) ||
                                TypeUtil.TypesAreEqual(TypeSystem.Char, rhsType)
                                ))
                        {
                            rhs     = JSInvocationExpression.InvokeMethod(rhsType, JS.toString, rhs, null);
                            isAddOk = true;
                        }

                        if (isAddOk)
                        {
                            var boe = new JSBinaryOperatorExpression(
                                JSOperator.Add, lhs, rhs, TypeSystem.String
                                );

                            ParentNode.ReplaceChild(
                                ie, boe
                                );

                            VisitReplacement(boe);
                        }
                    }
                    else if (
                        TypeUtil.GetTypeDefinition(ie.Arguments[0].GetActualType(TypeSystem)).FullName == "System.Array"
                        )
                    {
                    }
                    else
                    {
                        var firstArg = ie.Arguments.FirstOrDefault();

                        ParentNode.ReplaceChild(
                            ie, firstArg
                            );

                        if (firstArg != null)
                        {
                            VisitReplacement(firstArg);
                        }
                    }
                    return;
                }
                else if (
                    TypeUtil.IsDelegateType(method.Reference.DeclaringType) &&
                    (method.Method.Name == "Invoke")
                    )
                {
                    var newIe = new JSDelegateInvocationExpression(
                        thisExpression, ie.GetActualType(TypeSystem), ie.Arguments.ToArray()
                        );
                    ParentNode.ReplaceChild(ie, newIe);

                    VisitReplacement(newIe);
                    return;
                }
                else if (
                    (method.Reference.DeclaringType.Name == "RuntimeHelpers") &&
                    (method.Method.Name == "InitializeArray")
                    )
                {
                    var array       = ie.Arguments[0];
                    var arrayType   = array.GetActualType(TypeSystem);
                    var field       = ie.Arguments[1].SelfAndChildrenRecursive.OfType <JSField>().First();
                    var initializer = JSArrayExpression.UnpackArrayInitializer(arrayType, field.Field.Member.InitialValue);

                    var copy = JSIL.ShallowCopy(array, initializer, arrayType);
                    ParentNode.ReplaceChild(ie, copy);
                    VisitReplacement(copy);
                    return;
                }
                else if (
                    method.Reference.DeclaringType.FullName == "System.Reflection.Assembly"
                    )
                {
                    switch (method.Reference.Name)
                    {
                    case "GetExecutingAssembly": {
                        var assembly = Method.DeclaringType.Module.Assembly;
                        var asmNode  = new JSReflectionAssembly(assembly);
                        ParentNode.ReplaceChild(ie, asmNode);
                        VisitReplacement(asmNode);

                        return;
                    }
                    }
                }
                else if (
                    method.Method.DeclaringType.Definition.FullName == "System.Array" &&
                    (ie.Arguments.Count == 1)
                    )
                {
                    switch (method.Method.Name)
                    {
                    case "GetLength":
                    case "GetUpperBound": {
                        var index = ie.Arguments[0] as JSLiteral;
                        if (index != null)
                        {
                            var newDot = JSDotExpression.New(thisExpression, new JSStringIdentifier(
                                                                 String.Format("length{0}", Convert.ToInt32(index.Literal)),
                                                                 TypeSystem.Int32
                                                                 ));

                            if (method.Method.Name == "GetUpperBound")
                            {
                                var newExpr = new JSBinaryOperatorExpression(
                                    JSOperator.Subtract, newDot, JSLiteral.New(1), TypeSystem.Int32
                                    );
                                ParentNode.ReplaceChild(ie, newExpr);
                            }
                            else
                            {
                                ParentNode.ReplaceChild(ie, newDot);
                            }
                        }
                        break;
                    }

                    case "GetLowerBound":
                        ParentNode.ReplaceChild(ie, JSLiteral.New(0));
                        break;
                    }
                }
            }

            VisitChildren(ie);
        }
Ejemplo n.º 17
0
 public void GetType_ThrowOnError()
 {
     Assert.Throws <TypeLoadException>(() => TypeUtil.GetType("Mxyzptlk", throwOnError: true));
 }
Ejemplo n.º 18
0
        public static void OnSceneTreeReflectIList(SceneExplorerState state, ReferenceChain refChain, object myProperty, TypeUtil.SmartType elementSmartType = TypeUtil.SmartType.Undefined)
        {
            if (!SceneExplorerCommon.SceneTreeCheckDepth(refChain))
            {
                return;
            }

            if (!(myProperty is IList list))
            {
                return;
            }

            var oldRefChain    = refChain;
            var collectionSize = list.Count;

            if (collectionSize == 0)
            {
                GUILayout.BeginHorizontal();
                GUI.contentColor = Color.yellow;
                GUILayout.Label("List is empty!");
                GUI.contentColor = Color.white;
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                return;
            }

            var listItemType = list.GetType().GetElementType();
            var flagsField   = listItemType?.GetField("m_flags");
            var flagIsEnum   = flagsField?.FieldType.IsEnum == true && Type.GetTypeCode(flagsField.FieldType) == TypeCode.Int32;

            GUICollectionNavigation.SetUpCollectionNavigation("List", state, refChain, oldRefChain, collectionSize, out var arrayStart, out var arrayEnd);
            for (var i = arrayStart; i <= arrayEnd; i++)
            {
                refChain = oldRefChain.Add(i);

                GUILayout.BeginHorizontal(GUIWindow.HighlightStyle);
                SceneExplorerCommon.InsertIndent(refChain.Indentation);

                GUI.contentColor = Color.white;

                var value         = list[(int)i];
                var type          = value?.GetType() ?? listItemType;
                var isNullOrEmpty = value == null || flagIsEnum && Convert.ToInt32(flagsField.GetValue(value)) == 0;
                if (type != null)
                {
                    if (!isNullOrEmpty)
                    {
                        GUIExpander.ExpanderControls(state, refChain, type);
                    }

                    GUI.contentColor = MainWindow.Instance.Config.TypeColor;

                    GUILayout.Label($"{type} ");
                }

                GUI.contentColor = MainWindow.Instance.Config.NameColor;

                GUILayout.Label($"{oldRefChain.LastItemName}.[{i}]");

                GUI.contentColor = Color.white;

                GUILayout.Label(" = ");

                GUI.contentColor = MainWindow.Instance.Config.ValueColor;

                GUILayout.Label(value == null ? "null" : isNullOrEmpty ? "empty" : value.ToString());

                GUI.contentColor = Color.white;

                GUILayout.FlexibleSpace();

                if (!isNullOrEmpty)
                {
                    GUIButtons.SetupCommonButtons(refChain, value, i, elementSmartType);
                }

                if (value != null)
                {
                    GUIButtons.SetupJumpButton(value, refChain);
                }

                GUILayout.EndHorizontal();

                if (!isNullOrEmpty && !TypeUtil.IsSpecialType(type) && state.ExpandedObjects.Contains(refChain.UniqueId))
                {
                    GUIReflect.OnSceneTreeReflect(state, refChain, value, false);
                }
            }
        }
Ejemplo n.º 19
0
        public void GetTypeConfigHost()
        {
            TestHost host = new TestHost((s, b) => { return(typeof(string)); });

            Assert.Equal(typeof(string), TypeUtil.GetType(host, "Mxyzptlk", throwOnError: false));
        }
Ejemplo n.º 20
0
        private void Init(Type type)
        {
            this.type = type;
            InitClassExtractors();
            fieldExtractors    = new List <FieldExtractor>();
            propertyExtractors = new List <PropertyExtractor>();
            var fields    = TypeUtil.GetFieldsIncludeBaseClass(type);
            var propertys = TypeUtil.GetPropertysIncludeBaseClass(type);

            foreach (var field in fields)
            {
                var fieldExtractor    = GetAttributeExtractBy(type, field);
                var fieldExtractorTmp = GetAttributeExtractCombo(type, field);
                if (fieldExtractor != null && fieldExtractorTmp != null)
                {
                    throw new Exception("Only one of 'ExtractByAttribute, ComboExtractAttribute or ExtractByUrl' can be added to a field!");
                }
                else if (fieldExtractor == null && fieldExtractorTmp != null)
                {
                    fieldExtractor = fieldExtractorTmp;
                }
                fieldExtractorTmp = GetAttributeExtractByUrl(type, field);
                if (fieldExtractor != null && fieldExtractorTmp != null)
                {
                    throw new Exception("Only one of 'ExtractBy ComboExtract ExtractByUrl' can be added to a field!");
                }
                else if (fieldExtractor == null && fieldExtractorTmp != null)
                {
                    fieldExtractor = fieldExtractorTmp;
                }
                if (fieldExtractor != null)
                {
                    fieldExtractor.ObjectFormatter = new ObjectFormatterBuilder <IObjectFormatter>().SetField(field).Build();
                    fieldExtractors.Add(fieldExtractor);
                }
            }
            foreach (var property in propertys)
            {
                var propertyExtractor    = GetAttributeExtractBy(type, property);
                var propertyExtractorTmp = GetAttributeExtractCombo(type, property);
                if (propertyExtractor != null && propertyExtractorTmp != null)
                {
                    throw new Exception("Only one of 'ExtractByAttribute, ComboExtractAttribute or ExtractByUrl' can be added to a field!");
                }
                else if (propertyExtractor == null && propertyExtractorTmp != null)
                {
                    propertyExtractor = propertyExtractorTmp;
                }
                propertyExtractorTmp = GetAttributeExtractByUrl(type, property);
                if (propertyExtractor != null && propertyExtractorTmp != null)
                {
                    throw new Exception("Only one of 'ExtractBy ComboExtract ExtractByUrl' can be added to a field!");
                }
                else if (propertyExtractor == null && propertyExtractorTmp != null)
                {
                    propertyExtractor = propertyExtractorTmp;
                }
                if (propertyExtractor != null)
                {
                    propertyExtractor.ObjectFormatter = new ObjectFormatterBuilder <IObjectFormatter>().SetProperty(property).Build();
                    propertyExtractors.Add(propertyExtractor);
                }
            }
        }
        private System.Collections.IEnumerable ReduceTargets(object triggerArg)
        {
            switch (_find)
            {
            case FindCommand.Direct:
            {
                object obj = (_configured) ? _target : triggerArg;
                if (obj == null)
                {
                    yield break;
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    yield return(obj);

                    break;

                case ResolveByCommand.WithTag:
                {
                    var go = GameObjectUtil.GetGameObjectFromSource(obj);
                    if (go.HasTag(_queryString))
                    {
                        yield return(obj);
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    var go = GameObjectUtil.GetGameObjectFromSource(obj);
                    if (go.CompareName(_queryString))
                    {
                        yield return(obj);
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    var o = ObjUtil.GetAsFromSource(TypeUtil.FindType(_queryString), GameObjectUtil.GetGameObjectFromSource(obj));
                    if (o != null)
                    {
                        yield return(o);
                    }
                }
                break;
                }
            }
            break;

            case FindCommand.FindParent:
            {
                Transform trans = GameObjectUtil.GetTransformFromSource((_configured) ? _target : triggerArg);
                if (trans == null)
                {
                    yield break;
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                {
                    var t = trans.parent;
                    if (t != null)
                    {
                        yield return(t);
                    }
                }
                break;

                case ResolveByCommand.WithTag:
                {
                    foreach (var p in GameObjectUtil.GetParents(trans))
                    {
                        if (p.HasTag(_queryString))
                        {
                            yield return(p);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    foreach (var p in GameObjectUtil.GetParents(trans))
                    {
                        if (p.CompareName(_queryString))
                        {
                            yield return(p);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    var tp = TypeUtil.FindType(_queryString);
                    foreach (var p in GameObjectUtil.GetParents(trans))
                    {
                        var o = ObjUtil.GetAsFromSource(tp, p);
                        if (o != null)
                        {
                            yield return(o);
                        }
                    }
                }
                break;
                }
            }
            break;

            case FindCommand.FindInChildren:
            {
                Transform trans = GameObjectUtil.GetTransformFromSource((_configured) ? _target : triggerArg);
                if (trans == null)
                {
                    yield break;
                }
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    if (trans.childCount > 0)
                    {
                        yield return(trans.GetChild(0));
                    }
                    break;

                case ResolveByCommand.WithTag:
                    if (trans.childCount > 0)
                    {
                        using (var lst = TempCollection.GetList <Transform>())
                        {
                            GameObjectUtil.GetAllChildren(trans, lst);
                            for (int i = 0; i < lst.Count; i++)
                            {
                                if (lst[i].HasTag(_queryString))
                                {
                                    yield return(lst[i]);
                                }
                            }
                        }
                    }
                    break;

                case ResolveByCommand.WithName:
                    if (trans.childCount > 0)
                    {
                        using (var lst = TempCollection.GetList <Transform>())
                        {
                            GameObjectUtil.GetAllChildren(trans, lst);
                            for (int i = 0; i < lst.Count; i++)
                            {
                                if (lst[i].CompareName(_queryString))
                                {
                                    yield return(lst[i]);
                                }
                            }
                        }
                    }
                    break;

                case ResolveByCommand.WithType:
                    if (trans.childCount > 0)
                    {
                        var tp = TypeUtil.FindType(_queryString);
                        using (var lst = TempCollection.GetList <Transform>())
                        {
                            GameObjectUtil.GetAllChildren(trans, lst);
                            for (int i = 0; i < lst.Count; i++)
                            {
                                var o = ObjUtil.GetAsFromSource(tp, lst[i]);
                                if (o != null)
                                {
                                    yield return(o);
                                }
                            }
                        }
                    }
                    break;
                }
            }
            break;

            case FindCommand.FindInEntity:
            {
                GameObject entity = GameObjectUtil.GetRootFromSource((_configured) ? _target : triggerArg);
                if (entity == null)
                {
                    yield break;
                }
                ;

                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                    yield return(entity);

                    break;

                case ResolveByCommand.WithTag:
                {
                    foreach (var o in entity.FindAllWithMultiTag(_queryString))
                    {
                        yield return(o);
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    foreach (var o in GameObjectUtil.FindAllByName(entity.transform, _queryString))
                    {
                        yield return(o);
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    var tp = TypeUtil.FindType(_queryString);
                    using (var lst = TempCollection.GetList <Transform>())
                    {
                        GameObjectUtil.GetAllChildrenAndSelf(entity.transform, lst);
                        for (int i = 0; i < lst.Count; i++)
                        {
                            var o = ObjUtil.GetAsFromSource(tp, lst[i]);
                            if (o != null)
                            {
                                yield return(o);
                            }
                        }
                    }
                }
                break;
                }
            }
            break;

            case FindCommand.FindInScene:
            {
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                {
                    var go = GameObjectUtil.GetGameObjectFromSource((_configured) ? _target : triggerArg);
                    if (go != null)
                    {
                        yield return(go);
                    }
                }
                break;

                case ResolveByCommand.WithTag:
                {
                    foreach (var o in GameObjectUtil.FindGameObjectsWithMultiTag(_queryString))
                    {
                        yield return(o);
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    foreach (var o in GameObjectUtil.FindAllByName(_queryString))
                    {
                        yield return(o);
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    foreach (var o in ObjUtil.FindAll(SearchBy.Type, _queryString))
                    {
                        yield return(o);
                    }
                }
                break;
                }
            }
            break;

            case FindCommand.FindEntityInScene:
            {
                switch (_resolveBy)
                {
                case ResolveByCommand.Nothing:
                {
                    var go = GameObjectUtil.GetGameObjectFromSource((_configured) ? _target : triggerArg);
                    if (go != null)
                    {
                        yield return(go);
                    }
                }
                break;

                case ResolveByCommand.WithTag:
                {
                    var e = SPEntity.Pool.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if (e.Current.HasTag(_queryString))
                        {
                            yield return(e.Current);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithName:
                {
                    var e = SPEntity.Pool.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if (e.Current.CompareName(_queryString))
                        {
                            yield return(e.Current);
                        }
                    }
                }
                break;

                case ResolveByCommand.WithType:
                {
                    var e  = SPEntity.Pool.GetEnumerator();
                    var tp = TypeUtil.FindType(_queryString);
                    while (e.MoveNext())
                    {
                        var o = e.Current.GetComponent(tp);
                        if (o != null)
                        {
                            yield return(o);
                        }
                    }
                }
                break;
                }
            }
            break;
            }
        }
 public void GetType_ConfigurationManagerTypes(string typeString, Type expectedType)
 {
     Assert.Equal(expectedType, TypeUtil.GetType(typeString, throwOnError: false));
 }
Ejemplo n.º 23
0
 public DbType GetDbType(string nativeType, int precision = 0, int scale = 0)
 {
     return(TypeUtil.OracleDataType2DbType(nativeType, precision, scale));
 }
Ejemplo n.º 24
0
        protected virtual IEnumerable <Type> GetTypeImplementerMapping(Type[] interfaces,
                                                                       out IEnumerable <ITypeContributor> contributors,
                                                                       INamingScope namingScope)
        {
            var methodsToSkip = new List <MethodInfo>();
            var proxyInstance = new ClassProxyInstanceContributor(targetType, methodsToSkip, interfaces, ProxyTypeConstants.Class);
            // TODO: the trick with methodsToSkip is not very nice...
            var proxyTarget = new ClassProxyTargetContributor(targetType, methodsToSkip, namingScope)
            {
                Logger = Logger
            };
            IDictionary <Type, ITypeContributor> typeImplementerMapping = new Dictionary <Type, ITypeContributor>();

            // Order of interface precedence:
            // 1. first target
            // target is not an interface so we do nothing

            var targetInterfaces     = targetType.GetAllInterfaces();
            var additionalInterfaces = TypeUtil.GetAllInterfaces(interfaces);
            // 2. then mixins
            var mixins = new MixinContributor(namingScope, false)
            {
                Logger = Logger
            };

            if (ProxyGenerationOptions.HasMixins)
            {
                foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces)
                {
                    if (targetInterfaces.Contains(mixinInterface))
                    {
                        // OK, so the target implements this interface. We now do one of two things:
                        if (additionalInterfaces.Contains(mixinInterface) && typeImplementerMapping.ContainsKey(mixinInterface) == false)
                        {
                            AddMappingNoCheck(mixinInterface, proxyTarget, typeImplementerMapping);
                            proxyTarget.AddInterfaceToProxy(mixinInterface);
                        }
                        // we do not intercept the interface
                        mixins.AddEmptyInterface(mixinInterface);
                    }
                    else
                    {
                        if (!typeImplementerMapping.ContainsKey(mixinInterface))
                        {
                            mixins.AddInterfaceToProxy(mixinInterface);
                            AddMappingNoCheck(mixinInterface, mixins, typeImplementerMapping);
                        }
                    }
                }
            }
            var additionalInterfacesContributor = new InterfaceProxyWithoutTargetContributor(namingScope,
                                                                                             (c, m) => NullExpression.Instance)
            {
                Logger = Logger
            };

            // 3. then additional interfaces
            foreach (var @interface in additionalInterfaces)
            {
                if (targetInterfaces.Contains(@interface))
                {
                    if (typeImplementerMapping.ContainsKey(@interface))
                    {
                        continue;
                    }

                    // we intercept the interface, and forward calls to the target type
                    AddMappingNoCheck(@interface, proxyTarget, typeImplementerMapping);
                    proxyTarget.AddInterfaceToProxy(@interface);
                }
                else if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface) == false)
                {
                    additionalInterfacesContributor.AddInterfaceToProxy(@interface);
                    AddMapping(@interface, additionalInterfacesContributor, typeImplementerMapping);
                }
            }
            // 4. plus special interfaces
//#if FEATURE_SERIALIZATION
            if (targetType.IsSerializable)
            {
                AddMappingForISerializable(typeImplementerMapping, proxyInstance);
            }
//#endif
            try
            {
                AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyInstance, typeImplementerMapping);
            }
            catch (ArgumentException)
            {
                HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfaces);
            }

            contributors = new List <ITypeContributor>
            {
                proxyTarget,
                mixins,
                additionalInterfacesContributor,
                proxyInstance
            };
            return(typeImplementerMapping.Keys);
        }
Ejemplo n.º 25
0
        protected void TypeReferenceInternal(GenericParameter gp, TypeReferenceContext context)
        {
            var ownerType   = gp.Owner as TypeReference;
            var ownerMethod = gp.Owner as MethodReference;

            if (context != null)
            {
                if (ownerType != null)
                {
                    if (TypeUtil.TypesAreAssignable(TypeInfo, ownerType, context.SignatureMethodType))
                    {
                        TypeReference resolved = null;

                        var git = (context.SignatureMethodType as GenericInstanceType);
                        if (git != null)
                        {
                            for (var i = 0; i < git.ElementType.GenericParameters.Count; i++)
                            {
                                var _ = git.ElementType.GenericParameters[i];
                                if ((_.Name == gp.Name) || (_.Position == gp.Position))
                                {
                                    resolved = git.GenericArguments[i];
                                    break;
                                }
                            }

                            if (resolved == null)
                            {
                                throw new NotImplementedException(String.Format(
                                                                      "Could not find generic parameter '{0}' in type {1}",
                                                                      gp, context.SignatureMethodType
                                                                      ));
                            }
                        }

                        if (resolved != null)
                        {
                            if (resolved != gp)
                            {
                                TypeReference(resolved, context);
                                return;
                            }
                            else
                            {
                                TypeIdentifier(resolved, context, false);
                                return;
                            }
                        }
                    }

                    if (TypeUtil.TypesAreEqual(ownerType, context.EnclosingMethodType))
                    {
                        TypeIdentifier(gp, context, false);
                        return;
                    }

                    if (TypeUtil.TypesAreEqual(ownerType, context.DefiningType))
                    {
                        OpenGenericParameter(gp.Name, context.DefiningType.FullName);
                        return;
                    }

                    if (TypeUtil.TypesAreEqual(ownerType, context.EnclosingType))
                    {
                        WriteRaw("$.GenericParameter");
                        LPar();
                        Value(gp.Name);
                        RPar();

                        return;
                    }

                    throw new NotImplementedException(String.Format(
                                                          "Unimplemented form of generic type parameter: '{0}'.",
                                                          gp
                                                          ));
                }
                else if (ownerMethod != null)
                {
                    Func <MethodReference, int> getPosition = (mr) => {
                        for (var i = 0; i < mr.GenericParameters.Count; i++)
                        {
                            if (mr.GenericParameters[i].Name == gp.Name)
                            {
                                return(i);
                            }
                        }

                        throw new NotImplementedException(String.Format(
                                                              "Generic parameter '{0}' not found in method '{1}' parameter list",
                                                              gp, ownerMethod
                                                              ));
                    };

                    var ownerMethodIdentifier = new QualifiedMemberIdentifier(
                        new TypeIdentifier(ownerMethod.DeclaringType),
                        new MemberIdentifier(TypeInfo, ownerMethod)
                        );

                    if (ownerMethodIdentifier.Equals(ownerMethod, context.InvokingMethod, TypeInfo))
                    {
                        var gim = (GenericInstanceMethod)context.InvokingMethod;
                        TypeReference(gim.GenericArguments[getPosition(ownerMethod)], context);

                        return;
                    }

                    if (ownerMethodIdentifier.Equals(ownerMethod, context.DefiningMethod, TypeInfo))
                    {
                        Value(String.Format("!!{0}", getPosition(ownerMethod)));

                        return;
                    }

                    if (ownerMethodIdentifier.Equals(ownerMethod, context.EnclosingMethod, TypeInfo))
                    {
                        throw new NotImplementedException(String.Format(
                                                              "Unimplemented form of generic method parameter: '{0}'.",
                                                              gp
                                                              ));
                    }

                    Value(String.Format("!!{0}", getPosition(ownerMethod)));
                    return;
                }
            }
            else
            {
                throw new NotImplementedException("Cannot resolve generic parameter without a TypeReferenceContext.");
            }

            throw new NotImplementedException(String.Format(
                                                  "Unimplemented form of generic parameter: '{0}'.",
                                                  gp
                                                  ));
        }
Ejemplo n.º 26
0
 private static bool CanConvert(Type objectType)
 {
     return(TypeUtil.IsDerived(objectType, typeof(SmartEnum <,>)));
 }
Ejemplo n.º 27
0
        public ActionResult BaseRolePermission()
        {
            int num = TypeUtil.ObjectToInt(base.Request["param"]);

            base.ViewData["data"] = null;
            base.ViewBag.RoleId   = num;
            List <Base_ModuleInfo> list = new List <Base_ModuleInfo>();

            if (num > 0)
            {
                base.ViewBag.RoleName = TypeUtil.GetRoleName(num);
                if (num == 1)
                {
                    base.ViewBag.Tit = "<超级管理员默认具有全部权限>";
                }
                else
                {
                    DataSet moduleList           = FacadeManage.aidePlatformManagerFacade.GetModuleList();
                    DataSet modulePermissionList = FacadeManage.aidePlatformManagerFacade.GetModulePermissionList();
                    DataSet rolePermissionList   = FacadeManage.aidePlatformManagerFacade.GetRolePermissionList(num);
                    if (moduleList != null && moduleList.Tables.Count > 0)
                    {
                        foreach (DataRow row in moduleList.Tables[0].Rows)
                        {
                            Base_ModuleInfo base_ModuleInfo = new Base_ModuleInfo();
                            int             num2            = TypeUtil.ObjectToInt(row["ModuleID"]);
                            string          text2           = base_ModuleInfo.Title = TypeUtil.ObjectToString(row["Title"]);
                            base_ModuleInfo.ModuleID = num2;
                            DataRow[] array = moduleList.Tables[0].Select("ParentID=" + num2);
                            if (array != null && array.Count() > 0)
                            {
                                List <Base_ModuleSubInfo> list2 = new List <Base_ModuleSubInfo>();
                                DataRow[] array2 = array;
                                foreach (DataRow dataRow2 in array2)
                                {
                                    Base_ModuleSubInfo base_ModuleSubInfo = new Base_ModuleSubInfo();
                                    string             title = TypeUtil.ObjectToString(dataRow2["Title"]);
                                    int num3 = TypeUtil.ObjectToInt(dataRow2["ModuleID"]);
                                    if (modulePermissionList != null && modulePermissionList.Tables.Count > 0 && modulePermissionList.Tables[0].Select("ModuleID=" + num3).Count() > 0)
                                    {
                                        base_ModuleSubInfo.Title    = title;
                                        base_ModuleSubInfo.ModuleID = num3;
                                        DataRow[] array3 = modulePermissionList.Tables[0].Select("ModuleID=" + num3);
                                        List <Base_ModulePermissionInfo> list3 = new List <Base_ModulePermissionInfo>();
                                        DataRow[] array4 = array3;
                                        foreach (DataRow dataRow3 in array4)
                                        {
                                            Base_ModulePermissionInfo base_ModulePermissionInfo = new Base_ModulePermissionInfo();
                                            int num4 = TypeUtil.ObjectToInt(dataRow3["PermissionValue"]);
                                            base_ModulePermissionInfo.PermissionTitle = TypeUtil.ObjectToString(dataRow3["PermissionTitle"]);
                                            base_ModulePermissionInfo.PermissionValue = num4;
                                            if (rolePermissionList != null && rolePermissionList.Tables.Count > 0 && rolePermissionList.Tables[0].Rows.Count > 0)
                                            {
                                                DataRow[] array5 = rolePermissionList.Tables[0].Select("RoleID=" + num + " and ModuleID=" + num3);
                                                int       num5   = 0;
                                                if (array5 != null && array5.Count() > 0)
                                                {
                                                    num5 = TypeUtil.ObjectToInt(array5[0]["OperationPermission"]);
                                                }
                                                base_ModulePermissionInfo.IsChecked = (num5 != 0 && TypeUtil.IsExit(num5, num4));
                                            }
                                            else
                                            {
                                                base_ModulePermissionInfo.IsChecked = false;
                                            }
                                            list3.Add(base_ModulePermissionInfo);
                                        }
                                        base_ModuleSubInfo.Base_ModulePermissionInfoes = list3;
                                    }
                                    if (base_ModuleSubInfo != null)
                                    {
                                        list2.Add(base_ModuleSubInfo);
                                    }
                                }
                                if (list2 != null && list2.Count > 0)
                                {
                                    base_ModuleInfo.Base_ModuleSubInfoes = list2;
                                }
                            }
                            if (base_ModuleInfo != null && base_ModuleInfo.Base_ModuleSubInfoes != null && base_ModuleInfo.Base_ModuleSubInfoes.Count > 0)
                            {
                                list.Add(base_ModuleInfo);
                            }
                        }
                    }
                }
            }
            if (list != null && list.Count > 0)
            {
                foreach (Base_ModuleInfo item in list)
                {
                    foreach (Base_ModuleSubInfo base_ModuleSubInfo2 in item.Base_ModuleSubInfoes)
                    {
                        if (base_ModuleSubInfo2.Base_ModulePermissionInfoes != null && base_ModuleSubInfo2.Base_ModulePermissionInfoes.Count > 0)
                        {
                            base_ModuleSubInfo2.Base_ModulePermissionInfoes = (from p in base_ModuleSubInfo2.Base_ModulePermissionInfoes
                                                                               where p.PermissionTitle != ""
                                                                               select p).ToList();
                        }
                    }
                }
                foreach (Base_ModuleInfo item2 in list)
                {
                    if (item2.Base_ModuleSubInfoes != null && item2.Base_ModuleSubInfoes.Count > 0)
                    {
                        item2.Base_ModuleSubInfoes = item2.Base_ModuleSubInfoes.Where(delegate(Base_ModuleSubInfo p)
                        {
                            if (p.Title != "")
                            {
                                return(p.Base_ModulePermissionInfoes != null);
                            }
                            return(false);
                        }).ToList();
                    }
                }
                if (list != null && list.Count > 0)
                {
                    list = list.Where(delegate(Base_ModuleInfo p)
                    {
                        if (p.Title != "" && p.Base_ModuleSubInfoes != null)
                        {
                            return(p.Base_ModuleSubInfoes.Count > 0);
                        }
                        return(false);
                    }).ToList();
                }
            }
            base.ViewData["data"] = list;
            return(View());
        }
Ejemplo n.º 28
0
        public void VisitNode(JSBinaryOperatorExpression boe)
        {
            var leftType  = boe.Left.GetActualType(TypeSystem);
            var rightType = boe.Right.GetActualType(TypeSystem);

            // We can end up with a pointer literal in an arithmetic expression.
            // In this case we want to switch it back to a normal integer literal so that the math operations work.
            var leftPointer  = boe.Left as JSPointerLiteral;
            var rightPointer = boe.Right as JSPointerLiteral;

            if (!(boe.Operator is JSAssignmentOperator))
            {
                if (leftPointer != null)
                {
                    boe.ReplaceChild(boe.Left, JSIntegerLiteral.New(leftPointer.Value));
                }
                if (rightPointer != null)
                {
                    boe.ReplaceChild(boe.Right, JSIntegerLiteral.New(rightPointer.Value));
                }
            }

            JSExpression replacement = null;

            if (leftType.IsPointer && TypeUtil.IsIntegral(rightType))
            {
                if (
                    (boe.Operator == JSOperator.Add) ||
                    (boe.Operator == JSOperator.AddAssignment)
                    )
                {
                    replacement = new JSPointerAddExpression(
                        boe.Left, boe.Right,
                        boe.Operator == JSOperator.AddAssignment
                        );
                }
                else if (
                    (boe.Operator == JSOperator.Subtract) ||
                    (boe.Operator == JSOperator.SubtractAssignment)
                    )
                {
                    // FIXME: Int32 is probably wrong
                    replacement = new JSPointerAddExpression(
                        boe.Left,
                        new JSUnaryOperatorExpression(JSOperator.Negation, boe.Right, TypeSystem.Int32),
                        boe.Operator == JSOperator.SubtractAssignment
                        );
                }
            }
            else if (leftType.IsPointer && rightType.IsPointer)
            {
                if (boe.Operator == JSOperator.Subtract)
                {
                    // FIXME: Int32 is probably wrong
                    replacement = new JSPointerDeltaExpression(
                        boe.Left, boe.Right, TypeSystem.Int32
                        );
                }
                else if (boe.Operator is JSComparisonOperator)
                {
                    replacement = new JSPointerComparisonExpression(boe.Operator, boe.Left, boe.Right, boe.ActualType);
                }
            }

            if (replacement != null)
            {
                ParentNode.ReplaceChild(boe, replacement);
                VisitReplacement(replacement);
            }
            else
            {
                VisitChildren(boe);
            }
        }
Ejemplo n.º 29
0
        public void ApplyPresetMPN(Maid maid, PresetData preset, bool applyBody, bool applyWear, bool castoff)
        {
            // 衣装チェンジ
            foreach (var mpn in preset.mpns)
            {
                if (!applyBody)
                {
                    // bodyのMPNをスキップ
                    if (TypeUtil.IsBody(mpn.name))
                    {
                        continue;
                    }
                }
                if (!applyWear)
                {
                    // wearのMPNをスキップ
                    if (TypeUtil.IsWear(mpn.name))
                    {
                        continue;
                    }
                }
                // menuファイルが存在しない場合はスキップ
                if (!_fileUtil.Exists(mpn.filename))
                {
                    continue;
                }

                var prop = maid.GetProp(mpn.name);
                if (mpn.filename.Equals(prop.strFileName, StringComparison.OrdinalIgnoreCase))
                {
                    LogUtil.Debug("apply preset skip. mpn:", mpn.name, ", file:", mpn.filename);
                    continue;
                }

                if (mpn.name == MPN.body)
                {
                    LogUtil.Log("ACCexプリセットのbodyメニューの適用は現在未対応です。スキップします。", mpn.filename);
                    continue;
                }

                if (mpn.filename.EndsWith("_del.menu", StringComparison.OrdinalIgnoreCase))
                {
                    if (castoff)
                    {
                        // 対象のMPNが空でかつ、指定アイテムが削除アイテムと同一であればスキップ
                        if (prop.nFileNameRID == 0)
                        {
                            if (CM3.dicDelItem[mpn.name].Equals(mpn.filename, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                        }
                        // LogUtil.Debug("apply prop(del): ", mpn.filename, ", old:", prop.strFileName);
                        if (SetProp != null)
                        {
                            SetProp(maid, mpn.name, mpn.filename, 0);
                        }
                    }
                    continue;
                    // } else if (mpn.filename.EndsWith(".mod", StringComparison.OrdinalIgnoreCase)) {
                }

                // LogUtil.Debug("apply prop: ", mpn.filename, ", old:", prop.strFileName);
                if (SetProp != null)
                {
                    SetProp(maid, mpn.name, mpn.filename, 0);
                }
            }
        }
Ejemplo n.º 30
0
        public void Should_TypeId_ContainNullValue()
        {
            var typeId = TypeId.Double | TypeId.NullValue;

            Assert.AreEqual(true, TypeUtil.IsNullValue(typeId));
        }