Ejemplo n.º 1
0
        private static void FillIoCContainer(ClassFactory classFactory)
        {
            classFactory.RegisterType<IPathValidation, PathValidation>().AsSingleton();
            classFactory.RegisterType<IOperationValidation, OperationValidation>().AsSingleton();
            classFactory.RegisterType<IMainController, MainController>().AsSingleton();
            classFactory.RegisterType<ILinkerService, LinkerService>().AsSingleton();
            classFactory.RegisterType<ICommandDiscovery, CommandDiscovery>().AsSingleton();
            classFactory.RegisterType<ICommandFactory, CommandFactory>().AsSingleton();
            classFactory.RegisterType<IOperatingSystemVersion, OperatingSystemVersion>().AsSingleton();
            classFactory.RegisterType<IJunctionPointXp, JunctionPointXp>().AsSingleton();

            classFactory.RegisterType<ITransactionalCommandRunner, TransactionalCommandRunner>();
            classFactory.RegisterType<IWorkingView, ProgressView>();
            classFactory.RegisterType<ILocker, Locker>();
            classFactory.RegisterType<ILinkerView, DirLinkerView>();
            classFactory.RegisterType<IBackgroundWorker, BackgroundWorkerImp>();
            classFactory.RegisterType<ThreadSafeQueue<ICommand>>();

            classFactory.RegisterType<WorkerController>();

            classFactory.RegisterType<IMessenger, ThreadMessenger>()
                .WithFactory<ThreadMessengerFactory>();

            classFactory.RegisterType<IFolder, FolderImp>()
                .WithFactory<IFolderFactoryForPath>();

            classFactory.RegisterType<IFile, FileImp>()
                .WithFactory<IFileFactoryForPath>();
        }
Ejemplo n.º 2
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ClassFactory classFactory = new ClassFactory();
            FillIoCContainer(classFactory);

            IMainController mainController = classFactory.ManufactureType<IMainController>();
            Application.Run(mainController.Start());
        }
Ejemplo n.º 3
0
 private static ClassFactory CreateInstance()
 {
     if (FClassFactory == null)
     {
         FClassFactory = new ClassFactory();
         FClassFactory.FDataLogic = new DataLogic();
         FClassFactory.FDataCommunication = new DataCommunication();
         FClassFactory.FLogicClass = new LogicClass();
     }
     return FClassFactory;
 }
Ejemplo n.º 4
0
        public void ClassFactory_CreateFromCode_ClassCreated()
        {
            // arrange
            // 1. load source files and get class and mixin declarations
            var sourceCode = new SourceCode(Files.Person);
            var personClass = sourceCode.Class(nameof(WorkingPerson));

            var classFactory = new ClassFactory(sourceCode.Semantic);
            var @class = classFactory.Create(personClass);

            Assert.AreEqual("Name", @class.Properties.Single().Name);
            Assert.AreEqual("void Work(int toolNumber)", @class.Methods.Single().ToString());
        }
Ejemplo n.º 5
0
        public void ClassWithBaseClass_CreateFromSymbol_ClassAndBaseClassCreated()
        {
            // arrange
            // 1. load source files and get class and mixin declarations
            var sourceCode = new SourceCode(Files.Person);
            var personClass = sourceCode.Class(nameof(ThirdPersonClass));

            var classFactory = new ClassFactory(sourceCode.Semantic);
            var @class = classFactory.Create(personClass);

            Assert.IsFalse(@class.Properties.Any());
            Assert.AreEqual("Name", @class.BaseClass.BaseClass.Properties.Single().Name);            
        }
Ejemplo n.º 6
0
        public void PropertiesInBaseClass_Mix_NoPropertyToImplement()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(ThirdPersonClass));
            var mixinField = personClass.FindMixinReference("_name");

            var child = new ClassFactory(sourceCode.Semantic).Create(personClass);
            var mixin = new MixinReferenceFactory(sourceCode.Semantic).Create(mixinField);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // Assert: all properties of mixin should be implemented
            Assert.IsEmpty(mixer.MembersToImplement);
        }
Ejemplo n.º 7
0
        public void PropertiesInMixinAndChild_Mix_OnlyMissingPropertiesToImplement()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(PersonWithFullName));
            var mixinField = personClass.FindMixinReference("_name");

            var child = new ClassFactory(sourceCode.Semantic).Create(personClass);
            var mixin = new MixinReferenceFactory(sourceCode.Semantic).Create(mixinField);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // Assert: all properties of mixin should be implemented
            Assert.AreEqual(2, mixer.MembersToImplement.Count());
        }
Ejemplo n.º 8
0
        public void MethodImplementedWithOtherParameter_Include_MethodIncluded()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(PersonWithOtherWorkMethod));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // no method to implement
            Assert.AreEqual(1,mixer.MethodsToImplement.Count(x => x.Name == "Work"));
        }
Ejemplo n.º 9
0
        public void MixinWithStaticMethod_Include_MethodNotIncluded()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(PersonWithStaticMethodMixin));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // no method to implement
            Assert.IsEmpty(mixer.MethodsToImplement);
        }
Ejemplo n.º 10
0
        public void MixinWithMethod_Include_MethodsIncluded()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(Person));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            Assert.AreEqual(mixer.MethodsToImplement.Count(), mixin.Class.Methods.Count());
            foreach (var service in mixin.Class.Methods)
                Assert.AreEqual(1, mixer.MethodsToImplement.Count(x => x.Name == service.Name));
        }
        public DeleteFolderResponse DeleteFolder(string sourceSchemaName, Guid[] records)
        {
            DeleteFolderResponse response;
            var deleteCommand = ClassFactory.Get <DeleteFolderCommand>(
                new ConstructorArgument("userConnection", UserConnection));

            try {
                response = new DeleteFolderResponse {
                    NeedUpdateFavoriteGroups = deleteCommand.Execute(sourceSchemaName, records),
                    Success = true
                };
            } catch (Exception e) {
                response = new DeleteFolderResponse(e)
                {
                    Success = false
                };
            }
            return(response);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取来源表头数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabet(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            ApiService.DAL.TaskLog.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);

            string sql = "select t.*,lt.cWhCode as cWhCode ,lt.cRdCode as cCode,lt.cRdStyleCode as MES_T_cRdStyleCode, ";

            sql += " lt.cdepcode as MES_T_cDepCode ";
            sql += ",'" + System.DateTime.Now.ToString(SysInfo.dateFormat) + "' as ddate ";
            sql += ",'生产订单' as cSource ";
            sql += ",'" + apidata.ConnectInfo.UserId + "'  as PRO_CMaker  ";
            sql += " from  v_mom_order_wf t with(nolock) left join " + bodytable + " lb with(nolock) on lb.mocode = t.mocode left join " + headtable + " lt with(nolock) on lt.id = lb.id where lt.id =" +
                   U8.Interface.Bus.Comm.Convert.ConvertDbValueFromPro(pdt.Id, "string") + " ";
            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            ApiService.BLL.Common.ErrorMsg(ds, "未能获取生产订单表头信息");
            return(ds);
        }
