/// <summary>
        /// Update general insurance by generate sql script
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="referenceData">Reference data, store reference value from general_insurance -> workbook</param>
        private void UpdateGeneralInsuranceBySQLScript(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, Dictionary<int, int?> referenceData)
        {
            //
            // Initialize
            string destinationDatabaseName = destinationDatabase.GetDatabaseName();
            string sqlScript = "-- This script updates general_insurance table when all records of workbooks table are mapped." + Environment.NewLine +
                               "USE [" + destinationDatabaseName + "]" + Environment.NewLine +
                               "GO" + Environment.NewLine;
            string updateTemplate = "UPDATE {DESTINATION_DATABASE_NAME}.dbo." + Environment.NewLine +
                                    "SET genins_current_workbook = {REFERENCE_VALUE}" + Environment.NewLine +
                                    "WHERE genins_id = {PRIMARY_KEY_VALUE}" + Environment.NewLine;
            updateTemplate.Replace("{DESTINATION_DATABASE_NAME}", destinationDatabaseName);

            //
            // Generate update script
            foreach (int primaryKey in referenceData.Keys)
            {
                sqlScript = sqlScript + updateTemplate.Replace("{PRIMARY_KEY_VALUE}", primaryKey.ToString())
                                                      .Replace("{REFERENCE_VALUE}", referenceData[primaryKey].Value.ToString());
            }

            //
            // Append to workbook script
            manager.WriteSQLScript("workbooks", sqlScript, true);
        }
 protected UserController()
 {
     
     Log = ServiceLocator.Current.Resolve<ILog>();
     AuthenticationService = ServiceLocator.Current.Resolve<IAuthenticationService>();
     MappingManager = new MappingManager();
 }
 public static void CleanSourceDatabase()
 {
     EclipseDatabase source = new EclipseDatabase();
     BOALedgerDatabase destination = new BOALedgerDatabase();
     MappingManager manager = new MappingManager(source, destination);
     ValidationManager validationManager = new ValidationManager();
     validationManager.Validate<OrphanRecordValidation>(manager, source, destination);
 }
 /// <summary>
 /// Set blob pointer before mapping
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="sourceDatabase"></param>
 /// <param name="destinationDatabase"></param>
 /// <param name="obj"></param>
 public override void BeforeMappingRecord(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
 {
     DatabaseConversion.CleanerTool.BOALedgerDataAccess.EmailTemplates record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.EmailTemplates;
     if (this._temporyFilePath.ContainsKey(record.et_id))
     {
         record.et_blob_pointer = this._temporyFilePath[record.et_id];
     }
 }
 /// <summary>
 /// Set blob pointer before mapping
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="sourceDatabase"></param>
 /// <param name="destinationDatabase"></param>
 /// <param name="obj"></param>
 public override void BeforeMappingRecord(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
 {
     DatabaseConversion.CleanerTool.BOALedgerDataAccess.policy_transaction_documents record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.policy_transaction_documents;
     if (this._temporyFilePath.ContainsKey(record.poltrado_id))
     {
         record.poltrado_blob_pointer = this._temporyFilePath[record.poltrado_id];
     }
 }
 /// <summary>
 /// Set blob pointer before mapping
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="sourceDatabase"></param>
 /// <param name="destinationDatabase"></param>
 /// <param name="obj"></param>
 public override void BeforeMappingRecord(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
 {
     DatabaseConversion.CleanerTool.BOALedgerDataAccess.client_insurance_portfolio record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.client_insurance_portfolio;
     if (this._temporyFilePath.ContainsKey(record.cip_id))
     {
         record.cip_blob_pointer = this._temporyFilePath[record.cip_id];
     }
 }
 /// <summary>
 /// Manual mapping function for SteadfastReport table
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="sourceDatabase"></param>
 /// <param name="destinationDatabase"></param>
 public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
 {
     //
     // Create dump migration script if needed
     if (manager.IsGeneratedScript)
     {
         manager.WriteSQLScript("SteadfastReport", "", false);
     }
 }
        public void AddAndGet()
        {
            var mgr = new MappingManager();

            mgr.Add(typeof(Entity).GetProperty("Id"), "id");
            var fields = mgr.GetFields(typeof(Entity));

            Assert.AreEqual(1, fields.Count);
        }
        public void Inherited_gets_id_property_correctly()
        {
            var mgr = new MappingManager();

            mgr.Add(typeof(Entity).GetProperty("Id"), "id");

            Assert.IsTrue(mgr.GetFields(typeof(Entity)).ContainsKey("id"), "Entity contains id field");
            Assert.IsTrue(mgr.GetFields(typeof(InheritedEntity)).ContainsKey("id"), "InheritedEntity contains id field");
        }
Exemple #10
0
        public void ValidatingRuleSetReturnsValidationResults()
        {
            var mappingManager           = new MappingManager();
            var mappingValidationManager = new MappingValidator(mappingManager, new[] { new DummyValidationRuleError() });

            var validationResults = mappingValidationManager.EnumerateValidationResults(typeof(SchemaMappingTestDocument), new SolrSchema()).ToList();

            Assert.Single(validationResults);
        }
        public ActionResult List(PagerRequest request, BannerSearchOption search)
        {
            int totalCount;
            var linq = _bannerRepo.Get(e => (!search.PromotionId.HasValue || (e.SourceId == search.PromotionId.Value && e.SourceType == (int)SourceType.Promotion)) &&
                                       (!search.Status.HasValue || e.Status == (int)search.Status.Value) &&
                                       e.Status != (int)DataStatus.Deleted
                                       , out totalCount
                                       , request.PageIndex
                                       , request.PageSize
                                       , e =>
            {
                if (!search.OrderBy.HasValue)
                {
                    return(e.OrderByDescending(o => o.CreatedDate));
                }
                else
                {
                    switch (search.OrderBy.Value)
                    {
                    case GenericOrder.OrderByCreateUser:
                        return(e.OrderByDescending(o => o.CreatedUser));

                    case GenericOrder.OrderByCreateDate:
                    default:
                        return(e.OrderByDescending(o => o.CreatedDate));
                    }
                }
            });

            var linq_All = linq.Join(_proRepo.GetAll(),
                                     o => o.SourceId,
                                     i => i.Id,
                                     (o, i) => new { B = o, P = i })
                           .GroupJoin(_resourceRepo.Get(r => r.SourceType == (int)SourceType.BannerPromotion),
                                      o => o.B.Id,
                                      i => i.SourceId,
                                      (o, i) => new { B = o.B, P = o.P, R = i.FirstOrDefault() });
            var vo = from l in linq_All.ToList()
                     select new BannerViewModel()
            {
                Id         = l.B.Id,
                SourceId   = l.B.SourceId,
                SourceType = l.B.SourceType,
                Resource   = MappingManager.ResourceViewMapping(l.R),
                Promotion  = MappingManager.PromotionViewMapping(l.P),
                SortOrder  = l.B.SortOrder,
                Status     = l.B.Status
            };

            var v = new BannerCollectionViewModel(request, totalCount)
            {
                Banners = vo.ToList()
            };

            ViewBag.SearchOptions = search;
            return(View("List", v));
        }
Exemple #12
0
 static void Main(string[] args)
 {
     UserUI UIman = new UserUI() { userName = "******", userPass = "******" };
     MappingManager<UserUI, UserDB> mapper = new MappingManager<UserUI, UserDB>();
     UserDB DBman = mapper.mapObject(UIman);
     UIman.PrintValues();
     Console.WriteLine("\r\n");
     DBman.PrintValues();
     Console.ReadLine();
 }
        public void LoadFromAssembly_Should_Load_Mappings()
        {
            var assembly = typeof(PersonMap).Assembly;

            var manager = new MappingManager();
            manager.LoadFromAssembly(assembly);

            var map = manager.GetMapping(typeof(Person));
            Assert.IsNotNull(map);
        }
Exemple #14
0
        public static string GetTableName(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            var tableName = MappingManager.GetTableName(type);

            return(tableName == null ? null : tableName.Name);
        }
Exemple #15
0
        public void GetRegistered()
        {
            var mgr = new MappingManager();

            mgr.Add(typeof(Entity).GetProperty("Id"), "id");
            var types = mgr.GetRegisteredTypes();

            Assert.AreEqual(1, types.Count);
            Assert.Contains(types, typeof(Entity));
        }
        public void RemoveMappingEntry_ManagerHasOneEntry_ExistingEntryIsRemoved()
        {
            MappingManager mappingMgr   = Factory_MappingManager_Default();
            IMappingEntry  mappingEntry = Factory_IMappingEntry_Basic();

            mappingMgr.AddMappingEntry(mappingEntry);
            mappingMgr.RemoveMappingEntry(0);

            Assert.AreEqual(0, mappingMgr.GetNumEntries());
        }
Exemple #17
0
        public void ExchangeMappingInvalidContentTest(string mode, ContentParam contentParam, InvalidContent invalidContent, int expectedCode)
        {
            ExchangeMappingProperties requestBody = ExchangeMappingProperties.GetMappingContent(mode, mode == "import" ? CreatedImportMapping.Data : CreatedExportMapping.Data, Label, Name, Group, Resource, new List <string> {
                "Client.P_Id"
            }, Labels, GroupsDic, Items, AdditionConverters);
            var mappingHandler = new MappingManager();
            var response       = mappingHandler.ExchangeMapping <object>(InvalidContentMapper[contentParam](requestBody, invalidContent), System.Net.Http.HttpMethod.Put);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest).And.ErrorCode(100).Or.ErrorCode(116).Or.ErrorCode(103));
        }
        private void AddDrawableClass(MethodDef methodDef)
        {
            var drawableParam = methodDef.MethodSig.Params[0];

            Console.WriteLine("Drawable: " + methodDef.MethodSig.Params[0]);
            var drawableClass = MappingManager.GetClass("Drawable")
                                .OrElse(new ClassObj("Drawable", drawableParam.TypeName));

            MappingManager.AddClass(drawableClass);
        }
Exemple #19
0
        private void SendRequestAndVerify(string mode, Func <ExchangeMappingProperties, IEnumerable <KeyValuePair <string, object> > > getRequest, System.Net.HttpStatusCode statusCode, int expectedCode)
        {
            ExchangeMappingProperties requestBody = ExchangeMappingProperties.GetMappingContent(mode, mode == "import" ? CreatedImportMapping.Data : CreatedExportMapping.Data, Label, Name, Group, Resource, new List <string> {
                "Client.P_Id"
            }, Labels, GroupsDic, Items, AdditionConverters);
            var mappingHandler = new MappingManager();
            var response       = mappingHandler.ExchangeMapping <object>(getRequest(requestBody), System.Net.Http.HttpMethod.Put);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(statusCode).And.ErrorCode(expectedCode));
        }
