internal State(BinaryFormatter parent, SerializationHintsAttribute hints, Type t)
			{
				BinaryFormatter.WriteLine("New State: {0}", t != null ? t.FullName : "<null>");

				TypeDescriptor td = (t != null) ? new TypeDescriptor(t) : null;

				m_parent = parent;
				m_value = new TypeHandler(parent, hints, td);
			}
        public void Build_with_exactly_15_arguments()
        {
            //15 is the maximum number of arguments without having to put actions/funcs/predicates in an object array.
            //This comes from BuildLambdaExpression builds a Func, and Funcs may only have 16 input args: Func<T1,...,T16,TResult>
            //T1-argument is reserved for the obligatory value argument, which leaves us with 15 arguments to be used for the
            //actions/funcs/predicates
            string updatedValue = null;

            //Handle a string with one action
            var                typeHandlers    = new List <TypeHandler>();
            var                stringHandler   = new TypeHandler(typeof(string));
            Action <string>    actionString    = s => { };
            Predicate <string> predicateString = s => false;

            for (var i = 0; i < 7; i++)
            {
                stringHandler.Handlers.Add(PredicateAndHandler.CreateAction(actionString, predicate: predicateString));
            }
            typeHandlers.Add(stringHandler);

            var intHandler = new TypeHandler(typeof(int));
            //Handle an int with one action
            Action <int> actionInt = i => { updatedValue = i.ToString(); };
            var          handler2  = PredicateAndHandler.CreateAction(actionInt);

            intHandler.Handlers.Add(handler2);
            typeHandlers.Add(intHandler);

            //Build the expression
            var builder = new MatchExpressionBuilder <object>();
            var result  = builder.BuildLambdaExpression(typeHandlers);

            //Verify returned arguments
            XAssert.Equal(15, result.Arguments.Length, "Should contain the action and predicate delegates");
            var lastArgument = result.Arguments.Last();

            Assert.IsNotType <object[]>(lastArgument); //Last argument should not be an object[]

            //Compile the expression and test it
            var lambda = (Func <object, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <String>, Predicate <string>, Action <int>, bool>)
                         result.LambdaExpression.Compile();

            lambda("some value", actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionInt);
            Assert.Equal(null, updatedValue);
            lambda(4711, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionString, predicateString, actionInt);
            Assert.Equal("4711", updatedValue);
        }