Ejemplo n.º 13
0
        /// <summary>Handles entity Saved event.</summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">The <see cref="T:Terrasoft.Core.Entities.EntityAfterEventArgs"/> instance containing the event data.</param>
        public override void OnSaved(object sender, EntityAfterEventArgs e)
        {
            base.OnSaved(sender, e);
            var entity         = (Entity)sender;
            var userConnection = entity.UserConnection;

            if (!userConnection.GetIsFeatureEnabled("CalcFormulaOnSave"))
            {
                return;
            }
            if (_isSettingsChanged && _isFormulaColumn)
            {
                var forecastId = entity.GetTypedColumnValue <Guid>("SheetId");
                IEnumerable <Guid> periodsId = GetPeriodsId(userConnection, forecastId);
                var calculator = ClassFactory.Get <IForecastCalculator>(ForecastConsts.FormulaColumnTypeName,
                                                                        new ConstructorArgument("userConnection", userConnection));
                calculator.Calculate(new ForecastCalcParams(forecastId, periodsId));
            }
        }
Ejemplo n.º 14
0
        public string SaveEn(string vals)
        {
            Entity en = null;

            try
            {
                AtPara ap     = new AtPara(vals);
                string enName = ap.GetValStrByKey("EnName");
                string pk     = ap.GetValStrByKey("PKVal");
                en = ClassFactory.GetEn(enName);
                en.ResetDefaultVal();

                if (en == null)
                {
                    throw new Exception("无效的类名:" + enName);
                }

                if (string.IsNullOrEmpty(pk) == false)
                {
                    en.PKVal = pk;
                    en.RetrieveFromDBSources();
                }

                foreach (string key in ap.HisHT.Keys)
                {
                    if (key == "PKVal")
                    {
                        continue;
                    }
                    en.SetValByKey(key, ap.HisHT[key].ToString().Replace('^', '@'));
                }
                en.Save();
                return(en.PKVal as string);
            }
            catch (Exception ex)
            {
                if (en != null)
                {
                    en.CheckPhysicsTable();
                }
                return("Error:" + ex.Message);
            }
        }
Ejemplo n.º 15
0
        private IMLDataUploader InitDataUploader()
        {
            Guid sessionId = _modelConfig.TrainSessionId;

            sessionId.CheckArgumentEmpty("MLModelConfig.TrainSessionId");
            ConstructorArgument sessionIdArg      = new ConstructorArgument("sessionId", _modelConfig.TrainSessionId);
            ConstructorArgument proxyArg          = new ConstructorArgument("mlServiceProxy", _proxy);
            ConstructorArgument userConnectionArg = new ConstructorArgument("userConnection", _userConnection);
            var config = new MLDataLoaderConfig {
                MinRecordsCount = _modelConfig.TrainingMinimumRecordsCount,
                MaxRecordsCount = _modelConfig.TrainingMaxRecordsCount
            };
            ConstructorArgument configArg    = new ConstructorArgument("config", config);
            IMLDataLoader       loader       = ClassFactory.Get <IMLDataLoader>(userConnectionArg, configArg);
            ConstructorArgument loaderArg    = new ConstructorArgument("loader", loader);
            IMLDataUploader     dataUploader = ClassFactory.Get <IMLDataUploader>(proxyArg, sessionIdArg, loaderArg);

            return(dataUploader);
        }
Ejemplo n.º 16
0
        private string GetFieldList()
        {
            string            list = "";
            ObjectDescription od   = ClassFactory.GetObjectDescription(_mapper.EntityType, _ps);

            foreach (PropertyDescription pd in od.Properties)
            {
                if (pd == od.IdField || pd.IsNonPersistent || pd.IsOneToManyRelation || pd.IsManyToManyRelation)
                {
                    continue;
                }
                if (list != "")
                {
                    list += ", ";
                }
                list += SqlMapper[pd.Name, true];
            }
            return(list);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 获取来源表头数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabet(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            string _sourcetablenameh = "SaleOrderQ";

            ApiService.DAL.TaskLog.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);

            string sql = "select t.*,";

            sql += "lt." + voucherNoColumnName + " as cCode ";
            sql += ",'" + System.DateTime.Now.ToString(SysInfo.dateFormat) + "' as ddate ";
            sql += ",lt.cRemark as mes_t_cRemark ";
            sql += " from  " + _sourcetablenameh + " t with(nolock) left join " + headtable + " lt with(nolock) on lt.cSoCode = t.cSoCode where lt.id ='" + pdt.Id + "' ";
            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            ApiService.BLL.Common.ErrorMsg(ds, "未能获取销售订单表头信息");
            return(ds);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 获取来源表体数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabets(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            string _sourcetablenameh = "SaleOrderQ";
            string _sourcetablenameb = "SaleOrderSQ";

            ApiService.DAL.TaskLog.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);  //ClassFactory.GetITaskLogMain(3);;
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);
            string            sql     = "select b.*,";

            sql += " CASE lb.opertype WHEN 0 THEN 'A' WHEN 1 THEN 'M' WHEN '2' THEN 'D' ELSE 'A' END as editprop, ";
            sql += "lb.cWhCode as mes_cWhCode,lb.iquantity as mes_iquantity,lb.cvencode as mes_cvencode   ";
            sql += " from " + _sourcetablenameb + " b with(nolock) left join  " + _sourcetablenameh + " t with(nolock) on b.id = t.id left join " + bodytable + " lb with(nolock) on lb.isosid = b.isosid left join " + headtable + " lt with(nolock) on lt.id = lb.id where lt.id ='" + pdt.Id + "' ";

            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            ApiService.BLL.Common.ErrorMsg(ds, "未能获取销售订单表体信息");
            return(ds);
        }