Exemple #20
0
        /// <summary>
        /// Creates an object of the specified type associated with the attribute type
        /// </summary>
        /// <param name="ServiceType">Service type</param>
        /// <param name="AttributeType">Attribute type</param>
        /// <returns>An object of the specified type</returns>
        public object Get(Type ServiceType, Type AttributeType)
        {
            IMapping Mapping = MappingManager.GetMapping(ServiceType, AttributeType);

            if (Mapping.IsNull())
            {
                throw new ArgumentException("ServiceType not found in mappings");
            }
            return(Mapping.Implementation.Create());
        }
Exemple #21
0
        // GET: DIM/Mapping
        public ActionResult Index(long sourceId = 1, long targetId = 0, LinkElementType type = LinkElementType.System)
        {
            MappingManager mappingManager = new MappingManager();


            try
            {
                MappingMainModel model = new MappingMainModel();
                // load from mds example
                model.Source = MappingHelper.LoadFromMetadataStructure(sourceId, LinkElementPostion.Source, mappingManager);


                switch (type)
                {
                case LinkElementType.System:
                {
                    model.Target        = MappingHelper.LoadfromSystem(LinkElementPostion.Target, mappingManager);
                    model.SelectionList = MappingHelper.LoadSelectionList();
                    break;
                }

                case LinkElementType.MetadataStructure:
                {
                    model.Target        = MappingHelper.LoadFromMetadataStructure(targetId, LinkElementPostion.Target, mappingManager);
                    model.SelectionList = MappingHelper.LoadSelectionList();
                    break;
                }
                }

                if (model.Source != null && model.Target != null)
                {
                    //get linkelements
                    LinkElement source = mappingManager.GetLinkElement(sourceId, LinkElementType.MetadataStructure);
                    LinkElement target = mappingManager.GetLinkElement(targetId, type);

                    if (source != null && target != null)
                    {
                        //get root mapping
                        Mapping rootMapping = mappingManager.GetMapping(source, target);

                        if (rootMapping != null)
                        {
                            //get complex mappings
                            model.ParentMappings = MappingHelper.LoadMappings(rootMapping);
                        }
                    }
                }

                return(View(model));
            }
            finally
            {
                mappingManager.Dispose();
            }
        }
        /// <summary>
        /// Map a system key to xml node
        /// </summary>
        /// <param name="simpleNodeName"></param>
        /// <param name="simpleType"></param>
        /// <param name="complexNodeName"></param>
        /// <param name="complexType"></param>
        /// <param name="key"></param>
        /// <param name="root"></param>
        /// <param name="metadataRef"></param>
        /// <param name="mappingManager"></param>
        private void createFromKeyMapping(
            string simpleNodeName, LinkElementType simpleType,
            string complexNodeName, LinkElementType complexType,
            Key key,
            Mapping root,
            XDocument metadataRef,
            MappingManager mappingManager)
        {
            LinkElement le = createLinkELementIfNotExist(mappingManager, Convert.ToInt64(key),
                                                         key.ToString(), LinkElementType.Key, LinkElementComplexity.Simple);


            if (simpleNodeName.Equals(complexNodeName))
            {
                IEnumerable <XElement> elements = getXElements(simpleNodeName, metadataRef);

                foreach (XElement xElement in elements)
                {
                    string      sId  = xElement.Attribute("id").Value;
                    string      name = xElement.Attribute("name").Value;
                    LinkElement tmp  = createLinkELementIfNotExist(mappingManager, Convert.ToInt64(sId), name,
                                                                   simpleType, LinkElementComplexity.Simple);

                    Mapping tmpMapping = MappingHelper.CreateIfNotExistMapping(le, tmp, 1, null, root, mappingManager);
                    MappingHelper.CreateIfNotExistMapping(le, tmp, 2, null, tmpMapping, mappingManager);
                }
            }
            else
            {
                IEnumerable <XElement> complexElements = getXElements(complexNodeName, metadataRef);

                foreach (var complex in complexElements)
                {
                    string      sIdComplex        = complex.Attribute("id").Value;
                    string      nameComplex       = complex.Attribute("name").Value;
                    LinkElement tmpComplexElement = createLinkELementIfNotExist(mappingManager, Convert.ToInt64(sIdComplex), nameComplex,
                                                                                complexType, LinkElementComplexity.Complex);

                    Mapping complexMapping = MappingHelper.CreateIfNotExistMapping(le, tmpComplexElement, 1, null, root, mappingManager);


                    IEnumerable <XElement> simpleElements = XmlUtility.GetAllChildren(complex).Where(s => s.Name.LocalName.Equals(simpleNodeName));

                    foreach (XElement xElement in simpleElements)
                    {
                        string      sId  = xElement.Attribute("id").Value;
                        string      name = xElement.Attribute("name").Value;
                        LinkElement tmp  = createLinkELementIfNotExist(mappingManager, Convert.ToInt64(sId), name,
                                                                       simpleType, LinkElementComplexity.Simple);

                        MappingHelper.CreateIfNotExistMapping(le, tmp, 2, null, complexMapping, mappingManager);
                    }
                }
            }
        }