Esempio n. 3
0
        public static SnComponentInfo Create(ISnComponent component)
        {
            var asmVersion = TypeHandler.GetVersion(component.GetType().Assembly);

            if (component.SupportedVersion > asmVersion)
            {
                throw new ApplicationException($"Invalid component: {component.ComponentId}: supported version ({component.SupportedVersion}) cannot be greater than the assembly version ({asmVersion}).");
            }

            return(new SnComponentInfo
            {
                ComponentId = component.ComponentId,
                SupportedVersion = component.SupportedVersion ?? asmVersion,
                AssemblyVersion = asmVersion,
                IsComponentAllowed = component.IsComponentAllowed
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Insert rows in table or ignores if exists
        /// </summary>
        /// <param name="conn">A connection</param>
        /// <param name="table">Name of table to insert into</param>
        /// <param name="dataList">List of objects containing the data</param>
        /// <param name="pk">Name of primary key field</param>
        /// <param name="transaction">Transaction to associate with the command</param>
        /// <returns>Rows affected</returns>
        public static int InsertIfMissing(this DbConnection conn, string table, IEnumerable <object> dataList, string pk, DbTransaction transaction = null)
        {
            TypeDescriber td = TypeHandler.Get(dataList.First());

            string columns = string.Join(",", td.WriteableColumns.Select(x => x.DbName));
            string values  = string.Join(",", dataList.Select((data, i) => $"({string.Join(",", td.WriteableColumns.Select(x => "@" + x.Property.Name + i))})"));

            string sql = $@"
                INSERT INTO {table} ({columns}) VALUES {values}
                ON CONFLICT ({pk}) DO NOTHING";

            DbCommand cmd = conn.Prepare(sql, transaction);

            cmd.ApplyParameters(dataList);

            return(cmd.ExecuteNonQuery());
        }
Esempio n. 5
0
        // This changes the type
        public void ChangeType(int typeindex)
        {
            // Can't do this for a fixed field!
            if (isfixed)
            {
                throw new InvalidOperationException();
            }

            // Different?
            if (typeindex != fieldtype.Index)
            {
                // Change field type!
                TypeHandlerAttribute attrib = General.Types.GetAttribute(typeindex);
                fieldtype           = General.Types.GetFieldHandler(typeindex, this.Cells[2].Value);
                this.Cells[1].Value = fieldtype.GetDisplayType();
            }
        }
Esempio n. 6
0
        private void Load()
        {
            engines = new Dictionary <string, IEvaluator>();
            foreach (var type in TypeHandler.GetTypesByInterface(typeof(IEvaluator)))
            {
                var attrs = (ScriptTagNameAttribute[])type.GetCustomAttributes(typeof(ScriptTagNameAttribute), false);
                if (attrs.Length == 0)
                {
                    throw new ApplicationException(String.Concat(
                                                       "Evaluator has not ScriptTagNameAttribute: ", type.FullName, " (Assembly: ", type.Assembly.ToString(), ")"));
                }
                var engine = (IEvaluator)Activator.CreateInstance(type);
                engines.Add(attrs[0].TagName, engine);

                Logger.WriteInformation(String.Concat("Add Evaluator: ", attrs[0].TagName, "."), Logger.GetDefaultProperties, engine);
            }
        }
Esempio n. 7
0
        public void Encode(object data, IClient client, IBinaryWriter writer)
        {
            using (IWriteBlock msgsize = writer.Allocate4Bytes())
            {
                int length = (int)writer.Length;
                TypeHandler.WriteType(data, writer);
                using (IWriteBlock bodysize = writer.Allocate4Bytes())
                {
                    int    bodyStartlegnth = (int)writer.Length;
                    string strData         = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    writer.Write(strData);

                    bodysize.SetData((int)writer.Length - bodyStartlegnth);
                }
                msgsize.SetData((int)writer.Length - length);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Insert rows in table or ignores if exists
        /// </summary>
        /// <param name="conn">A connection</param>
        /// <param name="table">Name of table to insert into</param>
        /// <param name="dataList">List of objects containing the data</param>
        /// <param name="pk">Name of primary key field</param>
        /// <param name="transaction">Transaction to associate with the command</param>
        /// <param name="cancellationToken">Cancellationtoken</param>
        /// <returns>Rows affected</returns>
        public static async Task <int> InsertIfMissingAsync(this DbConnection conn, string table, IEnumerable <object> dataList, string pk, DbTransaction transaction = null, CancellationToken cancellationToken = default)
        {
            TypeDescriber td = TypeHandler.Get(dataList.First());

            string columns = string.Join(",", td.WriteableColumns.Select(x => x.DbName));
            string values  = string.Join(",", dataList.Select((data, i) => $"({string.Join(",", td.WriteableColumns.Select(x => "@" + x.Property.Name + i))})"));

            string sql = $@"
                INSERT INTO {table} ({columns}) VALUES {values}
                ON CONFLICT ({pk}) DO NOTHING";

            DbCommand cmd = await conn.PrepareAsync(sql, transaction, cancellationToken).ConfigureAwait(false);

            cmd.ApplyParameters(dataList);

            return(await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false));
        }
Esempio n. 9
0
        public override void Save(NodeSaveSettings settings)
        {
            // Check uniqueness first
            CheckUniqueUser();
            if (base.IsPropertyChanged("CreationDate"))
            {
                if (_password != null)
                {
                    this.PasswordHash = PasswordHashProvider.EncodePassword(_password, this);
                }
            }

            Domain = GenerateDomain();

            var originalId = this.Id;

            // save current password to the list of old passwords
            this.SaveCurrentPassword();

            base.Save(settings);

            // AD Sync
            SynchUser(originalId);

            // set creator for performant self permission setting
            // creator of the user will always be the user itself. this way setting permissions to the creators group on /Root/IMS will be adequate for user permissions
            // if you need the original creator, use the auditlog
            if (originalId == 0)
            {
                //need to clear this flag to avoid getting an 'Id <> 0' error during copying
                this.CopyInProgress   = false;
                this.CreatedBy        = this;
                this.VersionCreatedBy = this;
                this.DisableObserver(TypeHandler.GetType(NodeObserverNames.NOTIFICATION));
                this.DisableObserver(TypeHandler.GetType(NodeObserverNames.WORKFLOWNOTIFICATION));

                base.Save(SavingMode.KeepVersion);
            }

            // create profiles
            if (originalId == 0 && Repository.UserProfilesEnabled)
            {
                CreateProfile();
            }
        }
Esempio n. 10
0
        internal void DoStart()
        {
            ConsoleWriteLine();
            ConsoleWriteLine("Starting Repository...");
            ConsoleWriteLine();

            LoggingSettings.SnTraceConfigurator.UpdateStartupCategories();

            TypeHandler.Initialize(_settings.Providers);

            InitializeLogger();

            // Lucene subsystem behaves strangely if the enums are not initialized.
            var x = Lucene.Net.Documents.Field.Index.NO;
            var y = Lucene.Net.Documents.Field.Store.NO;
            var z = Lucene.Net.Documents.Field.TermVector.NO;

            CounterManager.Start();

            RegisterAppdomainEventHandlers();

            if (_settings.IndexPath != null)
            {
                StorageContext.Search.SetIndexDirectoryPath(_settings.IndexPath);
            }
            RemoveIndexWriterLockFile();
            _startupInfo.IndexDirectory = System.IO.Path.GetDirectoryName(StorageContext.Search.IndexLockFilePath);

            LoadAssemblies();

            SenseNet.ContentRepository.Storage.Security.SecurityHandler.StartSecurity(_settings.IsWebContext);

            using (new SenseNet.ContentRepository.Storage.Security.SystemAccount())
                StartManagers();

            LoggingSettings.SnTraceConfigurator.UpdateCategories();

            InitializeOAuthProviders();

            ConsoleWriteLine();
            ConsoleWriteLine("Repository has started.");
            ConsoleWriteLine();

            _startupInfo.Started = DateTime.UtcNow;
        }
Esempio n. 11
0
        protected override string GetQueryFilter()
        {
            var originalQueryFilter = base.GetQueryFilter();

            if (SearchForm == null)
            {
                return(originalQueryFilter);
            }

            SearchForm.UpdateContent();

            DefaultQueryBuilder qBuilder;

            if (string.IsNullOrEmpty(PluginFullPath))
            {
                qBuilder = new DefaultQueryBuilder(originalQueryFilter, SearchForm.Content, EmptyQueryTerm);
            }
            else
            {
                qBuilder = TypeHandler.CreateInstance(PluginFullPath, new object[] { originalQueryFilter, SearchForm.Content }) as DefaultQueryBuilder;
            }

            var filter = qBuilder.BuildQuery(/*kv*/);

            var sb     = new StringBuilder();
            var writer = XmlWriter.Create(sb);

            writer.WriteStartDocument();
            writer.WriteStartElement("ContentMetaData");
            writer.WriteElementString("ContentType", SearchForm.Content.ContentType.Name);
            writer.WriteElementString("ContentName", SearchForm.Content.Name);
            writer.WriteStartElement("Fields");

            SearchForm.Content.ExportFieldData(writer, new ExportContext("/Root", ""));

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();

            _state.ExportQueryFields = sb.ToString();
            PortletState.Persist(_state);

            return(filter);
        }
Esempio n. 12
0
        public void ApplyMigrations(ApplyMigrationCriteria criteria)
        {
            var repoInfo = TypeHandler.FindSingleRepo(criteria.ProjectPath, criteria.RepoName);

            if (repoInfo == null)
            {
                return;
            }

            var repoBase         = TypeHandler.CreateRepoBase(repoInfo.Assembly.Location, repoInfo.RepoType);
            var connectionString = ConnectionStringHandler.FindConnectionString(repoBase, criteria.ConfigFilePath);

            ConnectionStringHandler.OverrideConnectionString(repoBase, connectionString);

            var migrationTypes = TypeHandler.FindAllMigrations(criteria.ProjectPath, repoInfo.RepoType);

            if (migrationTypes == null || !migrationTypes.Any())
            {
                LoggerBase.Log("No migrations to run.");
                return;
            }

            var migrationRepo  = new MigrationRepo(connectionString);
            var doneMigrations = migrationRepo.GetMigrationsThatHaveRun(repoInfo.RepoType.Name);

            //only run on migrations that have not been run yet.
            //order by name, ie. datestamp.
            foreach (var migrationType in migrationTypes.Where(m => !doneMigrations.Contains(m.Name)).OrderBy(m => m.Name))
            {
                var migration = Activator.CreateInstance(migrationType) as AbstractBaseMigration;
                if (migration == null)
                {
                    LoggerBase.Log("Error creating migration: " + migrationType.Name);
                    throw new ApplicationException("Error creating migration: " + migrationType.Name);
                }

                //use reflection to set the internal base repo
                PropertyInfo baseRepoPropertyInfo = migrationType.GetProperty("BaseRepo", BindingFlags.Instance | BindingFlags.NonPublic);
                baseRepoPropertyInfo.SetValue(migration, repoBase);

                LoggerBase.Log(string.Format("Executing Migration: {0}", migrationType.Name));
                migration.Execute();
                migrationRepo.LogMigrationRan(migrationType.Name, repoInfo.RepoType.Name);
            }
        }
Esempio n. 13
0
        private void SaveFieldSetting()
        {
            var fsName = this.Name;

            if (!fsName.StartsWith("#"))
            {
                fsName = string.Concat("#", fsName);
            }

            if (this._isNew)
            {
                //set field index default to int.Max to place
                //the new field at the end of the field list
                this.FieldIndex = int.MaxValue;
            }

            if (this._isNew && this.ContentList.FieldSettings.Any(fs => fs.Name.CompareTo(fsName) == 0))
            {
                //field already exists with this name
                throw new InvalidOperationException(HttpContext.GetGlobalResourceObject("FieldEditor", "FieldError_FieldExists") as string);
            }

            if (string.Compare(this.FieldSetting.Name, fsName) != 0)
            {
                //field setting was renamed, remove the old one
                this.ContentList.DeleteField(this.FieldSetting);

                this.FieldSetting.Name = fsName;
            }

            this.ContentList.AddOrUpdateField(this.FieldSetting);

            if (!this._isNew || !this.AddToDefaultView)
            {
                return;
            }

            //add to default view
            var ivm = TypeHandler.ResolveNamedType <IViewManager>("ViewManager");

            if (ivm != null)
            {
                ivm.AddToDefaultView(this.FieldSetting, this.ContentList);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Insert rows in table or updates if exists
        /// </summary>
        /// <param name="conn">A connection</param>
        /// <param name="table">Name of table to upsert into</param>
        /// <param name="dataList">List of objects containing the data</param>
        /// <param name="pk">Name of primary key field</param>
        /// <param name="transaction">Transaction to associate with the command</param>
        /// <param name="cancellationToken">Cancellationtoken</param>
        /// <returns>IEnumerable of true when inserted, false when updated</returns>
        public static async Task <IEnumerable <bool> > UpsertAsync(this DbConnection conn, string table, IEnumerable <object> dataList, string pk, DbTransaction transaction = null, CancellationToken cancellationToken = default)
        {
            TypeDescriber td = TypeHandler.Get(dataList.First());

            string columns = string.Join(",", td.WriteableColumns.Select(x => x.DbName));
            string values  = string.Join(",", dataList.Select((data, i) => $"({string.Join(",", td.WriteableColumns.Select(x => "@" + x.Property.Name + i))})"));
            string set     = string.Join(",", td.WriteableColumns.Select(x => x.DbName + "=excluded." + x.DbName));

            string sql = $@"
                INSERT INTO {table} ({columns}) VALUES {values}
                ON CONFLICT ({pk}) DO UPDATE SET {set} RETURNING (xmax = 0) as inserted";

            DbCommand cmd = await conn.PrepareAsync(sql, transaction, cancellationToken).ConfigureAwait(false);

            cmd.ApplyParameters(dataList);

            return(await conn.ScalarListAsync <bool>(cmd, cancellationToken).ToListAsync().ConfigureAwait(false));
        }
Esempio n. 15
0
        /// <summary>
        /// Insert rows in table or updates if exists
        /// </summary>
        /// <param name="conn">A connection</param>
        /// <param name="table">Name of table to upsert into</param>
        /// <param name="dataList">List of objects containing the data</param>
        /// <param name="pk">Name of primary key field</param>
        /// <param name="transaction">Transaction to associate with the command</param>
        /// <returns>IEnumerable of true when inserted, false when updated</returns>
        public static IEnumerable <bool> Upsert(this DbConnection conn, string table, IEnumerable <object> dataList, string pk, DbTransaction transaction = null)
        {
            TypeDescriber td = TypeHandler.Get(dataList.First());

            string columns = string.Join(",", td.WriteableColumns.Select(x => x.DbName));
            string values  = string.Join(",", dataList.Select((data, i) => $"({string.Join(",", td.WriteableColumns.Select(x => "@" + x.Property.Name + i))})"));
            string set     = string.Join(",", td.WriteableColumns.Select(x => x.DbName + "=excluded." + x.DbName));

            string sql = $@"
                INSERT INTO {table} ({columns}) VALUES {values}
                ON CONFLICT ({pk}) DO UPDATE SET {set} RETURNING (xmax = 0) as inserted";

            DbCommand cmd = conn.Prepare(sql, transaction);

            cmd.ApplyParameters(dataList);

            return(conn.ScalarList <bool>(cmd));
        }
Esempio n. 16
0
        public void Register(Type type, string fullPath)
        {
            if (_cache.IsExist(type))
            {
                return;
            }

            if (ReflectionHelper.HasAttribute <ScriptIgnoreAttribute>(type))
            {
                return;
            }

            var handler = new TypeHandler(_luaState);

            handler.Initilaze(new object[] { type, fullPath });
            handler.Reg2Env();
            _cache.Add(type, handler);
        }
Esempio n. 17
0
        public void Packaging_EzRelease_CreateComponentInfo_SupportedVersionGreaterThanThisVersion()
        {
            var thisVersion            = TypeHandler.GetVersion(this.GetType().Assembly);
            var supportedVersion       = new Version(thisVersion.Major, thisVersion.Minor + 1, 0);
            var supportedVersionString = supportedVersion.ToString();
            var componentName          = "TestComponent-1";
            var component = new TestComponent(componentName, supportedVersionString, false);

            try
            {
                var componentInfo = SnComponentInfo.Create(component);
                Assert.Fail();
            }
            catch (ApplicationException)
            {
                // do nothing
            }
        }
Esempio n. 18
0
        public Node CreateInstance(Node parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (_type == null)
            {
                _type = TypeHandler.GetType(_className);
            }

            if (_type == null)
            {
                string exceptionMessage = String.Concat("Type not found, therefore the node can't be created.",
                                                        "\nClass name: ", _className,
                                                        "\nNode type path: ", _nodeTypePath,
                                                        "\nParent class name: ", (_parent != null ? _parent._className : "Parent is null"), "\n");
                throw new ApplicationException(exceptionMessage);
            }

            //---- only public ctor is valid: public NodeDescendant(Node parent, string nodeTypeName)
            ConstructorInfo ctor = _type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, _newArgTypes, null);

            if (ctor == null)
            {
                throw new TypeInitializationException(String.Concat("Constructor not found. Valid signature: ctor(Node, string).\nClassName: ", _className), null);
            }

            Node node;

            try
            {
                node = (Node)ctor.Invoke(new object[] { parent, this.Name });
            }
            catch (Exception ex)             //rethrow
            {
                throw new ApplicationException(String.Concat("Couldn't create an instance of type '", _className,
                                                             "'. The invoked constructor threw an exception of type ", ex.GetType().Name, " (it said '", ex.Message, "')."), ex);
            }

            return(node);
        }
Esempio n. 19
0
        /// <summary>
        /// Read data from database
        /// </summary>
        /// <typeparam name="T">class to map data to</typeparam>
        /// <param name="conn">A connection</param>
        /// <param name="cmd">Command to be executed</param>
        /// <returns>IEnumerable of T</returns>
        public static IEnumerable <T> Query <T>(this DbConnection conn, DbCommand cmd) where T : new()
        {
            using (var reader = cmd.ExecuteReader())
            {
                var td = TypeHandler.Get <T>();

                while (reader.Read())
                {
                    var result = new T();

                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        td.SetValue(reader.GetName(i), result, reader.GetValueWithNull(i));
                    }

                    yield return(result);
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Read data from database
        /// </summary>
        /// <typeparam name="T">class to map data to</typeparam>
        /// <param name="conn">A connection</param>
        /// <param name="cmd">Command to be executed</param>
        /// <param name="cancellationToken">Cancellationtoken</param>
        /// <returns>IAsyncEnumerable of T</returns>
        public static async IAsyncEnumerable <T> QueryAsync <T>(this DbConnection conn, DbCommand cmd, [EnumeratorCancellation] CancellationToken cancellationToken = default) where T : new()
        {
            using (var reader = await cmd.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
            {
                var td = TypeHandler.Get <T>();

                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    var result = new T();

                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        td.SetValue(reader.GetName(i), result, reader.GetValueWithNull(i));
                    }

                    yield return(result);
                }
            }
        }
Esempio n. 21
0
        public static File CreateByBinary(IFolder parent, BinaryData binaryData)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (binaryData == null)
            {
                return(new File(parent as Node));
            }

            File file;
            // Resolve filetype by binary-config matching
            BinaryTypeResolver resolver = new BinaryTypeResolver();

            if (!resolver.ParseBinary(binaryData))
            {
                // Unknown file type
                file = new File(parent as Node);
            }
            else
            {
                // Specific File subtype has been found
                file = TypeHandler.CreateInstance <File>(resolver.NodeType.ClassName, parent);

                var fname = binaryData.FileName.FileNameWithoutExtension;
                if (string.IsNullOrEmpty(fname))
                {
                    fname = file.Name;
                }
                else if (fname.Contains("\\"))
                {
                    fname = System.IO.Path.GetFileNameWithoutExtension(fname);
                }

                binaryData.FileName    = new BinaryFileName(fname, resolver.FileNameExtension);
                binaryData.ContentType = resolver.ContentType;
            }

            file.Binary = binaryData;
            return(file);
        }
Esempio n. 22
0
        private void CreateLayout()
        {
            switch (PortletType)
            {
            case PreviewPortletType.ContentCollectionPortlet:
                var collectionPortlet = TypeHandler.CreateInstance("SenseNet.Portal.Portlets.ContentCollectionPortlet") as ContextBoundPortlet;
                collectionPortlet.ID             = "previewedPortlet";
                collectionPortlet.BindTarget     = SenseNet.Portal.UI.PortletFramework.BindTarget.CustomRoot;
                collectionPortlet.CustomRootPath = CustomRootPath;
                collectionPortlet.RenderingMode  = RenderingMode;
                collectionPortlet.Renderer       = Renderer;
                //this.form1.Controls.Add(collectionPortlet);
                renderedContent.Controls.Add(collectionPortlet);
                break;

            default:
                break;
            }
        }
Esempio n. 23
0
        public void Build_two_actions_and_predicate_for_same_type()
        {
            string updatedValue = null;

            //Handle a string with one action
            var                typeHandlers  = new List <TypeHandler>();
            var                stringHandler = new TypeHandler(typeof(string));
            Action <string>    action1       = s => { updatedValue = s; };
            Predicate <string> predicate1    = s => s.Length > 5 && s.Length < 15;
            var                handler1      = PredicateAndHandler.CreateAction(action1, predicate: predicate1);

            stringHandler.Handlers.Add(handler1);
            Action <string>    action2    = s => { updatedValue = "action2"; };
            Predicate <string> predicate2 = s => s.Length >= 15 && s.Length < 20;
            var handler2 = PredicateAndHandler.CreateAction(action2, predicate: predicate2);

            stringHandler.Handlers.Add(handler2);
            typeHandlers.Add(stringHandler);
            var builder = new MatchExpressionBuilder <object>();

            //Build the expression
            var result = builder.BuildLambdaExpression(typeHandlers);

            //Verify returned arguments
            XAssert.Equal(4, result.Arguments.Length, "Should contain the action and predicate delegate");
            Assert.Same(action1, result.Arguments[0]);
            Assert.Same(predicate1, result.Arguments[1]);
            Assert.Same(action2, result.Arguments[2]);
            Assert.Same(predicate2, result.Arguments[3]);

            //Compile the expression and test it
            var lambda = (Func <object, Action <String>, Predicate <string>, Action <String>, Predicate <string>, bool>)result.LambdaExpression.Compile();

            lambda("short", action1, predicate1, action2, predicate2);
            Assert.Equal(null, updatedValue);
            lambda("longer value", action1, predicate1, action2, predicate2);
            Assert.Equal("longer value", updatedValue);
            lambda("1234567890123456789", action1, predicate1, action2, predicate2);
            Assert.Equal("action2", updatedValue);
            lambda(4711, action1, predicate1, action2, predicate2);
            Assert.Equal("action2", updatedValue);
        }
Esempio n. 24
0
        public void Encode(object data, IClient client, IBinaryWriter writer)
        {
            Message msg = data as Message;

            if (msg != null)
            {
                msg.Track("message GetType");
                msg.DataType = TypeHandler.GetMessageType(msg.Data.GetType()).TypeName;
            }
            using (IWriteBlock msgsize = writer.Allocate4Bytes())
            {
                int length = (int)writer.Length;
                TypeHandler.WriteType(data, writer);
                using (IWriteBlock bodysize = writer.Allocate4Bytes())
                {
                    int bodyStartlegnth = (int)writer.Length;
                    data.Serialize(writer.Stream);
                    bodysize.SetData((int)writer.Length - bodyStartlegnth);
                }
                if (msg != null)
                {
                    msg.Track("message write body");
                    using (IWriteBlock datasize = writer.Allocate4Bytes())
                    {
                        int    dataStartlength = (int)writer.Length;
                        object body            = msg.Data;
                        if (body is ISerializer)
                        {
                            ((ISerializer)body).Serialize(writer);
                        }
                        else
                        {
                            msg.Data.Serialize(writer.Stream);
                        }
                        datasize.SetData((int)writer.Length - dataStartlength);
                    }
                    msg.Track("message write body completed!");
                    msg.Track("message size:" + writer.Length);
                }
                msgsize.SetData((int)writer.Length - length);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the data base value.
        /// </summary>
        /// <param name="dataReader">The data reader.</param>
        /// <returns></returns>
        public object GetDataBaseValue(IDataReader dataReader)
        {
            object value = null;

            ///Add by me. 用列名称解决分页之后造成的下标错位问题
            if (!string.IsNullOrEmpty(ColumnName))
            {
                value = TypeHandler.GetValueByName(this, dataReader);
            }
            ///
            else if (columnIndex == UNKNOWN_COLUMN_INDEX)
            {
                value = TypeHandler.GetValueByName(this, dataReader);
            }
            else
            {
                value = TypeHandler.GetValueByIndex(this, dataReader);
            }

            bool wasNull = (value == DBNull.Value);

            if (wasNull)
            {
                if (this.HasNullValue)
                {
                    if (setAccessor != null)
                    {
                        value = TypeHandler.ValueOf(setAccessor.MemberType, nullValue);
                    }
                    else
                    {
                        value = TypeHandler.ValueOf(null, nullValue);
                    }
                }
                else
                {
                    value = TypeHandler.NullValue;
                }
            }

            return(value);
        }
Esempio n. 26
0
 public EModel UseDefaultConstructor()
 {
     if (TypeHandler.IsClass && !TypeHandler.IsArray && TypeHandler != typeof(string) && Builder != null)
     {
         //使用默认构造函数
         ConstructorInfo ctor = TypeHandler.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
         if (ctor == null)
         {
             throw new InvalidOperationException("Type [" + TypeHandler.FullName + "] should have default public or non-public constructor");
         }
         il.REmit(OpCodes.Newobj, ctor);
         il.EmitStoreBuilder(Builder);
     }
     else if (IsStruct)
     {
         il.REmit(OpCodes.Ldloca_S, Builder);
         il.InitObject(TypeHandler);
     }
     return(this);
 }
Esempio n. 27
0
        private static void LoadProperty(XmlElement xmlNode, SmartSqlMapConfig sqlMapConfig, XmlNamespaceManager xmlNsM, ResultMap resultMap)
        {
            var resultNodes = xmlNode.SelectNodes("./ns:Result", xmlNsM);

            foreach (XmlNode resultNode in resultNodes)
            {
                var property = new Property
                {
                    Name        = resultNode.Attributes["Property"].Value,
                    Column      = (resultNode.Attributes["Column"] ?? resultNode.Attributes["Property"]).Value,
                    TypeHandler = resultNode.Attributes["TypeHandler"]?.Value
                };
                if (!String.IsNullOrEmpty(property.TypeHandler))
                {
                    TypeHandler typeHandler = TypeHanderNotNull(sqlMapConfig, property.TypeHandler);
                    property.Handler = typeHandler.Handler;
                }
                resultMap.Properties.Add(property);
            }
        }
Esempio n. 28
0
        public void Decode(IClient client, IBinaryReader reader)
        {
START:
            try
            {
                object data;
                if (mSize == 0)
                {
                    if (reader.Length < 4)
                    {
                        return;
                    }
                    mSize = reader.ReadInt32();
                }
                if (reader.Length < mSize)
                {
                    return;
                }
                Type type     = TypeHandler.ReadType(reader);
                int  bodySize = reader.ReadInt32();
                data  = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadString(bodySize), type);
                mSize = 0;
                try
                {
                    if (Completed != null)
                    {
                        Completed(client, data);
                    }
                }
                catch (Exception e_)
                {
                    client.ProcessError(e_, "client packet process object error!");
                }
                goto START;
            }
            catch (Exception e_)
            {
                client.ProcessError(e_, "client packet decode error!");
                client.DisConnect();
            }
        }
Esempio n. 29
0
        internal static bool IsComponentAllowed(SnComponentInfo component, Version installedComponentVersion)
        {
            return(true);

            if (installedComponentVersion == null)
            {
                throw new InvalidOperationException($"{component.ComponentId} component is missing.");
            }

            var assemblyVersion = component.AssemblyVersion ?? TypeHandler.GetVersion(component.GetType().Assembly);

            // To be able to publish code hotfixes, we allow the revision number (the 4th element)
            // to be higher in the assembly (in case every other part equals). This assumes
            // that every repository change raises at least the build number (the 3rd one)
            // in the component's version.
            if (installedComponentVersion.Major != assemblyVersion.Major ||
                installedComponentVersion.Minor != assemblyVersion.Minor ||
                installedComponentVersion.Build != assemblyVersion.Build)
            {
                // Not allowed if the assembly is older than the matched component.
                if (assemblyVersion < installedComponentVersion)
                {
                    return(false);
                }

                // Not allowed if the component is older than the assembly can support.
                if (installedComponentVersion < component.SupportedVersion)
                {
                    return(false);
                }
            }

            // Call the customized function if there is.
            if (component.IsComponentAllowed != null)
            {
                return(component.IsComponentAllowed.Invoke(installedComponentVersion));
            }

            // Everything is fine, assembly is runnable.
            return(true);
        }
Esempio n. 30
0
        /// <summary>
        /// Deserialize a TypeHandler object
        /// </summary>
        /// <param name="node"></param>
        /// <param name="configScope"></param>
        /// <returns></returns>
        public static void Deserialize(XmlNode node, ConfigurationScope configScope)
        {
            TypeHandler handler = new TypeHandler();

            NameValueCollection prop = NodeUtils.ParseAttributes(node, configScope.Properties);

            handler.CallBackName = NodeUtils.GetStringAttribute(prop, "callback");
            handler.ClassName    = NodeUtils.GetStringAttribute(prop, "type");
            handler.DbType       = NodeUtils.GetStringAttribute(prop, "dbType");

            handler.Initialize();

            configScope.ErrorContext.MoreInfo = "Check the callback attribute '" + handler.CallBackName + "' (must be a classname).";
            ITypeHandler typeHandler = null;
            Type         type        = configScope.SqlMapper.TypeHandlerFactory.GetType(handler.CallBackName);
            object       impl        = Activator.CreateInstance(type);

            if (impl is ITypeHandlerCallback)
            {
                typeHandler = new CustomTypeHandler((ITypeHandlerCallback)impl);
            }
            else if (impl is ITypeHandler)
            {
                typeHandler = (ITypeHandler)impl;
            }
            else
            {
                throw new ConfigurationErrorsException("The callBack type is not a valid implementation of ITypeHandler or ITypeHandlerCallback");
            }

            //
            configScope.ErrorContext.MoreInfo = "Check the type attribute '" + handler.ClassName + "' (must be a class name) or the dbType '" + handler.DbType + "' (must be a DbType type name).";
            if (handler.DbType != null && handler.DbType.Length > 0)
            {
                configScope.DataExchangeFactory.TypeHandlerFactory.Register(TypeUtils.ResolveType(handler.ClassName), handler.DbType, typeHandler);
            }
            else
            {
                configScope.DataExchangeFactory.TypeHandlerFactory.Register(TypeUtils.ResolveType(handler.ClassName), typeHandler);
            }
        }
Esempio n. 31
0
        static SnJsonConverter()
        {
            var fieldConverterTypes = TypeHandler.GetTypesByBaseType(typeof(FieldConverter));

            _jsonConverters  = new List <JsonConverter>();
            _fieldConverters = new List <FieldConverter>();

            foreach (var fieldConverterType in fieldConverterTypes)
            {
                var fieldConverter = (FieldConverter)Activator.CreateInstance(fieldConverterType);
                _jsonConverters.Add(fieldConverter);
                _fieldConverters.Add(fieldConverter);
            }

            _jsonSettings = new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                Formatting         = Formatting.Indented,
                Converters         = JsonConverters
            };
        }
Esempio n. 32
-1
 public static IDisposable Override(TypeHandler handler)
 {
     return new TypeHandlerOverride(handler);
 }
Esempio n. 33
-1
 public TypeHandlerOverride(TypeHandler handler)
 {
     current = handler;
 }