Ejemplo n.º 19
0
 public CompilationResult CompileAll()
 {
     if (UserConnection.DBSecurityEngine.GetCanExecuteOperation("CanManageSolution"))
     {
         WorkspaceBuilder        workspaceBuilder = WorkspaceBuilderUtility.CreateWorkspaceBuilder(AppConnection);
         CompilerErrorCollection compilerErrors   = workspaceBuilder.Rebuild(AppConnection.Workspace,
                                                                             out var buildResultType);
         var configurationBuilder = ClassFactory.Get <IAppConfigurationBuilder>();
         configurationBuilder.BuildAll();
         return(new CompilationResult {
             Status = buildResultType,
             CompilerErrors = compilerErrors
         });
     }
     else
     {
         throw new Exception("You don't have permission for operation CanManageSolution");
     }
 }
Ejemplo n.º 20
0
        private void CreateXmlNodeEl(EntityBase entity, XmlWriter writer)
        {
            writer.WriteStartElement(Mapper.TableName);
            writer.WriteAttributeString("Id", entity.ID.ToString());
            foreach (PropertyDescription property in ClassFactory.GetObjectDescription(ReflectedType, _ps).Properties)
            {
                if (property.IsId || !(property.IsMapped || property.IsManyToManyRelation))
                {
                    continue;
                }


                writer.WriteStartElement(property.Name);
                object value = null;
                try
                {
                    if (property.IsManyToManyRelation)
                    {
                        WriteMtm(entity, property, writer);
                    }
                    else
                    {
                        if (property.IsOneToOneRelation)
                        {
                            value = (entity[property.Name] as EntityBase).ID;
                        }
                        else
                        {
                            value = entity[property.Name];
                        }
                        value = PrepareToSave(value);
                        writer.WriteValue(value);
                    }
                }
                catch
                {
                    throw new ApplicationException(string.Format("Unable to write attribute: {0}", property.Name));
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
        /// <summary>
        /// Send registration confirmation email.
        /// </summary>
        /// <param name="userConnection">User connection.</param>
        /// <param name="contactId">Contact identifier.</param>
        /// <param name="confirmRegistrationUrl">Confirmation registration url.</param>
        public static void SendEmail(UserConnection userConnection, Guid contactId, string confirmRegistrationUrl)
        {
            if (confirmRegistrationUrl.IsNullOrEmpty())
            {
                string errorMessage = GetLocalizableString(userConnection, "LinkNotExist");
                throw new ArgumentNullOrEmptyException(errorMessage, null);
            }
            string contactEmail = GetContactEmail(userConnection, contactId);
            var    esq          = new EntitySchemaQuery(userConnection.EntitySchemaManager, "EmailTemplate");

            esq.AddColumn("Subject");
            esq.AddColumn("Body");
            esq.AddColumn("IsHtmlBody");
            esq.AddColumn("Macros");
            Guid registrationEmailTemplateId = GetRegistrationEmailTemplateId(userConnection);
            var  template = (EmailTemplate)esq.GetEntity(userConnection, registrationEmailTemplateId);

            if (template == null)
            {
                string errorMessage = GetLocalizableString(userConnection, "EmailTemplateNotFound");
                throw new ArgumentNullOrEmptyException(errorMessage, null);
            }
            var body    = ReplaceRegistrationUrl(userConnection, contactId, confirmRegistrationUrl, template);
            var subject = ReplaceRegistrationUrl(userConnection, contactId, confirmRegistrationUrl, template);

            if (userConnection.GetIsFeatureEnabled("EmailIntegrationV2") ||
                userConnection.GetIsFeatureEnabled("UseEmailSenderForSelfReg"))
            {
                SendWithEmailSender(userConnection, contactEmail, body, subject);
            }
            else
            {
                var emailMessage = CreateEmailMessage(userConnection, contactEmail, body, subject);
                emailMessage.Attachments = GetEmailAttachmentsFromTemplate(registrationEmailTemplateId, userConnection);
                var credentials        = CreateMailCredentials(userConnection);
                var emailClientFactory = GetEmailClientFactory(userConnection);
                var emailSender        = ClassFactory.Get <IEmailSender>(
                    new ConstructorArgument("emailClientFactory", emailClientFactory),
                    new ConstructorArgument("userConnection", userConnection));
                emailSender.Send(emailMessage, credentials);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 获取来源表头数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabet(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            ApiService.DAL.TaskLog.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);

            //string sql = "select mrd.*,mr.moid,mr.modid,";   // mrd.FirstFlag  1 首工序
            //sql += " '" + cimodel.UserId + "' as cMaker,";
            //sql += " '" + System.DateTime.Now.ToString(SysInfo.dateFormat) + "' as dTVDate ";   //移库日期
            //sql += ",'" + System.DateTime.Now.ToString(SysInfo.datetimeFormat) + "' as dnmaketime, ";   //制单时间
            //sql += " lt.MOCODE as mes_MOCODE ,";  //生产订单号
            //sql += " lt.MOSEQ as mes_MOSEQ ,";   //订单行号
            //sql += " lt.ITEMCODE as mes_ITEMCODE ,";  //物料编码
            //sql += " lt.OPSeq as mes_OPSeq ,";  //工序行号
            //sql += " lt.OPCode as mes_OPCode, ";  //工序编号
            //sql += " lt.OPDescription as mes_OPDescription,  ";   //工序说明
            //sql += " lt.PersonCode as mes_PersonCode,  ";   //人员编码
            //sql += " lt.ResCode as mes_ResCode,  ";   //资源编码
            //sql += " lt.Istatus as mes_Istatus,  ";   //状态
            //sql += " lt.Qty as mes_Qty,  ";   //数量
            //sql += " lt.StartDate as mes_StartDate,  ";   //开工日期
            //sql += " lt.StartTime as mes_StartTime,  ";   //开工时间
            //sql += " lt.ISCOMDATE as mes_ISCOMDATE,  ";   //完工时间
            //sql += " lt.ISCOMTIME as mes_ISCOMTIME,  ";   //完工时间
            //sql += " lt.opdoccode as mes_opdoccode,  ";   //生成的工序转移单号
            //sql += " lt.workdoccode as mes_workdoccode  ";   //生成的工时记录单号
            //sql += " from " + headtable + " with(nolock) ";
            //sql += " inner join mom_order m with(nolock) on op.mocode = m.mocode ";
            //sql += " inner join sfc_morouting mr with(nolock) on m.moid = mr.moid ";
            //sql += " inner join sfc_moroutingdetail mrd with(nolock) on mr.MoRoutingId = mrd.MoRoutingId and op.OPSeq = mrd.OPSeq ";
            // sql   += " where lt.id ='" + pdt.Id + "' ";
            //DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            //DataSet ds = help.Query(sql);

            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);

            IDataParameter[] Para = new SqlParameter[1];
            Para[0] = new SqlParameter("@id", pdt.Id);
            DataSet ds = help.RunProcedure("Proc_GetOptranform", Para, "MES_Int_optransform");

            BLL.Common.ErrorMsg(ds, "未能获取 表头信息");
            return(ds);
        }
Ejemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.All;
            });

            services.AddSingleton(Configuration);

            services.AddTransient <ChannelBase>(delegate
            {
                return(new Channel("localhost:9080", ChannelCredentials.Insecure));
            });

            services.AddTransient(sp =>
                                  new Dgraph4NetClient(sp.GetRequiredService <ChannelBase>()));

            ClassFactory.MapAssembly(typeof(DUser).Assembly);

            var channel = new Channel("localhost:9080", ChannelCredentials.Insecure);
            var dgraph  = new Dgraph4NetClient(channel);

            if (!File.Exists("schema.dgraph"))
            {
                dgraph.Alter(new Api.Operation {
                    DropAll = true
                }).GetAwaiter().GetResult();
            }

            // sends mapping to Dgraph
            dgraph.Map(typeof(DUser).Assembly);

            services.AddIdentity <DUser, DRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoleStore <RoleStore>()
            .AddUserStore <UserStore>()
            .AddDefaultTokenProviders()
            .AddDefaultUI();

            services.AddTransient <UserStore, UserStore>();

            services.AddRazorPages();
        }