Exemple #23
0
 /// <summary>
 /// Captura a DAO relacionado com a Model do tipo submetido.
 /// </summary>
 /// <param name="typeModel">Tipo do model na qual a DAO est� relacionada.</param>
 /// <returns>DAO.</returns>
 /// <exception cref="GDAException"></exception>
 public static ISimpleBaseDAO GetDAO(Type typeModel)
 {
     if (MappingManager.MembersDAO.ContainsKey(typeModel))
     {
         return(MappingManager.MembersDAO[typeModel]);
     }
     else
     {
         PersistenceBaseDAOAttribute info = MappingManager.GetPersistenceBaseDAOAttribute(typeModel);
         if (info != null)
         {
             ISimpleBaseDAO dao;
             try
             {
                 if (info.BaseDAOType.IsGenericType)
                 {
                     Type t = info.BaseDAOType.MakeGenericType(info.BaseDAOGenericTypes);
                     dao = (ISimpleBaseDAO)Activator.CreateInstance(t);
                 }
                 else
                 {
                     dao = (ISimpleBaseDAO)Activator.CreateInstance(info.BaseDAOType);
                 }
             }
             catch (InvalidCastException)
             {
                 throw new GDAException(String.Format("Invalid cast, type {0} not inherit interface ISimpleBaseDAO.", info.BaseDAOType.FullName));
                 ;
             }
             catch (Exception ex)
             {
                 if (ex is TargetInvocationException)
                 {
                     throw new GDAException(ex.InnerException);
                 }
                 else
                 {
                     throw new GDAException(ex);
                 }
             }
             return(dao);
         }
         else
         {
             try
             {
                 return((ISimpleBaseDAO)Activator.CreateInstance(typeof(BaseDAO <object>).GetGenericTypeDefinition().MakeGenericType(typeModel)));
             }
             catch (Exception ex)
             {
                 throw new GDAException("Error to create instance BaseDAO<> for type " + typeModel.FullName + ".\r\n" + ex.Message, ex);
             }
         }
     }
 }
        public Dictionary <string, dynamic> GetConfigurationRoutes()
        {
            var mappingModel = new MappingManager(_settings);
            var hostUri      = _settings.HostUri;

            _queryEndpoints = new Dictionary <string, IEnumerable <string> >();

            // Generate the root endpoint
            var resources = mappingModel.Entities.Select(e => string.Format("{0}/{1}", hostUri, e.Name)).ToArray();

            Dictionary <string, dynamic> routes = new Dictionary <string, dynamic>();

            routes["/"] = new { resources };

            // Generate an endpoint for each entity
            foreach (var e in mappingModel.Entities)
            {
                if (!string.IsNullOrEmpty(e.Regex))
                {
                    var url = string.Format("/{0}", e.Name);
                    IDictionary <string, object> ret = new ExpandoObject();
                    var items = InMemoryRepository.Get(e.Name) as IEnumerable <dynamic>;
                    ret.Add(e.Name, items);

                    // Generate an endpoint for the entity collection
                    routes[url] = ret;

                    foreach (var item in items)
                    {
                        // Generate an endpoint for each entity within the collection
                        routes[item._route] = item;
                    }
                }
            }

            // Process the queries
            foreach (var q in mappingModel.Queries)
            {
                if (!string.IsNullOrEmpty(q.UriTemplate))
                {
                    // Generate the query endpoints (these reference mapped entities)

                    // extract the uri tokens from the query URI and translate them into entity names
                    var uriTokens   = Regex.Matches(q.UriTemplate, @"\{.*?\}");
                    var queryFields = new List <string>();
                    foreach (var s in uriTokens)
                    {
                        queryFields.Add(s.ToString().Replace("{", "").Replace("}", ""));
                    }
                    // cache the ordered entity names for the current query
                    _queryEndpoints.Add(q.UriTemplate, queryFields);
                }
            }
            return(routes);
        }