Ejemplo n.º 24
0
        private string BuildGetMTMQuery(PropertyDescription property, object entityId)
        {
            Cryptany.Core.DPO.Mapper m = new Mapper(property.ReflectedObject.ObjectType, _ps);
            string mtmTableName        = "";

            if (!string.IsNullOrEmpty(property.RelationAttribute.SchemaName))
            {
                mtmTableName = property.RelationAttribute.SchemaName + "."
                               + property.RelationAttribute.MamyToManyRelationTable;
            }
            else if (m.SchemaName != "")
            {
                mtmTableName = m.SchemaName + "." + property.RelationAttribute.MamyToManyRelationTable;
            }
            else
            {
                mtmTableName = property.RelationAttribute.MamyToManyRelationTable;
            }
            string select = "SELECT t1.";

            select += property.RelationAttribute.MtmRelationTableParentColumn + ", ";
            select += property.RelationAttribute.MtmRelationTableChildColumn + " ";
            select += "FROM " + mtmTableName + " AS t1 ";

            ObjectDescription od   = ClassFactory.GetObjectDescription(ReflectedType, _ps);
            TableAttribute    attr = od.DbTableAttribute;

            if (attr != null && attr.ToString() != "")
            {
                string select2 = "INNER JOIN " + Mapper.FullTableName + " AS t2 ON ";
                select2 += "t1." + property.RelationAttribute.MtmRelationTableParentColumn + " = ";
                select2 += "t2." + Mapper[od.IdField.Name, true];
                select2 += " AND t2." + attr.ToString();
                select  += select2;
            }
            if (entityId != null)
            {
                string where = " WHERE t1." + m[od.IdField.Name, true] + " = " + IdToString(entityId);
                select      += where;
            }
            return(select);
        }
Ejemplo n.º 25
0
        public string CreateInsertStatement(IList <EntityBase> list)
        {
            string            fieldList = "";
            ObjectDescription od        = ClassFactory.GetObjectDescription(_mapper.EntityType, _ps);

            fieldList += _mapper[od.IdField.Name, true];
            foreach (PropertyDescription pd in od.Properties)
            {
                if (pd == od.IdField || pd.IsNonPersistent || pd.IsOneToManyRelation || pd.IsManyToManyRelation)
                {
                    continue;
                }
                //if ( fieldList != "" )
                fieldList += ", ";
                fieldList += SqlMapper[pd.Name];
            }
            string valuesTable = "";

            foreach (EntityBase e in list)
            {
                string valuesRow = "";
                valuesRow += ValueToString(e.ID);
                foreach (PropertyDescription pd in od.Properties)
                {
                    if (pd == od.IdField || pd.IsNonPersistent || pd.IsOneToManyRelation || pd.IsManyToManyRelation)
                    {
                        continue;
                    }

                    //if ( valuesRow != "" )
                    valuesRow += ", ";
                    valuesRow += ValueToString(e[pd.Name]);
                }
                valuesRow = "SELECT " + valuesRow;
                if (valuesTable != "")
                {
                    valuesTable += "\r\nUNION ALL\r\n";
                }
                valuesTable += valuesRow;
            }
            return(_insertTemplate.Replace("@@FieldList", fieldList).Replace("@@Values", valuesTable));
        }
Ejemplo n.º 26
0
        /// <inheritdoc cref="IJobExecutor.Execute(UserConnection userConnection, IDictionary{string, object})"/>
        public void Execute(UserConnection userConnection, IDictionary <string, object> parameters)
        {
            var senderEmailAddress = parameters["SenderEmailAddress"].ToString();

            _log.Info($"ConnectionEventExecutor.Execute for {senderEmailAddress} started");
            var helper = ClassFactory.Get <ISynchronizationErrorHelper>
                             (new ConstructorArgument("userConnection", userConnection));
            var ignoreRetryCount = GetIgnoreRetryCount(parameters);

            if ((bool)parameters["Avaliable"])
            {
                helper.CleanUpSynchronizationError(senderEmailAddress);
            }
            else
            {
                helper.ProcessSynchronizationError(senderEmailAddress,
                                                   parameters["ExceptionClassName"].ToString(), parameters["ExceptionMessage"].ToString(), ignoreRetryCount);
            }
            _log.Info($"ConnectionEventExecutor.Execute for {senderEmailAddress} finished");
        }