Exemple #25
0
        public void Creation()
        {
            var TestObject = new MappingManager(new IMapping[] {
                new BaseClass1Mapping(),
                new ConcreteClass1Mapping(),
                new ConcreteClass2Mapping(),
                new ConcreteClass3Mapping(),
                new IInterface1Mapping(),
                new IInterface2Mapping()
            },
                                                new IDatabase[] {
                new MockDatabaseMapping()
            },
                                                new QueryProviderManager(new[] { new SQLServerQueryProvider(Configuration, ObjectPool) }, Logger),
                                                Canister.Builder.Bootstrapper.Resolve <ILogger>(),
                                                ObjectPool)
                             .Sources
                             .First();

            Assert.Equal(5, TestObject.Mappings.Count);
            Assert.Contains(typeof(BaseClass1), TestObject.Mappings.Keys);
            Assert.Contains(typeof(ConcreteClass1), TestObject.Mappings.Keys);
            Assert.Contains(typeof(ConcreteClass2), TestObject.Mappings.Keys);
            Assert.Contains(typeof(ConcreteClass3), TestObject.Mappings.Keys);
            Assert.Contains(typeof(IInterface1), TestObject.Mappings.Keys);
            Assert.Equal(5, TestObject.TypeGraphs.Count);
            Assert.Equal(typeof(ConcreteClass1), TestObject.TypeGraphs[typeof(ConcreteClass1)].Root.Data);
            Assert.Equal(typeof(ConcreteClass2), TestObject.TypeGraphs[typeof(ConcreteClass2)].Root.Data);
            Assert.Equal(typeof(ConcreteClass3), TestObject.TypeGraphs[typeof(ConcreteClass3)].Root.Data);

            Assert.Single(TestObject.TypeGraphs[typeof(ConcreteClass1)].Root.Nodes);
            Assert.Equal(typeof(BaseClass1), TestObject.TypeGraphs[typeof(ConcreteClass1)].Root.Nodes[0].Data);
            Assert.Single(TestObject.TypeGraphs[typeof(ConcreteClass1)].Root.Nodes[0].Nodes);
            Assert.Equal(typeof(IInterface1), TestObject.TypeGraphs[typeof(ConcreteClass1)].Root.Nodes[0].Nodes[0].Data);

            Assert.Single(TestObject.TypeGraphs[typeof(ConcreteClass2)].Root.Nodes);
            Assert.Equal(typeof(BaseClass1), TestObject.TypeGraphs[typeof(ConcreteClass2)].Root.Nodes[0].Data);
            Assert.Single(TestObject.TypeGraphs[typeof(ConcreteClass2)].Root.Nodes[0].Nodes);
            Assert.Equal(typeof(IInterface1), TestObject.TypeGraphs[typeof(ConcreteClass2)].Root.Nodes[0].Nodes[0].Data);

            Assert.Single(TestObject.TypeGraphs[typeof(ConcreteClass3)].Root.Nodes);
            Assert.Equal(typeof(IInterface1), TestObject.TypeGraphs[typeof(ConcreteClass3)].Root.Nodes[0].Data);

            Assert.Equal(6, TestObject.ChildTypes.Count);
            Assert.Equal(2, TestObject.ChildTypes[typeof(BaseClass1)].Count());
            Assert.Single(TestObject.ChildTypes[typeof(ConcreteClass1)]);
            Assert.Single(TestObject.ChildTypes[typeof(ConcreteClass2)]);
            Assert.Single(TestObject.ChildTypes[typeof(ConcreteClass3)]);
            Assert.Equal(3, TestObject.ChildTypes[typeof(IInterface1)].Count());
            Assert.Single(TestObject.ChildTypes[typeof(IInterface2)]);
            Assert.Equal(3, TestObject.ParentTypes.Count);
            Assert.Equal(3, TestObject.ParentTypes[typeof(ConcreteClass1)].Count());
            Assert.Equal(3, TestObject.ParentTypes[typeof(ConcreteClass2)].Count());
            Assert.Equal(2, TestObject.ParentTypes[typeof(ConcreteClass3)].Count());
        }
Exemple #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryTranslator{TObject}"/> class.
 /// </summary>
 /// <param name="mappingManager">The mapping manager.</param>
 /// <param name="queryProviderManager">The query provider manager.</param>
 /// <exception cref="ArgumentNullException">mappingManager or queryProviderManager</exception>
 public QueryTranslator(MappingManager mappingManager,
                        QueryProviderManager queryProviderManager)
 {
     MappingManager       = mappingManager ?? throw new ArgumentNullException(nameof(mappingManager));
     QueryProviderManager = queryProviderManager ?? throw new ArgumentNullException(nameof(queryProviderManager));
     Builders             = new Dictionary <IMappingSource, QueryData <TObject> >();
     foreach (var Source in MappingManager.ReadSources.Where(x => x.GetChildMappings(typeof(TObject)).Any()))
     {
         Builders.Add(Source, new QueryData <TObject>(Source));
     }
 }
Exemple #27
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Manager()
 {
     if (ProviderManager == null)
     {
         ProviderManager = new ProviderManager();
     }
     if (MappingManager == null)
     {
         MappingManager = new MappingManager(ProviderManager);
     }
 }
Exemple #28
0
        /// <summary>
        /// Constrói o resultado com as informações que serão processadas.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public override QueryReturnInfo BuildResultInfo <T>(GDA.Interfaces.IProviderConfiguration configuration)
        {
            if (string.IsNullOrEmpty(_commandText))
            {
                throw new QueryException("Command text not informed.");
            }
            var query = _commandText;

            if (!string.IsNullOrEmpty(Order))
            {
                var orderByIndex = query.LastIndexOf("ORDER BY");
                if (orderByIndex >= 0)
                {
                    query = query.Substring(0, orderByIndex);
                }
                query += " ORDER BY " + Order;
            }
            var mapping     = MappingManager.GetMappers <T>(null, null);
            var selectProps = new List <Mapper>(mapping);

            if (!string.IsNullOrEmpty(_selectProperties) && _selectProperties != "*")
            {
                List <string> functions = new List <string>();
                Parser        p         = new Parser(new Lexer(_selectProperties));
                SelectPart    sp        = p.ExecuteSelectPart();
                selectProps = new List <Mapper>(sp.SelectionExpressions.Count);
                foreach (SelectExpression se in sp.SelectionExpressions)
                {
                    if (se.ColumnName.Type == GDA.Sql.InterpreterExpression.Enums.SqlExpressionType.Column)
                    {
                        Column col = se.Column;
                        foreach (Mapper mp in mapping)
                        {
                            if (string.Compare(se.ColumnName.Value.Text, mp.PropertyMapperName, true) == 0 && (mp.Direction == DirectionParameter.Input || mp.Direction == DirectionParameter.InputOutput || mp.Direction == DirectionParameter.OutputOnlyInsert))
                            {
                                if (!selectProps.Exists(f => f.PropertyMapperName == mp.PropertyMapperName))
                                {
                                    selectProps.Add(mp);
                                }
                            }
                        }
                        if (col.Name == "*")
                        {
                            throw new GDAException("Invalid expression {0}", se.ColumnName.Value.Text);
                        }
                    }
                    else if (se.ColumnName.Type == GDA.Sql.InterpreterExpression.Enums.SqlExpressionType.Function)
                    {
                        throw new QueryException("NativeQuery not support function in select part");
                    }
                }
            }
            return(new QueryReturnInfo(query, this.Parameters, selectProps));
        }
        public ExecuteResult <List <BrandInfoResponse> > GetRefresh(BrandRefreshRequest request)
        {
            var entities = this._brandRepository.GetListForRefresh(request.Timestamp);

            if (entities == null || entities.Count == 0)
            {
                return(new ExecuteResult <List <BrandInfoResponse> >(new List <BrandInfoResponse>(0)));
            }

            return(new ExecuteResult <List <BrandInfoResponse> >(MappingManager.BrandInfoResponseMapping(entities).ToList()));
        }
Exemple #30
0
        public void Add_duplicate_property_overwrites()
        {
            var mgr = new MappingManager();

            mgr.Add(typeof(Entity).GetProperty("Id"), "id");
            mgr.Add(typeof(Entity).GetProperty("Id"), "id2");
            var fields = mgr.GetFields(typeof(Entity));

            Assert.AreEqual(1, fields.Count);
            Assert.AreEqual("id2", fields.First().Value.FieldName);
        }
        public ExecuteResult <SpecialTopicInfoResponse> GetInfo(GetSpecialTopicInfoRequest request)
        {
            var data     = _specialTopicRepository.GetItem(request.TopicId);
            var response = MappingManager.SpecialTopicInfoResponseMapping(data);



            var result = new ExecuteResult <SpecialTopicInfoResponse>(response);

            return(result);
        }
        public ExecuteResult <GroupStructInfoResponse <BrandInfoResponse> > GetRefresh4Group(BrandRefreshRequest request)
        {
            var entities = this._brandRepository.GetListForRefresh(request.Timestamp);

            if (entities == null || entities.Count == 0)
            {
                return(new ExecuteResult <GroupStructInfoResponse <BrandInfoResponse> >(null));
            }

            return(new ExecuteResult <GroupStructInfoResponse <BrandInfoResponse> >(MappingManager.BrandInfoResponse4GroupMapping(entities)));
        }
Exemple #33
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Manager()
 {
     if (ProviderManager.IsNull())
     {
         ProviderManager = new ProviderManager();
     }
     if (MappingManager.IsNull())
     {
         MappingManager = new MappingManager(ProviderManager);
     }
 }
Exemple #34
0
        public ExecuteResult <CommentInfoResponse> Create(CommentCreateRequest request)
        {
            CommentEntity entity;

            if ((request.Files == null || request.Files.Count == 0) &&
                string.IsNullOrEmpty(request.Content))
            {
                return(new ExecuteResult <CommentInfoResponse>(null)
                {
                    StatusCode = StatusCode.ClientError, Message = "没有评论内容!"
                });
            }
            using (var ts = new TransactionScope())
            {
                entity = _commentRepository.Insert(new CommentEntity
                {
                    Content     = request.Content,
                    CreatedDate = DateTime.Now,
                    CreatedUser = request.AuthUid,
                    ReplyUser   = request.ReplyUser,
                    SourceId    = request.SourceId,
                    SourceType  = (int)request.SType,
                    Status      = 1,
                    UpdatedDate = DateTime.Now,
                    UpdatedUser = request.AuthUid,
                    User_Id     = request.AuthUid
                });

                //插入一个提醒
                _remindService.Insert(new RemindEntity
                {
                    CreatedDate = DateTime.Now,
                    CreatedUser = request.AuthUid,
                    IsRemind    = false,
                    RemindUser  = request.AuthUid,
                    SourceId    = entity.Id,
                    Stauts      = (int)DataStatus.Default,
                    Type        = (int)SourceType.Comment,
                    UpdatedDate = DateTime.Now,
                    UpdatedUser = request.AuthUid,
                    User_Id     = entity.ReplyUser
                });

                //处理文件上传
                if (request.Files != null && request.Files.Count > 0)
                {
                    ServiceLocator.Current.Resolve <IResourceService>().Save(request.Files, request.AuthUid, 0, entity.Id, SourceType.CommentAudio);
                }

                ts.Complete();
            }

            return(new ExecuteResult <CommentInfoResponse>(MappingManager.CommentInfoResponseMapping(entity, request.Version)));
        }
        public ExecuteResult <BrandInfoResponse> GetBrand(BrandDetailRequest request)
        {
            var entity = this._brandRepository.GetItem(request.BrandId);

            if (entity == null)
            {
                return(new ExecuteResult <BrandInfoResponse>(null));
            }

            return(new ExecuteResult <BrandInfoResponse>(MappingManager.BrandInfoResponseMapping(entity)));
        }
Exemple #36
0
        public ParameterTypeFacadeTests()
        {
            MappingManager.Initialize();

            var builder = BuildODataModel();

            _mockDtoOptions = new Mock <ODataQueryOptions <ParameterTypeQueryDto> >(
                new ODataQueryContext(builder.GetEdmModel(), typeof(ParameterTypeQueryDto), new ODataPath()), new HttpRequestMessage());

            _mockDtoOptions.Setup(x => x.Validate(It.IsAny <ODataValidationSettings>())).Callback(() => { });
        }
Exemple #37
0
        public void Add_property_only()
        {
            var mgr      = new MappingManager();
            var property = typeof(Entity).GetProperty("Id");

            mgr.Add(property);
            var fields = mgr.GetFields(typeof(Entity));

            Assert.AreEqual(1, fields.Count);
            Assert.AreEqual("Id", fields.First().Value.FieldName);
        }
        public void MappedPropertiesIsInSolrSchemaRule_ignores_score()
        {
            var rule   = new MappedPropertiesIsInSolrSchemaRule();
            var mapper = new MappingManager();

            mapper.Add(typeof(SchemaMappingTestDocument).GetProperty("Score"), "score");
            var results = rule.Validate(typeof(SchemaMappingTestDocument), new SolrSchema(), mapper).ToList();

            Assert.NotNull(results);
            Assert.Empty(results);
        }