Ejemplo n.º 27
0
        public GameSession()
        {
            CurrentPlayer = new Player("Kuba", ClassFactory.GetClassByName("Válečník"), 0, 10, 10, 0, 100, 100);

            if (!CurrentPlayer.Weapons.Any())
            {
                CurrentPlayer.AddItemToInventory(ItemFactory.CreateGameItem(1001));
                CurrentPlayer.AddItemToInventory(SpellFactory.CreateSpell(1001));
            }
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateGameItem(2001));
            CurrentPlayer.LearnRecipe(RecipeFactory.RecipeByID(1));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateGameItem(3001));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateGameItem(3002));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateGameItem(3003));
            CurrentPlayer.SetBaseStrenght(2);

            CurrentWorld = WorldFactory.CreateWorld();

            CurrentLocation = CurrentWorld.LocationAt(0, 0);
        }
Ejemplo n.º 28
0
        public ServiceTermResponse GetServiceTerm(ServiceTermRequest request)
        {
            var userConnection = (UserConnection)HttpContext.Current.Session["UserConnection"];
            var termCalculator = ClassFactory.Get <TermCalculatorITILService>(
                new ConstructorArgument("userConnection", userConnection),
                new ConstructorArgument("servicePactId", request.ServicePactId),
                new ConstructorArgument("serviceItemId", request.ServiceItemId),
                new ConstructorArgument("priorityId", request.PriorityId)
                );
            DateTime registrationTime = DateTime.Parse(request.RegistrationTime);
            DateTime reactionTime     = termCalculator.Calculate(registrationTime,
                                                                 TermCalculationConstants.ReactionTimeColumnsConfig);
            DateTime solutionTime = termCalculator.Calculate(registrationTime,
                                                             TermCalculationConstants.SolutionTimeColumnsConfig);

            return(new ServiceTermResponse {
                ReactionTime = reactionTime,
                SolutionTime = solutionTime
            });
        }
Ejemplo n.º 29
0
                protected void EarthView_World_Graphic_CScriptLoader_parseScript_void_DataStreamPtr_EVString_Function(IntPtr stream, ref IntPtr groupName)
                {
                    EarthView.World.Core.DataStreamPtr csobj_stream = new EarthView.World.Core.DataStreamPtr(CreatedWhenConstruct.CWC_NotToCreate);
                    csobj_stream.BindNativeObject(stream, "DataStreamPtr");
                    csobj_stream.Delegate = true;
                    IClassFactory csobj_streamClassFactory = GlobalClassFactoryMap.Get(csobj_stream.GetCppInstanceTypeName());

                    if (csobj_streamClassFactory != null)
                    {
                        csobj_stream.Delegate = true;
                        csobj_stream          = csobj_streamClassFactory.Create() as EarthView.World.Core.DataStreamPtr;
                        csobj_stream.BindNativeObject(stream, "DataStreamPtr");
                        csobj_stream.Delegate = true;
                    }
                    string strgroupName = Marshal.PtrToStringAnsi(groupName);

                    ClassFactory.FreeString(ref groupName);

                    ParseScript(ref csobj_stream, strgroupName);
                }
Ejemplo n.º 30
0
        public void ProcessMailboxState(MailboxState mailboxState)
        {
            var logMessage = string.Concat($"ProcessMailboxState mailbox = {mailboxState.SenderEmailAddress}, ",
                                           $"avaliable = {mailboxState.Avaliable}, ",
                                           $"exception = {mailboxState.ExceptionClassName}, ",
                                           $"message = {mailboxState.ExceptionMessage}, ",
                                           $"context = {mailboxState.Context}");

            if (mailboxState.Avaliable)
            {
                _log.Info(logMessage);
            }
            else
            {
                _log.Error(logMessage);
            };
            var connectionEventsProcessor = ClassFactory.Get <IMailboxStateEventsProcessor>();

            connectionEventsProcessor.ProcessMailboxState(mailboxState);
        }
        /// <summary>
        /// Notifies the model owners.
        /// </summary>
        /// <param name="message">The message for notification.</param>
        public virtual void NotifyModelEventRecipients(string message)
        {
            if (!_userConnection.GetIsFeatureEnabled("MLNotifications"))
            {
                return;
            }
            var remindingUtilities = ClassFactory.Get <RemindingUtilities>();

            foreach (Guid contactId in GetTargetContacts())
            {
                var config = new RemindingConfig(_contactSchemaUId)
                {
                    AuthorId    = _userConnection.CurrentUser.ContactId,
                    ContactId   = contactId,
                    SubjectId   = contactId,
                    Description = message
                };
                remindingUtilities.CreateReminding(_userConnection, config);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 获取来源表体数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabets(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            ApiService.DAL.TaskLogFactory.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);  //new ApiService.DAL.SynergismLogDt();
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);
            string            sql     = "select b.*,";

            sql += " lt.cWhCode as MES_cWhCode,lt.cRdCode as cCode,";
            sql += "lb.iquantity as MES_iquantity, lb.cVenCode as mes_cvencode,lb.cpinvcode as mes_cpinvcode,lb.cInvCode as mes_cinvcode,lb.mocode as mes_mocode,  ";
            sql += " CASE lb.opertype WHEN 0 THEN 'A' WHEN 1 THEN 'M' WHEN '2' THEN 'D' ELSE 'A' END as editprop  ";
            sql += " from " + sourceBodyTable + " sb with(nolock) INNER JOIN  " + sourceHeadTable + " t with(nolock) on sb.moid = t.moid ";
            sql += " INNER JOIN mom_moallocate b with(nolock) on b.modid = sb.modid ";
            sql += " INNER JOIN " + bodytable + " lb with(nolock) on lb.mocode = t.mocode and lb.cinvcode = b.invcode and lb.cpinvcode = sb.dinvcode ";
            sql += " INNER JOIN " + headtable + " lt with(nolock) on lt.id = lb.id where lt.id ='" + pdt.Id + "' ";

            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            BLL.Common.ErrorMsg(ds, "未能获取生产订单表体信息");
            return(ds);
        }