Exemple #39
0
        private object CreateInstance(ConstructorInfo Constructor)
        {
            if (Constructor.IsNull() || MappingManager.IsNull())
            {
                return(null);
            }
            List <object> ParameterValues = new List <object>();

            Constructor.GetParameters().ForEach <ParameterInfo>(x => ParameterValues.Add(CreateInstance(x)));
            return(Constructor.Invoke(ParameterValues.ToArray()));
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.EmailTemplates record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.EmailTemplates;

            //
            // Run blob pointer converter if needed
            if (record.et_template != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.EMAIL_TEMPLATE, BlobStoreCategories.EMAIL_TEMPLATE, record.et_template);
                this._temporyFilePath.Add(record.et_id, fullPath);
            }
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.confirmation_of_cover record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.confirmation_of_cover;

            //
            // Run blob pointer converter if needed
            if (record.coc_document_object_eclipse != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.CONFIRMATION_OF_COVER, BlobStoreCategories.CONFIRMATION_OF_COVER, record.coc_document_object_eclipse);
                this._temporyFilePath.Add(record.coc_id, fullPath);
            }
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.claim_sub_tasks record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.claim_sub_tasks;

            //
            // Run blob pointer converter if needed
            if (record.clasubta_image != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.CLAIM_TASK_DOCUMENT, BlobStoreCategories.CLAIM_TASK_DOCUMENT, record.clasubta_image);
                this._temporyFilePath.Add(record.clasubta_id, fullPath);
            }
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.policy_transaction_documents record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.policy_transaction_documents;

            //
            // Run blob pointer converter if needed
            if (record.poltrado_object_eclipse != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.POLICY_TRANSACTION_DOCUMENTS, BlobStoreCategories.POLICY_TRANSACTION_DOCUMENTS, record.poltrado_object_eclipse);
                this._temporyFilePath.Add(record.poltrado_id, fullPath);
            }
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.client_insurance_portfolio record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.client_insurance_portfolio;

            //
            // Run blob pointer converter if needed
            if (record.cip_document_object_eclipse != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.CLIENT_INSURANCE_PORTFOLIO, BlobStoreCategories.CLIENT_INSURANCE_PORTFOLIO, record.cip_document_object_eclipse);
                this._temporyFilePath.Add(record.cip_id, fullPath);
            }
        }
        /// <summary>
        /// Run BLOBPointer converter before mapping
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.EclipseDataAccess.DocumentRepository record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.DocumentRepository;

            //
            // Run blob pointer converter if needed
            if (record.dr_document != null && !IgnoreBlobs)
            {
                string fullPath = BlobConverter.ConvertToFile(BlobStoreCategories.DOCUMENT_REPOSITORY, BlobStoreCategories.DOCUMENT_REPOSITORY, record.dr_document);
                this._temporyFilePath.Add(record.dr_id, fullPath);
            }
        }
        /// <summary>
        /// Before add policies record into BOALedger database, we will try to update value from Workbook_SOA Table
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="record"></param>
        public override void BeforeMappingRecord(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Cast type
            DatabaseConversion.CleanerTool.BOALedgerDataAccess.policies record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.policies;

            //
            // Check does this record reference to workbooks table or not ?
            // If it does, we need to check the value of
            if (record.pol_wor_id.HasValue)
            {
                DatabaseConversion.CleanerTool.EclipseDataAccess.EclipseDatabaseEntities sourceDbContext = sourceDatabase.GetNewDbContext() as DatabaseConversion.CleanerTool.EclipseDataAccess.EclipseDatabaseEntities;

                //
                // Get related workbook_SOA record
                DatabaseConversion.CleanerTool.EclipseDataAccess.Workbook_SOA workbook_SOARecord =
                    (from workbook_SOATable in sourceDbContext.Workbook_SOA
                    join workbooksTable in sourceDbContext.workbooks on workbook_SOATable.ws_parent_id equals workbooksTable.wor_id
                    where workbooksTable.wor_id == record.pol_wor_id.Value
                    select workbook_SOATable).FirstOrDefault();

                //
                // If not null, try to convert and assign new value to record
                if (workbook_SOARecord != null)
                {
                    if (workbook_SOARecord.ws_scopeofadvice != null)
                    {
                        record.pol_scope_of_advice = WordGenerator.ConvertRtfToHtml(WordGenerator.ConvertDocxToRTF(workbook_SOARecord.ws_scopeofadvice));
                    }
                    if (workbook_SOARecord.ws_recommendations != null)
                    {
                        record.pol_recommendations = WordGenerator.ConvertRtfToHtml(WordGenerator.ConvertDocxToRTF(workbook_SOARecord.ws_recommendations));
                    }
                    if (workbook_SOARecord.ws_notice1 != null)
                    {
                        record.pol_notice1 = WordGenerator.ConvertRtfToHtml(WordGenerator.ConvertDocxToRTF(workbook_SOARecord.ws_notice1));
                    }
                    if (workbook_SOARecord.ws_notice2 != null)
                    {
                        record.pol_notice2 = WordGenerator.ConvertRtfToHtml(WordGenerator.ConvertDocxToRTF(workbook_SOARecord.ws_notice2));
                    }
                    if (workbook_SOARecord.ws_notice3 != null)
                    {
                        record.pol_notice3 = WordGenerator.ConvertRtfToHtml(WordGenerator.ConvertDocxToRTF(workbook_SOARecord.ws_notice3));
                    }
                }
            }
        }
        /// <summary>
        /// Migration reference from destination to source
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        private void MigrationReference(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            List<string> listSourceTableName = sourceDatabase.GetListTable();
            List<string> listDestTableName = destinationDatabase.GetListTable();
            foreach (string sourceTableName in listSourceTableName)
            {
                //
                // Check does it rename or not ?
                string destTableName = manager.GetTableNewName(sourceTableName);
                LogService.Log.Info("Migrate from " + destTableName + " to " + sourceTableName);

                //
                // Then check, it's still exist in destination database or not
                if (listDestTableName.Contains(destTableName) == false)
                {
                    LogService.Log.Info("Table " + sourceTableName + " has been dropped in destination database.");
                    continue;
                }

                //
                // Get MapTable (class contains information about table, includes references)
                MapTable sourceMapTable = sourceDatabase.GetMapTable(sourceTableName);
                MapTable destMapTable = destinationDatabase.GetMapTable(destTableName);

                //
                // Add references
                List<ReferenceInformation> listDestReference = destMapTable.GetReference();
                foreach (ReferenceInformation reference in listDestReference)
                {
                    //
                    // Try to revert from new name of table to old name of table
                    string PKTableOldName = manager.GetTableOldName(reference.PKTableName);
                    string FKTableOldName = manager.GetTableOldName(reference.FKTableName);
                    reference.PKTableName = PKTableOldName;
                    reference.FKTableName = FKTableOldName;

                    //
                    // Add new reference information to sourceMapTable
                    if (sourceMapTable.HasReference(reference) == false)
                    {
                        LogService.Log.Info("Add new reference from " + reference.FKTableName + "(" + reference.FKColumnName + ")" +
                                            "to " + reference.FKTableName + "(" + reference.FKColumnName + ")");
                        sourceMapTable.AddReference(reference);
                    }
                }
            }
        }
        /// <summary>
        /// Manual function, after mapping completed, we will re-update reference value
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void AfterMapping(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // First, try to load new record in destination database
            string destinationDatabaseName = destinationDatabase.GetDatabaseName();

            //
            // Try to update
            if (manager.IsGeneratedScript)
            {
                //
                // First generate update script
                string sqlScript = "USE [" + destinationDatabaseName + "]" + Environment.NewLine +
                                   "GO" + Environment.NewLine;
                string updateTemplate = "UPDATE {DESTINATION_DATABASE_NAME}.dbo.branches" + Environment.NewLine +
                                        "SET bra_parent_branch = {REFERENCE_VALUE}" + Environment.NewLine +
                                        "WHERE bra_id = {PRIMARY_KEY_VALUE}" + Environment.NewLine;
                updateTemplate = updateTemplate.Replace("{DESTINATION_DATABASE_NAME}", destinationDatabase.GetDatabaseName());
                foreach (int primaryKeyValue in this._listReferenceValue.Keys)
                {
                    int? referenceValue = this._listReferenceValue[primaryKeyValue];
                    sqlScript = sqlScript + updateTemplate.Replace("{REFERENCE_VALUE}", referenceValue.Value.ToString())
                                                          .Replace("{PRIMARY_KEY_VALUE}", primaryKeyValue.ToString());
                }

                //
                // Then append to file (existed file)
                manager.WriteSQLScript("branches", sqlScript, true);
            }
            else
            {
                //
                // If we do not generate sql script
                // we need to update directly in destination table
                BOALedgerDataAccess.BOALedgerEntities dbContext = destinationDatabase.GetDbContext() as BOALedgerDataAccess.BOALedgerEntities;
                List<BOALedgerDataAccess.branches> listRecords = dbContext.branches.ToList();
                foreach (BOALedgerDataAccess.branches record in listRecords)
                {
                    if (this._listReferenceValue.ContainsKey(record.bra_id))
                    {
                        record.bra_parent_branch = this._listReferenceValue[record.bra_id];
                    }
                }
                dbContext.SaveChanges();
            }
        }
 /// <summary>
 /// Set blob pointer before mapping
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="sourceDatabase"></param>
 /// <param name="destinationDatabase"></param>
 /// <param name="obj"></param>
 public override void BeforeMappingRecord(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
 {
     DatabaseConversion.CleanerTool.BOALedgerDataAccess.general_insurance_workbooks record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.general_insurance_workbooks;
     if (this._documentFilePath.ContainsKey(record.geninswb_id))
     {
         record.geninswb_blob_pointer_document = this._documentFilePath[record.geninswb_id];
     }
     if (this._portfolioFilePath.ContainsKey(record.geninswb_id))
     {
         record.geninswb_blob_pointer_portfolio = this._portfolioFilePath[record.geninswb_id];
     }
     if (this._cocFilePath.ContainsKey(record.geninswb_id))
     {
         record.geninswb_blob_pointer_coc = this._cocFilePath[record.geninswb_id];
     }
     if (this._objectFilePath.ContainsKey(record.geninswb_id))
     {
         record.geninswb_blob_pointer_object = this._objectFilePath[record.geninswb_id];
     }
 }
        /// <summary>
        /// Validate database
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Validate(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Initialize
            this.MigrationReference(manager, sourceDatabase, destinationDatabase);
            this._threadManager = new OrphanRecordValidationThreadManager(sourceDatabase, destinationDatabase);
            List<string> listTable = sourceDatabase.GetListTable();

            //
            // Start validate
            LogService.Log.Info("Start validate orphan record from database.");
            foreach (string table in listTable)
            {
                LogService.Log.Info("Validate table : " + table);
                this._threadManager.Validate(table);
            }

            //
            // Write SQLScript to Orphans.sql
            LogService.Log.Info("Create Orphans.sql to delete orphan record.");
            ErrorHandlerManager.ExportScriptToDeleteOrphan(sourceDatabase, @"Orphans.sql");
        }
        /// <summary>
        /// Do some stuffs before commit new value to destination database
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="listNewRecord"></param>
        public override void BeforeCommitChanges(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, List<object> listNewRecord)
        {
            //
            // Initialize for sharing data
            Dictionary<int, int?> shareData = new Dictionary<int, int?>();

            //
            // Loop and set null
            foreach (object obj in listNewRecord)
            {
                DatabaseConversion.CleanerTool.BOALedgerDataAccess.general_insurance record = obj as DatabaseConversion.CleanerTool.BOALedgerDataAccess.general_insurance;
                if (record.genins_current_workbook != null)
                {
                    shareData.Add(record.genins_id, record.genins_current_workbook);
                    record.genins_current_workbook = null;
                }
            }

            //
            // Share data for ManualMapping_workbooks
            ManualMappingDropBox.ShareData("general_insurance", shareData);
        }
        /// <summary>
        /// Manual mapping function for glsl_Transactions
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "glsl_Transactions";

            //
            // Exec sql script to insert data
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.glsl_Transactions(Glsl_id, Glac_Balance, TranDate, TranNumber, TranType, InvNumber, Particulars, TranAmount, Spid, Glsl_balance)" + Environment.NewLine +
                               "SELECT Glsl_id, Glac_Balance, TranDate, TranNumber, TranType, InvNumber, Particulars, TranAmount, Spid, Glsl_balance FROM {SOURCE_DATABASE_NAME}.dbo.glsl_Transactions" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Manual mapping function for view_DofiReport_Table1
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "view_DofiReport_Table1";

            //
            // Generate SQL script
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.view_DofiReport_Table1(spid, apra_authorised_during_reporting_period, apra_authorised_after_reporting_period, apra_authorised_before_reporting_period, lloyd_during_reporting_period, lloyd_after_reporting_period, lloyd_before_reporting_period, ufi_during_reporting_period, ufi_after_reporting_period, ufi_before_reporting_period, broker_during_reporting_period, broker_after_reporting_period, broker_before_reporting_period)" + Environment.NewLine +
                               "SELECT spid, apra_authorised_during_reporting_period, apra_authorised_after_reporting_period, apra_authorised_before_reporting_period, lloyd_during_reporting_period, lloyd_after_reporting_period, lloyd_before_reporting_period, ufi_during_reporting_period, ufi_after_reporting_period, ufi_before_reporting_period, broker_during_reporting_period, broker_after_reporting_period, broker_before_reporting_period FROM {SOURCE_DATABASE_NAME}.dbo.view_DofiReport_Table1" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Main mapping function
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "statements";

            //
            // Generate SQL script
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.statements(gltr_glsl_id, glsl_entity_id, glsl_name, gltr_id, gltr_date, glmv_date, glmv_id, glmv_glrs_set, glmv_record_ref_id, origamount, gltr_amount, debit, credit, balance, unalloccash, netbalance, pol_id, pol_id1, pol_tran_id, pol_tran_id1, tran_id, Pol_policy_number, genins_name, genins_class_of_business, gencob_name, paymethod, client, sortid, spid, salesteam, BRComm, NetDue, BRClient, StatementInsurer, PaymentType, InvoiceComments)" + Environment.NewLine +
                               "SELECT gltr_glsl_id, glsl_entity_id, glsl_name, gltr_id, gltr_date, glmv_date, glmv_id, glmv_glrs_set, glmv_record_ref_id, origamount, gltr_amount, debit, credit, balance, unalloccash, netbalance, pol_id, pol_id1, pol_tran_id, pol_tran_id1, tran_id, Pol_policy_number, genins_name, genins_class_of_business, gencob_name, paymethod, client, sortid, spid, salesteam, BRComm, NetDue, BRClient, StatementInsurer, PaymentType, InvoiceComments FROM {SOURCE_DATABASE_NAME}.dbo.statements" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Manual mapping function for view_earnings2
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "view_earnings2";

            //
            // Generate SQL script
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.view_earnings2(ent_id, ent_name, genins_name, pol_parent_id, pol_id, pol_tran_id, pol_total_gross_premium, pol_total_net_premium, adj, acr, debtor_bal, earn_broker_comm, earn_sa_comm, earn_broker_fee, earn_sa_fee, earn_total, spid, earn_gst, broker_comm, broker_fee, total_earn, comm_earned, fees_earned, fees_gst, comm_gst, total_earn_gst, total_earn_net_gst, gst_rate, bal, bal2, sa_payable, pol_amount_remitted_sub, sa_gst, pol_fee_gst, pol_comm_gst, debtor_paid, paid_date, br_comm_adjustment, sa_fee_net, sa_comm_net, broker_rep, cob_name, sales_team, service_team, branch, insurer, tran_time)" + Environment.NewLine +
                               "SELECT ent_id, ent_name, genins_name, pol_parent_id, pol_id, pol_tran_id, pol_total_gross_premium, pol_total_net_premium, adj, acr, debtor_bal, earn_broker_comm, earn_sa_comm, earn_broker_fee, earn_sa_fee, earn_total, spid, earn_gst, broker_comm, broker_fee, total_earn, comm_earned, fees_earned, fees_gst, comm_gst, total_earn_gst, total_earn_net_gst, gst_rate, bal, bal2, sa_payable, pol_amount_remitted_sub, sa_gst, pol_fee_gst, pol_comm_gst, debtor_paid, paid_date, br_comm_adjustment, sa_fee_net, sa_comm_net, broker_rep, cob_name, sales_team, service_team, branch, insurer, tran_time FROM {SOURCE_DATABASE_NAME}.dbo.view_earnings2" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Change format before running automapper
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        /// <param name="obj"></param>
        public override void BeforeRunningAutoMapper(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase, object obj)
        {
            //
            // Try to cast type first
            DatabaseConversion.CleanerTool.EclipseDataAccess.soa_clauses record = null;
            try
            {
                record = obj as DatabaseConversion.CleanerTool.EclipseDataAccess.soa_clauses;
            }
            catch (Exception excCastType)
            {
                LogService.Log.Error("Can not cast type as soa_clauses.", excCastType);
                return;
            }

            //
            // Change from rtf format to html format
            if (record.nature_of_advice != null)
            {
                record.nature_of_advice = WordGenerator.ConvertRtfToHtml(record.nature_of_advice);
            }
            if (record.recommendations != null)
            {
                record.recommendations = WordGenerator.ConvertRtfToHtml(record.recommendations);
            }
            if (record.optional_notice1 != null)
            {
                record.optional_notice1 = WordGenerator.ConvertRtfToHtml(record.optional_notice1);
            }
            if (record.optional_notice2 != null)
            {
                record.optional_notice2 = WordGenerator.ConvertRtfToHtml(record.optional_notice2);
            }
            if (record.optional_notice3 != null)
            {
                record.optional_notice3 = WordGenerator.ConvertRtfToHtml(record.optional_notice3);
            }
        }
        /// <summary>
        /// Main mapping function
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "PaidInvoices";

            //
            // Exec sql script to insert data
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.PaidInvoices(tritm_tran_id, tritm_amount, Paid, Remaining, tritm_inc_id, DatePaid, spid)" + Environment.NewLine +
                               "SELECT tritm_tran_id, tritm_amount, Paid, Remaining, tritm_inc_id, DatePaid, spid FROM {SOURCE_DATABASE_NAME}.dbo.PaidInvoices" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Main mapping function
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "renewal_retention_report";

            //
            // Generate SQL script
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.renewal_retention_report(PolID, TranID, Client, SalesTeam, ServiceTeam, Branch, COB, InsurerName, BrokerName, TransactionType, Paid, PartPaid, UnPaid, Lapsed, UnInvited, saltea_id, sertea_id, gencob_id, ent_id, pol_insurer, br_id, tratyp_id, bra_name, genins_id, genins_name, Rentention, Spid, Premium, Earnings, DueDate)" + Environment.NewLine +
                               "SELECT PolID, TranID, Client, SalesTeam, ServiceTeam, Branch, COB, InsurerName, BrokerName, TransactionType, Paid, PartPaid, UnPaid, Lapsed, UnInvited, saltea_id, sertea_id, gencob_id, ent_id, pol_insurer, br_id, tratyp_id, bra_name, genins_id, genins_name, Rentention, Spid, Premium, Earnings, DueDate FROM {SOURCE_DATABASE_NAME}.dbo.renewal_retention_report" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Manual mapping function for period_renewals_particulars_t
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "period_renewals_particulars_t";

            //
            // Generate SQL script
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.period_renewals_particulars_t(prp_pol_parent_id, prp_pol_particulars, prp_pol_id, prp_pol_sum_insured, prp_spid)" + Environment.NewLine +
                               "SELECT prp_pol_parent_id, prp_pol_particulars, prp_pol_id, prp_pol_sum_insured, prp_spid FROM {SOURCE_DATABASE_NAME}.dbo.period_renewals_particulars_t" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }
        /// <summary>
        /// Main mapping function
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="sourceDatabase"></param>
        /// <param name="destinationDatabase"></param>
        public override void Map(MappingManager manager, SourceDatabase sourceDatabase, DestinationDatabase destinationDatabase)
        {
            //
            // Try to get source database name and destination database name
            DbContext sourceDbContext = sourceDatabase.GetDbContext();
            DbContext destDbContext = destinationDatabase.GetDbContext();
            string sourceDatabaseName = sourceDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string destDatabaseName = destDbContext.Database.SqlQuery<string>(@"SELECT DB_NAME() AS [Current Database]").FirstOrDefault();
            string tableName = "IBA";

            //
            // Exec sql script to insert data
            string sqlQuery = @"INSERT INTO {DESTINATION_DATABASE_NAME}.dbo.IBA(Fromdate, Todate, adp77, adp78, adp79, adp80, adp81, adp82, adp83, adp84, adp85, adp86, adp87A, adp87B, adp87C, adp87, adp88, adp89, adp90, adp91, adp92, adp93, adp94, adp95, adp100, adp101, adp102, adp103, adp104, adp105, TotalSelfDrawings, TotalGSTDrawings, TotalBrokerRepEarnings, Earnings, GSTonEarnings, DrawnToBrokerRep, DrawnToGST, DrawnToSelf, Adjustments, adp106A, adp106b, adp106c, adp106, adp107, adp108, CashClosingBalance, Asic26DiffAmount, Asic27DiffAmount, spid)" + Environment.NewLine +
                               "SELECT Fromdate, Todate, adp77, adp78, adp79, adp80, adp81, adp82, adp83, adp84, adp85, adp86, adp87A, adp87B, adp87C, adp87, adp88, adp89, adp90, adp91, adp92, adp93, adp94, adp95, adp100, adp101, adp102, adp103, adp104, adp105, TotalSelfDrawings, TotalGSTDrawings, TotalBrokerRepEarnings, Earnings, GSTonEarnings, DrawnToBrokerRep, DrawnToGST, DrawnToSelf, Adjustments, adp106A, adp106b, adp106c, adp106, adp107, adp108, CashClosingBalance, Asic26DiffAmount, Asic27DiffAmount, spid FROM {SOURCE_DATABASE_NAME}.dbo.IBA" + Environment.NewLine;
            sqlQuery = sqlQuery.Replace("{SOURCE_DATABASE_NAME}", sourceDatabaseName)
                               .Replace("{DESTINATION_DATABASE_NAME}", destDatabaseName);

            //
            // Exec SQL script or write to file
            if (manager.IsGeneratedScript)
            {
                sqlQuery = "USE [" + destDatabaseName + "]" + Environment.NewLine +
                           "GO" + Environment.NewLine +
                           sqlQuery;
                manager.WriteSQLScript(tableName, sqlQuery, false);
            }
            else
            {
                try
                {
                    destDbContext.Database.ExecuteSqlCommand(sqlQuery);
                }
                catch (Exception excExecScript)
                {
                    LogService.Log.Error("Can not run migration script for " + tableName, excExecScript);
                }
            }
        }