Ejemplo n.º 33
0
        /// <summary>  Construct a new DataObjectOutputStream</summary>
        /// <returns> A new DataObjectOutputStream object, which will always be a
        /// an instanceof DataObjectOutputStreamImpl as defined by the
        /// <c>adkglobal.factory.DataObjectOutputStream</c> system property.
        ///
        /// </returns>
        public static DataObjectOutputStreamImpl NewInstance()
        {
            String cls = Properties.GetProperty("adkglobal.factory.DataObjectOutputStream");

            if (cls == null)
            {
                return(new DataObjectOutputFileStream());
            }
            else
            {
                try {
                    return((DataObjectOutputStreamImpl)ClassFactory.CreateInstance(cls));
                }
                catch (Exception thr) {
                    throw new AdkException
                              ("Adk could not create an instance of the class " + cls + ": " + thr, null,
                              thr);
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 获取来源表体数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabets(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            ApiService.DAL.TaskLogFactory.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);  //new ApiService.DAL.SynergismLogDt();
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);
            string            sql     = "select  ";

            sql += " lt.cWhCode as MES_cWhCode,lt.cRdStyleCode as MES_cRdCode,lt.cDepCode as MES_cDepCode,";
            //sql += " lt.cPersonCode as MES_cPersonCode, ";
            sql += " lt.cvencode as MES_cvencode,";
            sql += " CASE lb.opertype WHEN 0 THEN 'A' WHEN 1 THEN 'M' WHEN '2' THEN 'D' ELSE 'A' END as editprop, ";
            sql += " lb.cinvcode as mes_cinvcode   ";
            sql += " ,lb.iquantity as MES_iquantity   ";
            sql += " from   " + bodytable + " lb with(nolock) INNER JOIN " + headtable + " lt with(nolock) on lt.id = lb.id where lt.id ='" + pdt.Id + "' ";

            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            BLL.Common.ErrorMsg(ds, "未能获取 表体信息");
            return(ds);
        }
Ejemplo n.º 35
0
        public override void PrepereSynchronizeSubjectRemindingUserTask(SynchronizeSubjectRemindingUserTask userTask, Guid contact, DateTime remindTime, bool active, Guid source)
        {
            base.PrepereSynchronizeSubjectRemindingUserTask(userTask, contact, remindTime, active, source);
            bool isFeatureEnabled = FeatureUtilities.GetIsFeatureEnabled(UserConnection, "NotificationV2");

            if (isFeatureEnabled)
            {
                IRemindingTextFormer textFormer = ClassFactory.Get <ActivityRemindingTextFormer>(
                    new ConstructorArgument("userConnection", UserConnection));
                string accountName = GetLookupDisplayColumnValue(Entity, "Account");
                string contactName = GetLookupDisplayColumnValue(Entity, "Contact");
                string title       = Entity.GetTypedColumnValue <string>("Title");
                userTask.SubjectCaption = textFormer.GetBody(new Dictionary <string, object> {
                    { "AccountName", accountName },
                    { "ContactName", contactName },
                    { "Title", title }
                });
                userTask.PopupTitle = textFormer.GetTitle(new Dictionary <string, object>());
            }
        }
Ejemplo n.º 36
0
        public CompareViewModel()
        {
            #region 让Caliburn 知道

            Assembly assembly = Assembly.GetExecutingAssembly();
            if (!AssemblySource.Instance.Contains(assembly))
            {
                AssemblySource.Instance.Add(assembly);
            }

            #endregion


            _service = ClassFactory.GetInstance <ICompareService>();
            _appInfo = new AppInfo();
            DicError.Add(1, "对象不一致");
            DicError.Add(2, "对象丢失");
            DicError.Add(3, "对象冗余");
            ResultsList = new ObservableCollection <UICompareResult>();
        }
Ejemplo n.º 37
0
        public void MixinClassWithProperty_Include_PropertiesIncluded()
        {
            // arrange
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(Person));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // assert all properties of the mixin should have been added
            Assert.AreEqual(mixin.Class.Properties.Count(),mixer.PropertiesToImplement.Count());
            // check that every method of mixin appears only once in the child
            foreach (var service in mixin.Class.Properties)
                Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.Name == service.Name));
        }
Ejemplo n.º 38
0
        private IImapClient GetImapClientByMailboxId(string mailboxId, out string mailboxName)
        {
            mailboxName = string.Empty;
            var mailboxEntitySchema = UserConnection.EntitySchemaManager.GetInstanceByName("MailboxSyncSettings");
            var mailbox             = mailboxEntitySchema.CreateEntity(UserConnection);

            if (!mailbox.FetchFromDB(new Guid(mailboxId)))
            {
                return(null);
            }
            mailboxName = mailbox.GetTypedColumnValue <string>("UserName");
            var mailServerUId          = mailbox.GetTypedColumnValue <Guid>("MailServerId");
            var mailServerEntitySchema = UserConnection.EntitySchemaManager.GetInstanceByName("MailServer");
            var currentMailServer      = mailServerEntitySchema.CreateEntity(UserConnection);

            if (!currentMailServer.FetchFromDB(mailServerUId) || !currentMailServer.GetTypedColumnValue <bool>("AllowEmailDownloading"))
            {
                return(null);
            }
            var imapServerCredentials = new MailCredentials {
                Host               = currentMailServer.GetTypedColumnValue <string>("Address"),
                Port               = currentMailServer.GetTypedColumnValue <int>("Port"),
                UseSsl             = currentMailServer.GetTypedColumnValue <bool>("UseSSL"),
                UserName           = mailbox.GetTypedColumnValue <string>("UserName"),
                UserPassword       = mailbox.GetTypedColumnValue <string>("UserPassword"),
                StartTls           = currentMailServer.GetTypedColumnValue <bool>("IsStartTls"),
                SenderEmailAddress = mailbox.GetTypedColumnValue <string>("SenderEmailAddress"),
            };

            try {
                return(ClassFactory.Get <IImapClient>("OldEmailIntegration",
                                                      new ConstructorArgument("credentials", imapServerCredentials),
                                                      new ConstructorArgument("errorMessages", new Terrasoft.Mail.ImapErrorMessages()),
                                                      new ConstructorArgument("userConnection", UserConnection),
                                                      new ConstructorArgument("login", true)));
            } catch (Exception ex) {
                SynchronizationErrorHelper helper = SynchronizationErrorHelper.GetInstance(UserConnection);
                helper.ProcessSynchronizationError(imapServerCredentials.SenderEmailAddress, ex, true);
                throw;
            }
        }
Ejemplo n.º 39
0
        /// <inheritdoc cref="BaseLoadEmailEventExecutor.Synchronize(UserConnection, IDictionary{string, object})"/>
        protected override void Synchronize(UserConnection uc, IDictionary <string, object> parameters)
        {
            _log.Info($"LoadEmailEventExecutor.Synchronize started");
            var emails = parameters["Items"] as IEnumerable <Email>;

            if (!emails.Any())
            {
                _log.Info($"LoadEmailEventExecutor.Synchronize - no emails passed");
                return;
            }
            if (!uc.LicHelper.GetHasOperationLicense("Login"))
            {
                _log.Info($"LoadEmailEventExecutor.Synchronize - user has no license!");
                return;
            }
            var emailService = ClassFactory.Get <IEmailService>(new ConstructorArgument("uc", uc));

            _log.Info($"IEmailService created");
            var synsSessionId = string.Format("LoadEmailEventSyncSession_{0}", Guid.NewGuid());
            var mailboxId     = (Guid)parameters["MailboxId"];

            foreach (var emailDto in emails)
            {
                if (emailDto == null)
                {
                    continue;
                }
                if (LockItemForSync(uc, emailDto))
                {
                    _log.Info($"{synsSessionId} - item {emailDto.MessageId} locked for sync");
                    emailService.Save(emailDto, mailboxId, synsSessionId);
                }
                else
                {
                    NeedReRun = true;
                }
            }
            SaveSyncSession(uc, synsSessionId);
            UnlockSyncedEntities(uc);
            _log.Info($"LoadEmailEventExecutor.Synchronize ended");
        }
Ejemplo n.º 40
0
        /// <summary>
        /// 获取来源表头数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pdt"></param>
        /// <param name="apidata"></param>
        /// <returns></returns>
        public override System.Data.DataSet SetFromTabet(Model.Synergismlogdt dt, Model.Synergismlogdt pdt, Model.APIData apidata)
        {
            ApiService.DAL.TaskLogFactory.ITaskLogDetail dtdal = ClassFactory.GetITaskLogDetailDAL(apidata.TaskType);
            Model.ConnectInfo cimodel = dtdal.GetConnectInfo(pdt);

            string sql = "select ";

            sql += " lt.cvencode as MES_cvencode,";
            sql += " '" + System.DateTime.Now.ToString(SysInfo.dateFormat) + "' as ddate ";           //入库日期
            sql += ",'" + System.DateTime.Now.ToString(SysInfo.datetimeFormat) + "' as dnmaketime, "; //制单时间
            sql += " lt.cRdCode as cCode ,";
            sql += " lt.cWhCode as MES_cWhCode,lt.cRdStyleCode as MES_cRdCode,lt.cDepCode as MES_cDepCode ";
            //sql += " ,lt.cPersonCode as MES_cPersonCode ";
            sql += " from   " + bodytable + " lb with(nolock) INNER JOIN " + headtable + " lt with(nolock) on lt.id = lb.id where lt.id ='" + pdt.Id + "' ";

            DbHelperSQLP help = new DbHelperSQLP(cimodel.Constring);
            DataSet      ds   = help.Query(sql);

            BLL.Common.ErrorMsg(ds, "未能获取 表头信息");
            return(ds);
        }
        /// <summary>
        /// Send email asynchronously.
        /// </summary>
        /// <param name="userConnection">User connection.</param>
        /// <param name="parameters">Parameters.</param>
        public virtual void Execute(UserConnection userConnection, IDictionary <string, object> parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullOrEmptyException("parameters can't be null");
            }
            Guid activityId = parameters.GetValue("activityId", Guid.Empty);

            if (activityId != Guid.Empty)
            {
                var userConnectionArg  = new ConstructorArgument("userConnection", userConnection);
                var emailClientFactory = ClassFactory.Get <EmailClientFactory>(userConnectionArg);
                var sender             = userConnection.GetIsFeatureEnabled("SecureEstimation") ? new SecureActivityEmailSender(emailClientFactory, userConnection) :
                                         new ActivityEmailSender(emailClientFactory, userConnection);
                sender.Send(activityId);
            }
            else
            {
                throw new ArgumentException("ActivityId must be specified");
            }
        }
Ejemplo n.º 42
0
        public void MixinWithPropertyOnlyGetter_Include_PropertyHasGetter()
        {
            // arrange
            // 1. load source files and get class and mixin declarations
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(PersonWithGetterName));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            // 2. create instances for mixin and child mixin
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // assert. Only one property in resulting class
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count());
            // that one property should only have a getter
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.IsReadOnly));
        }
Ejemplo n.º 43
0
        public void MixinInterfaceWithProperty_Include_PropertiesIncluded()
        {
            // arrange
            // 1. load source files and get class and mixin declarations
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(Person));
            var mixinReference = personClass.FindMixinReference("_interfaceName");
            var semanticModel = sourceCode.Semantic;
            // 2. create instances for mixin and child mixin
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // assert. The child should have the same properties as the mixin
            Assert.AreEqual(mixin.Class.Properties.Count(), mixer.PropertiesToImplement.Count());
            // check that every method of mixin appears only once in the child
            foreach (var service in mixin.Class.Properties)
                Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.Name == service.Name));
        }
Ejemplo n.º 44
0
        public void MixinWithGenericProperty_Include_PropertyImplemented()
        {
            // arrange
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(PersonWithGenericMixin));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // child should have "Name" property
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.Name == "Names"));
            // name property should be of type "IEnumerable<string>"
            var typeName = mixer.PropertiesToImplement.Single().Type.ToString();
            Assert.AreEqual("System.Collections.Generic.IEnumerable<string>", typeName);
        }
Ejemplo n.º 45
0
        public void MixinWithGenericParameter_Include_MixinImplemented()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(PersonWithGenericClassMixin));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should be one method to implement
            Assert.AreEqual(1, mixer.MethodsToImplement.Count());
            // parameter and return type of the method should be int
            Assert.AreEqual("int", mixer.MethodsToImplement.Single().ReturnType.ToString());
            Assert.AreEqual("int", mixer.MethodsToImplement.Single().GetParameter(0).Type.ToString());
        }
Ejemplo n.º 46
0
        public void MixinWithIndexer_Include_IndexerImplemented()
        {
            // arrange
            var sourceCode = new SourceCode(Files.Person, Files.Collection);
            var personClass = sourceCode.Class(nameof(PersonWithIndexer));
            var mixinReference = personClass.FindMixinReference("_collection");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // child should also have an indexer property now
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count());
            Assert.AreEqual("string this[int index]", mixer.PropertiesToImplement.Single().ToString());            
        }
Ejemplo n.º 47
0
        public void ChildWithAbstractProperty_Include_AbstractPropertyOverridden()
        {
            // we need Person file and NotCompilable because
            // the base class is defined in Person file
            var sourceCode = new SourceCode(Files.Person, Files.NotCompilable, Files.Name);
            var personClass = sourceCode.Class("PersonFromAbstractName");
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should be two methods, from base mixin and derived mixin
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count());
            // only one method from the mixin should be implemented, the other one
            // is alredy implemented by childs base
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.Name == "Name"));
            Assert.IsTrue(mixer.PropertiesToImplement.Single().IsOverride);
        }
Ejemplo n.º 48
0
        public void MixinWithToString_Include_ToStringShouldBeImplemented()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(PersonWithToString));
            var mixinReference = personClass.FindMixinReference("_toString");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // ToString should be in list of methods to override
            Assert.IsTrue(mixer.MethodsToImplement.Any(x => x.Name == "ToString"));
            // ToString in mixin must have override keyword
            Assert.IsTrue(mixer.MethodsToImplement.Single(x => x.Name == "ToString").IsOverrideFromObject);
        }
Ejemplo n.º 49
0
        public void MixinWithBaseClass_Include_BothMethodsImplemented()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(PersonWithDerivedWorker));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should be two methods, from base mixin and derived mixin
            Assert.AreEqual(2, mixer.MethodsToImplement.Count());
            // method from base should be in the implementation list
            Assert.AreEqual(1, mixer.MethodsToImplement.Count(x => x.Name == "Work"));
            // method from derived should be in the implementation list
            Assert.AreEqual(1, mixer.MethodsToImplement.Count(x => x.Name == "AdditionalWork"));            
        }
Ejemplo n.º 50
0
        public void ChildWithBaseMethod_Include_BaseMethodNotImplemented()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker);
            var personClass = sourceCode.Class(nameof(DerivedPerson));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should be two methods, from base mixin and derived mixin
            Assert.AreEqual(1, mixer.MethodsToImplement.Count());
            // only one method from the mixin should be implemented, the other one
            // is alredy implemented by childs base
            Assert.AreEqual(1, mixer.MethodsToImplement.Count(x => x.Name == "Work"));
        }
Ejemplo n.º 51
0
        public void ChildHasInterfaceWithProperty_Include_PropertyImplemented()
        {
            // arrange
            var sourceCode = new SourceCode(Files.NotCompilable, Files.Name);
            var personClass = sourceCode.Class("DerivedFromInterfaceClass");
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // assert: Child should have one "Name" property
            Assert.AreEqual(1, mixer.PropertiesToImplement.Count(x => x.Name == "Name"));
            // this one property should have only getter (signature from interface and mixin is the same)
            Assert.IsTrue(mixer.PropertiesToImplement.Single(x => x.Name == "Name").IsReadOnly);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// alternate constructor -- performs the initialization, including reading the config
        /// file, instantiating and initializing the configured stations, 
        /// specifying an alternate class factory to instantiate stations.
        /// </summary>
        /// <param name="configName">name of configuration file which describes this specific pipeline</param>
        /// <param name="memory">instance memory to be associated with this pipeline</param>
        /// <param name="stationCreator">used when we had problems finding classes in a different assembly</param>
        public Pipeline(string configName, InstanceMemory memory, ClassFactory stationCreator)
        {
            this.classFactory = stationCreator;

            this.memory = memory;

            // read config file
            Stream configStream = new FileStream(configName, FileMode.Open, FileAccess.Read);
            // TODO new way to get the resource file -- actually should use IOC / Dependency Injection
            //         also accept a stream instead of a file

            ConfigData config = new ConfigData(configStream);

            errors = "";
            errorsDetail = "";

            ConfigureCommands(config);

            ConfigureStations(memory, config);

            ConfigFile = (configName);
            Description = (config.RequiredValue("description"));

            if (errors.Length > 0)
            {
                //Console.Error.WriteLine("WARNING: " + _errors); // leave it to the app to decide how to present error messages
                //throw new StationFailedException(_errors); // allow the constructor to succeed, caller can check HasError
            }
        }
Ejemplo n.º 53
0
 public void Setup()
 {
     _sourceCode = new SourceCode(Files.Interface);
     _factory = new ClassFactory(_sourceCode.Semantic);
 }
Ejemplo n.º 54
0
        public void MixinWithStaticProperty_Include_PropertyNotImplemented()
        {
            // arrange
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(PersonWithStaticMixin));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // assert: Child should not have a "Name" property
            Assert.IsEmpty(mixer.PropertiesToImplement);
        }
Ejemplo n.º 55
0
        public void ChildWithOverrideMethod_Include_MethodOverrideNotCreated()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Worker); 
            var personClass = sourceCode.Class(nameof(PersonWithOverriddenMethod));
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should not be any method to override,
            // because the child itself already overrides the method
            Assert.AreEqual(0, mixer.MethodsToImplement.Count());
        }
Ejemplo n.º 56
0
        public void ChildWithOverrideProperty_Include_PropertyOverrideNotCreated()
        {
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(PersonWithOverriddenProperty));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // no property to override because child overrides it already
            Assert.AreEqual(0, mixer.PropertiesToImplement.Count());
        }
Ejemplo n.º 57
0
        public void ChildWithAbstractMethodFromBase_Include_AbstractMethodOverridden()
        {
            // file Person with base class is also needed here
            var sourceCode = new SourceCode(Files.Person, Files.NotCompilable, Files.Worker);
            var personClass = sourceCode.Class("PersonFromAbstractWork");
            var mixinReference = personClass.FindMixinReference("_worker");
            var semanticModel = sourceCode.Semantic;

            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // there should be one method that overrides the abstract method
            Assert.AreEqual(1, mixer.MethodsToImplement.Count());
            // only one method from the mixin should be implemented, the other one
            // is alredy implemented by childs base
            Assert.AreEqual(1, mixer.MethodsToImplement.Count(x => x.Name == "Work"));
            Assert.IsTrue(mixer.MethodsToImplement.Single().IsOverride);
        }
Ejemplo n.º 58
0
        public void ChildHasBaseClassWithBaseClassesWithProperty_Include_PropertyNotReimplemented()
        {
            // arrange
            var sourceCode = new SourceCode(Files.Person, Files.Name);
            var personClass = sourceCode.Class(nameof(ThirdPersonClass));
            var mixinReference = personClass.FindMixinReference("_name");
            var semanticModel = sourceCode.Semantic;
            var mixin = new MixinReferenceFactory(semanticModel).Create(mixinReference);
            var child = new ClassFactory(semanticModel).Create(personClass);

            // act 
            var mixer = new Mixer();
            mixer.IncludeMixinInChild(mixin, child);

            // nothing to implement for the mixer, child already has property
            Assert.IsEmpty(mixer.PropertiesToImplement);
        }