Exemple #1
0
 /// <summary>
 /// 将Logic的数据写入到UnitParameter
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="up"></param>
 public void SetUnitParameter(FlowParameter ld, UnitParameter up)
 {
     foreach (var v in ld.Domain(DomainKey.INPUT_PARAMETER))
     {
         up.SetValue(v.Key, ComFunc.nvl(v.Value));
     }
 }
Exemple #2
0
    public UnitParameter Clone()
    {
        UnitParameter up = new UnitParameter();

        up.unit    = unit;
        up.enabled = enabled;
        up.minWave = minWave;

        up.minDelay    = minDelay;
        up.maxDelay    = maxDelay;
        up.minInterval = minInterval;
        up.maxInterval = maxInterval;

        up.minSpd       = minSpd;
        up.startSpd     = startSpd;
        up.spdIncrement = spdIncrement;
        up.spdDeviation = spdDeviation;

        up.minHP       = minHP;
        up.startHP     = startHP;
        up.HPIncrement = HPIncrement;
        up.HPDeviation = HPDeviation;

        up.minShd       = minShd;
        up.startShd     = startShd;
        up.shdIncrement = shdIncrement;
        up.shdDeviation = shdDeviation;

        up.startInterval = startInterval;
        up.intIncrement  = intIncrement;
        up.intModifier   = intModifier;
        up.intDeviation  = intDeviation;

        return(up);
    }
Exemple #3
0
        void addUserInfo(UnitParameter up, dynamic sql)
        {
            sql.sql = @"INSERT INTO [UserInfo]
           ([UserUID]
           ,[UserAccountNo]
           ,[UserMobile]
           ,[UserName]
           ,[UserSex]
           ,[UserRealName]
           ,[UserRealID]
           ,[UserType]
           ,[BelongToStore])
     VALUES
           (@UserUID
           ,@UserAccountNo
           ,@UserMobile
           ,@UserName
           ,@UserSex
           ,@UserRealName
           ,@UserRealID
           ,@UserType
           ,@BelongToStore)";

            if (ComFunc.nvl(up.GetValue("RecommededUID")) != "")
            {
                sql.sql += @"delete from Map_Recommend where UserUID=@UserUID and RecommededUID=@RecommededUID
insert into Map_Recommend(UserUID,RecommededUID)values(@UserUID,@RecommededUID)";
            }
        }
            protected void InitUPPage(UnitParameter p)
            {
                if (ComFunc.nvl(_logic.CallContext_Parameter[DomainKey.QUERY_STRING, ToPage_Key]) != "")
                {
                    p.ToPage = IntStd.ParseStd(_logic.CallContext_Parameter[DomainKey.QUERY_STRING, ToPage_Key]);
                }
                else if (ComFunc.nvl(_logic.CallContext_Parameter[DomainKey.POST_DATA, ToPage_Key]) != "")
                {
                    p.ToPage = IntStd.ParseStd(_logic.CallContext_Parameter[DomainKey.POST_DATA, ToPage_Key]);
                }
                else
                {
                    p.ToPage = 1;
                }
                if (p.ToPage <= 0)
                {
                    p.ToPage = 1;
                }

                if (ComFunc.nvl(_logic.CallContext_Parameter[DomainKey.QUERY_STRING, Count_per_Page_Key]) != "")
                {
                    p.Count_Of_OnePage = IntStd.ParseStd(_logic.CallContext_Parameter[DomainKey.QUERY_STRING, Count_per_Page_Key]);
                }
                else if (ComFunc.nvl(_logic.CallContext_Parameter[DomainKey.POST_DATA, Count_per_Page_Key]) != "")
                {
                    p.Count_Of_OnePage = IntStd.ParseStd(_logic.CallContext_Parameter[DomainKey.POST_DATA, Count_per_Page_Key]);
                }
                else
                {
                    p.Count_Of_OnePage = _logic.CallContext_Parameter[DomainKey.CONFIG, "Count_per_Page"] != null?IntStd.ParseStd(_logic.CallContext_Parameter[DomainKey.CONFIG, "Count_per_Page"]).Value : 10;
                }
            }
Exemple #5
0
            /// <summary>
            /// 创建Table
            /// </summary>
            /// <param name="up"></param>
            /// <param name="toTable"></param>
            /// <param name="columns"></param>
            public virtual void CreateTable(UnitParameter up, string toTable, params TableColumn[] columns)
            {
                if (columns == null || columns.Length <= 0)
                {
                    return;
                }
                FrameDLRObject express = FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'CreateTable',
$table : {0}
}", FrameDLRFlags.SensitiveCase, toTable);
                var            pk      = new List <object>();

                foreach (var c in columns)
                {
                    FrameDLRObject cobj = FrameDLRObject.CreateInstance(FrameDLRFlags.SensitiveCase);
                    cobj.SetValue("$datatype", c.DataType);
                    cobj.SetValue("$precision", c.Precision);
                    cobj.SetValue("$scale", c.Scale);
                    cobj.SetValue("$default", c.Default);
                    cobj.SetValue("$isnull", c.IsPK ? false : c.AllowNull);
                    if (c.IsPK)
                    {
                        pk.Add(c.Name);
                    }
                    express.SetValue(c.Name, cobj);
                }

                express.SetValue("$pk", pk);
                Excute(up, express);
            }
Exemple #6
0
 /// <summary>
 /// 将Logic的数据写入到UnitParameter
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="up"></param>
 public void SetUnitParameter(LogicData ld, UnitParameter up)
 {
     foreach (var val in ld)
     {
         up.SetValue(val.Key, val.Value);
     }
 }
 /// <summary>
 /// 将Logic的数据写入到UnitParameter
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="up"></param>
 public void SetUnitParameter(FlowLogicData ld, UnitParameter up)
 {
     foreach (var v in ld)
     {
         up.SetValue(v.Key, ComFunc.nvl(v.Value));
     }
 }
Exemple #8
0
            /// <summary>
            /// 创建一个默认的DB访问参数
            /// </summary>
            /// <returns></returns>
            public override UnitParameter NewDBUnitParameter()
            {
                var           dbtype = ComFunc.nvl(_logic.Configs["DB_Type"]);
                UnitParameter rtn    = null;

                if (dbtype.ToLower() == "sqlserver")
                {
                    rtn = base.NewDBUnitParameter <SQLServerAccess>();
                }
                else if (dbtype.ToLower() == "mysql")
                {
                    rtn = base.NewDBUnitParameter <MySQLAccess>();
                }
                else if (dbtype.ToLower() == "oracle")
                {
                    rtn = base.NewDBUnitParameter <OracleAccess>();
                }
                else if (dbtype.ToLower() == "sqlite")
                {
                    rtn = base.NewDBUnitParameter <SqliteAccess>();
                }
                InitUPPage(rtn);
                rtn.Dao.Open(_logic.CallContext_Parameter.DBConnectionString);
                return(rtn);
            }
Exemple #9
0
            public virtual void DeleteFromOracle(UnitParameter p, string tablename, FrameDLRObject obj)
            {
                StringBuilder sbsql = new StringBuilder();

                sbsql.Append("delete from " + tablename + " where 1=1 ");
                var values  = "";
                var columns = "";
                DBOParameterCollection dpc = new DBOParameterCollection();

                foreach (var s in obj.Keys)
                {
                    var pkey = s.Replace("(", "").Replace(")", "").Replace("'", "").Replace("\"", "").Replace("[", "").Replace("]", "").Replace(".", "");
                    dpc.SetValue(pkey, obj.GetValue(s));
                    sbsql.Append(string.Format(" and {0}=:{0}", pkey));
                }
                if (p.Dao == null)
                {
                    p.Dao = _logic.CallContext_ResourceManage.CreateInstance <OracleAccess>(p.CurrentTransToken);
                    p.Dao.Open(ComFunc.nvl(_logic.Configs[ParameterKey.DBCONNECT_STRING]));
                }
                //目前只支持关系型数据库
                if (p.Dao is ADBAccess)
                {
                    ((ADBAccess)p.Dao).ExecuteNoQuery(sbsql.ToString(), dpc);
                }
            }
 /// <summary>
 /// 将Logic的数据写入到UnitParameter
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="up"></param>
 public void SetUnitParameter(FlowLogicData ld, UnitParameter up, string domain)
 {
     foreach (var v in ld.Domain(domain))
     {
         up.SetValue(v.Key, ComFunc.nvl(v.Value));
     }
 }
Exemple #11
0
            public virtual void InsertIntoOracle(UnitParameter p, string tablename, FrameDLRObject obj)
            {
                StringBuilder sbsql = new StringBuilder();

                sbsql.Append("insert into " + tablename + "(");
                var values  = "";
                var columns = "";
                DBOParameterCollection dpc = new DBOParameterCollection();

                foreach (var s in obj.Keys)
                {
                    var pkey = s.Replace("(", "").Replace(")", "").Replace("'", "").Replace("\"", "").Replace("[", "").Replace("]", "").Replace(".", "");
                    dpc.SetValue(pkey, obj.GetValue(s));
                    columns += columns.Length > 0 ? "," + s : s;
                    values  += values.Length > 0 ? ",:" + pkey : ":" + pkey;
                }
                sbsql.Append(columns + ")values(");
                sbsql.Append(values);
                sbsql.Append(");");

                if (p.Dao == null)
                {
                    p.Dao = _logic.CallContext_ResourceManage.CreateInstance <OracleAccess>(p.CurrentTransToken);
                    p.Dao.Open(ComFunc.nvl(_logic.Configs[ParameterKey.DBCONNECT_STRING]));
                }
                //目前只支持关系型数据库
                if (p.Dao is ADBAccess)
                {
                    ((ADBAccess)p.Dao).ExecuteNoQuery(sbsql.ToString(), dpc);
                }
            }
Exemple #12
0
            /// <summary>
            /// 标准化DB执行操作
            /// </summary>
            /// <param name="p"></param>
            /// <param name="express"></param>
            /// <returns></returns>
            public virtual UnitDataCollection Excute(UnitParameter p, DBExpress express)
            {
                UnitDataCollection rtn = new UnitDataCollection();

                if (express != null)
                {
                    p.SetValue("__json__", express);
                    if (p.Dao is ADBAccess)
                    {
                        if (express.CurrentAct == DBExpress.ActType.Query)
                        {
                            rtn = Query <JsonExpressUnit>(p, "");
                        }
                        else if (express.CurrentAct == DBExpress.ActType.QueryByPage)
                        {
                            rtn = QueryByPage <JsonExpressUnit>(p, "");
                        }
                        else
                        {
                            NonQuery <JsonExpressUnit>(p, "");
                        }
                    }
                    else if (p.Dao is MongoAccess26)
                    {
                        var result = ((MongoAccess26)p.Dao).Excute(express);
                        if (express.CurrentAct == DBExpress.ActType.Query)
                        {
                            rtn.MongoListData = (List <FrameDLRObject>)result;
                        }
                    }
                }
                return(rtn);
            }
Exemple #13
0
 /// <summary>
 /// 将Logic的数据写入到UnitParameter
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="up"></param>
 public void SetUnitParameter(LogicData ld, UnitParameter up, string domain)
 {
     foreach (var val in ld.Domain(domain))
     {
         up.SetValue(val.Key, val.Value);
     }
 }
Exemple #14
0
        void QueryUserList(UnitParameter up, dynamic sql)
        {
            sql.sql = @"select a.*,c.CodeText as StoreName,
d.UserUID as RecommendUID,e.[UserAccountNo] as RecommendAccountNo,
e.[UserMobile] as recommendMobile, e.[UserName] as RecommendName,f.CodeText as RecommededStoreName
from [UserInfo] a
left join CodeDictionary c on c.CodeValue=a.BelongToStore
join [Map_Recommend] d on a.UserUID=d.UserUID
join [UserInfo] e on e.UserUID=d.[RecommededUID] 
left join CodeDictionary f on f.CodeValue=e.BelongToStore";

            var where = "";
            if (ComFunc.nvl(up.GetValue("UserID")) != "")
            {
                where += "(a.UserMobile like '%'+@UserID+'%' or a.UserAccountNo like '%'+@UserID+'%')";
            }
            if (ComFunc.nvl(up.GetValue("RecommendedID")) != "")
            {
                where += (where == ""?"":" and ") + "(e.UserMobile like '%'+@RecommendedID+'%' or e.UserAccountNo like '%'+@RecommendedID+'%')";
            }

            where = where == "" ? "" : " where " + where;

            sql.sql += where;
        }
            /// <summary>
            /// 获得一个新的UnitParamter,默认Dao为DB类型的DBAccess
            /// </summary>
            /// <typeparam name="DB"></typeparam>
            /// <returns></returns>
            public UnitParameter NewDBUnitParameter <DB>() where DB : ADBAccess, IResourceEntity
            {
                UnitParameter _up = NewUnitParameter <UnitParameter>();

                _up.Dao          = _driver._p.Resources.CreateInstance <DB>(_driver._p.CurrentTransToken);
                _up.DBConnString = ComFunc.nvl(_driver._p[DomainKey.CONFIG, ParameterKey.DBCONNECT_STRING]);
                return(_up);
            }
Exemple #16
0
            /// <summary>
            /// 获得一个新的UnitParamter,默认Dao为DB类型的DBAccess
            /// </summary>
            /// <typeparam name="DB"></typeparam>
            /// <returns></returns>
            public UnitParameter NewDBUnitParameter <DB>() where DB : IDBAccessInfo, ITransaction, IResourceEntity
            {
                UnitParameter _up = NewUnitParameter <UnitParameter>();

                _up.Dao          = _logic.CallContext_ResourceManage.CreateInstance <DB>(_logic.CallContext_CurrentToken);
                _up.DBConnString = ComFunc.nvl(_logic.CallContext_Parameter[DomainKey.CONFIG, ParameterKey.DBCONNECT_STRING]);
                return(_up);
            }
Exemple #17
0
            public override UnitDataCollection Excute(UnitParameter p, DBExpress express, bool islog = false)
            {
                if (express.CurrentAct == DBExpress.ActType.QueryByPage)
                {
                    InitUPPage(p);
                }

                return(base.Excute(p, express));
            }
Exemple #18
0
        void functiontree(UnitParameter up, dynamic sql)
        {
            sql.sql = @"SELECT 
case when ifnull(c.RoleUID,'')<> '' then 1 else 0 end as ischecked, 
d.* from FunctionInfo d
left join Map_RoleFunction c on d.FunctionNo=c.FunctionNo and c.RoleUID=$roleuid
order by FunctionNo;
";
        }
Exemple #19
0
            /// <summary>
            /// 直接删除Table
            /// </summary>
            /// <param name="up"></param>
            /// <param name="toTable"></param>
            public virtual void DropTable(UnitParameter up, string toTable)
            {
                FrameDLRObject express = FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'DropTable',
$table : {0}
}", FrameDLRFlags.SensitiveCase, toTable);

                Excute(up, express);
            }
        private string NewUserID(UnitParameter up)
        {
            var s = from t in DB.LamdaTable(up, "user_info", "a")
                    where t.userid.startwith(DateTime.Now.ToString("yyyyMMdd"))
                    select t;
            var maxid = Int64Std.IsNotInt64Then(s.Max(up, "userid"), Int64Std.ParseStd(DateTime.Now.ToString("yyyyMMdd") + "00000").Value);

            return((maxid + 1).ToString());
        }
Exemple #21
0
            /// <summary>
            /// 直接调用DB驱动执行大数据量新增操作
            /// 并非所有的数据库引擎支持大数据量的新增操作,具体请看相关操作说明
            /// </summary>
            /// <param name="p"></param>
            /// <param name="toTable"></param>
            /// <param name="data"></param>
            /// <returns></returns>
            public virtual UnitDataCollection BulkInsert(UnitParameter p, string toTable, object data)
            {
                var rtn = new UnitDataCollection();

                if (p.Dao != null && p.Dao is ADBAccess)
                {
                    ((ADBAccess)p.Dao).Insert(data, toTable);
                }
                return(rtn);
            }
Exemple #22
0
        void userinfo(UnitParameter up, dynamic sql)
        {
            sql.sql = @"select a.*,c.CodeText as StoreName,
d.UserUID as RecommendUID,e.[UserAccountNo] as RecommendAccountNo,e.[UserMobile] as recommendMobile, e.[UserName] as RecommendName
from [UserInfo] a
left join CodeDictionary c on c.CodeValue=a.BelongToStore
left join [Map_Recommend] d on a.UserUID=d.[RecommededUID]
left join [UserInfo] e on e.UserUID=d.UserUID
where (a.UserUID=@id or a.UserMobile=@id or a.UserAccountNo=@id)";
        }
Exemple #23
0
            public override UnitDataCollection QueryByPage <T>(UnitParameter p, string actionflag)
            {
                InitUPPage(p);
                UnitDataCollection rtn = base.QueryByPage <T>(p, actionflag);

                _logic.CallContext_DataCollection.WebData.SetValue(Count_per_Page_Key, rtn.Count_Of_OnePage);
                _logic.CallContext_DataCollection.WebData.SetValue(CurrentPage_Key, rtn.CurrentPage);
                _logic.CallContext_DataCollection.WebData.SetValue(Total_Page_Key, rtn.TotalPage);
                _logic.CallContext_DataCollection.WebData.SetValue(Total_Row_Key, rtn.TotalRow);
                return(rtn);
            }
 public override int CompareTo(UnitParameter other)
 {
     if (other is UnitRedeclareParameter)
     {
         return this._impl.Name.CompareTo((other as UnitRedeclareParameter)._impl.Name);
     }
     else
     {
         return this._impl.Name.CompareTo(other.Name);
     }
 }
Exemple #25
0
            /// <summary>
            /// Copy Table
            /// </summary>
            /// <param name="up"></param>
            /// <param name="from_table"></param>
            /// <param name="to_Table"></param>
            /// <param name="with_data"></param>
            /// <param name="is_log">是否记录log</param>
            public virtual void CopyTable(UnitParameter up, string from_table, string to_Table, bool with_data = false, bool is_log = false)
            {
                FrameDLRObject express = FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'CopyTable',
$table : {0},
$to_table:{1},
$with_data:{2}
}", FrameDLRFlags.SensitiveCase, from_table, to_Table, with_data);

                Excute(up, express, is_log);
            }
Exemple #26
0
 /// <summary>
 /// 获取一个Lamdatable对象,可以进行lamda2sql的操作,通过up自动识别db类型
 /// </summary>
 /// <param name="up"></param>
 /// <param name="tablename"></param>
 /// <param name="alianname"></param>
 /// <returns></returns>
 public virtual LinqDLRTable LamdaTable(UnitParameter up, string tablename, string alianname = "")
 {
     if (up.Dao is ADBAccess)
     {
         var rtn = ((ADBAccess)up.Dao).NewLinqTable(tablename, alianname);
         return(rtn);
     }
     else
     {
         return(null);
     }
 }
Exemple #27
0
 /// <summary>
 /// 判断一个table是否已经存在
 /// </summary>
 /// <param name="up"></param>
 /// <param name="tablename"></param>
 /// <returns></returns>
 public bool IsTableExists(UnitParameter up, string tablename)
 {
     try
     {
         var i = (from t in LamdaTable(up, tablename, "a") where new LinqDLR2SqlWhereOperator("1=0", null) select t).Take(1).Count(up);
         return(true);
     }
     catch (SqlException ex)
     {
         return(false);
     }
 }
Exemple #28
0
        void loginInfo(UnitParameter up, dynamic sql)
        {
            sql.sql = @"SELECT c.* from LoginInfo a
join Map_LoginRole b on a.UID=b.LoginUID
join RoleInfo c on b.RoleUID=c.RoleUID
where a.LoginID=$LoginID;

SELECT distinct d.* from LoginInfo a
join Map_LoginRole b on a.UID=b.LoginUID
join Map_RoleFunction c on b.RoleUID=c.RoleUID
join FunctionInfo d on c.FunctionNo=d.FunctionNo
where a.LoginID=$LoginID and d.IsMenu=1;";
        }
        /// <summary>
        /// 通过json对象执行标准化DB操作
        /// </summary>
        /// <param name="p"></param>
        /// <param name="json"></param>
        /// <param name="islog">用于设定是否记录解析结果,以便进行debug操作</param>
        /// <returns></returns>
        public static UnitDataCollection Excute(UnitParameter p, FrameDLRObject json, bool islog = false)
        {
            DBExpress express = null;

            if (p.Dao is ADBAccess)
            {
                express = ((ADBAccess)p.Dao).MyDBExpress;
                DBExpress.Load(express, json);
            }
            express.IsLog = islog;

            return(Excute(p, express));
        }
Exemple #30
0
            /// <summary>
            /// 快速执行建议Delete操作
            /// </summary>
            /// <param name="p"></param>
            /// <param name="toTable"></param>
            /// <param name="where"></param>
            /// <param name="islog"></param>
            /// <returns></returns>
            public virtual UnitDataCollection QuickDelete(UnitParameter p, string toTable, object where, bool islog = false)
            {
                FrameDLRObject express      = FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'Delete',
$table : {0}
}", toTable);
                FrameDLRObject whereexpress = FrameDLRObject.CreateInstance(where);

                if (whereexpress != null && whereexpress.Items.Count > 0)
                {
                    express.SetValue("$where", whereexpress);
                }
                return(Excute(p, express));
            }
Exemple #31
0
        void sample_queryByPage(UnitParameter up, dynamic sql)
        {
            if (ComFunc.nvl(up.GetValue("prod_code_custs")) == "")
            {
                sql.sql = @"select a.* from hw_po_line a join hw_po b on a.hw_contract_no=b.hw_contract_no where a.quantity>ifnull(a.freeze_quantity,0)+ifnull(a.used_quantity,0) and b.status='Signed' and b.is_valid_ebs=1 ";
            }
            else
            {
                sql.presql = @"call PROCEDURE_split(@prod_code_custs,',');";
                sql.sql    = @"select a.* from hw_po_line a join hw_po b on a.hw_contract_no=b.hw_contract_no where a.quantity>ifnull(a.freeze_quantity,0)+ifnull(a.used_quantity,0) and b.status='Signed' and b.is_valid_ebs=1 and a.prod_code_cust in (select * from splittable)";
            }

            sql.orderby = @"hw_contract_no,po_line_no";
        }
        /// <summary>
        /// Get the expression encapsulated in the UnitParameter for a parameter that gets its value from outside its model.
        /// </summary>
        /// <param name="parentID">ID of parent of the model that contains the parameter.</param>
        /// <param name="parameter">CyPhyParameter to which the returned UnitParameter will be correspond to.</param>
        /// <param name="vf">Incoming value-flow to parameter.</param>
        /// <returns>Value-expression in UnitParameter.</returns>
        private UnitParameter GetArgumentParameter(string parentID, CyPhy.Parameter parameter, CyPhy.ValueFlow vf)
        {
            ModelicaValue modelicaValue = null;
            if (vf.SrcEnds.Parameter != null)
            {
                var srcParameter = vf.SrcEnds.Parameter;
                if (this.ParentContainerIsDynamic(srcParameter))
                {
                    var parameterName = this.ParentIsComponent(srcParameter) ? ParameterPrefix + srcParameter.Name : srcParameter.Name;

                    // The Parameter is in a subModel (prepend instance name of the subModel).
                    if (srcParameter.ParentContainer.ID != parentID)
                    {
                        parameterName = string.Format("{0}.{1}", srcParameter.ParentContainer.Name, parameterName);
                    }

                    modelicaValue = new ModelicaValue(parameterName);
                }
                else
                {
                    modelicaValue = new ModelicaValue(srcParameter.Attributes.Value);
                }
            }
            else if (vf.SrcEnds.SimpleFormula != null)
            {
                modelicaValue = new ModelicaValue(this.GetFormulaExpression(vf.SrcEnds.SimpleFormula));
            }
            else if (vf.SrcEnds.Property != null)
            {
                modelicaValue = new ModelicaValue(vf.SrcEnds.Property.Attributes.Value);
            }
            else if (vf.SrcEnds.CustomFormula != null)
            {
                modelicaValue = new ModelicaValue(parameter.Attributes.Value);
            }

            var parameter_mo = new UnitParameter()
            {
                Name = this.ParentIsComponent(parameter) ? ParameterPrefix + parameter.Name : parameter.Name,
                Value = modelicaValue
            };

            return parameter_mo;
        }
        /// <summary>
        /// Builds up all components (through AddComponent), connectors (through AddConnector/AddModelicaConnector)
        /// and inner component assemblies (and calls this function recursively on such), for componentAssembly_mo.
        /// </summary>
        /// <param name="componentAssembly_mo">ComponentAssembly to start from.</param>
        /// <param name="parentComponentAssembly_mo">If the callee was a component assembly -> the callee.</param>
        private void BuildUpComponentAssembly(ComponentAssembly componentAssembly_mo, ComponentAssembly parentComponentAssembly_mo)
        {
            var ca = componentAssembly_mo.Impl;

            // ------- Parameters/Properties & Metrics ---------
            foreach (var defParameter in ca.Children.ParameterCollection)
            {
                // META-3622
                if (String.IsNullOrWhiteSpace(defParameter.Attributes.Dimension) || defParameter.Attributes.Dimension.Trim() == "1")
                {
                    var parameter_mo = new UnitParameter()
                    {
                        Name = defParameter.Name,
                        Value = this.GetParameterModelicaValue(defParameter),
                        Modifier = this.GetParameterModifier(defParameter)
                    };

                    componentAssembly_mo.Parameters.Add(parameter_mo);
                }
            }

            foreach (var defProperty in ca.Children.PropertyCollection)
            {
                // META-3622
                if (String.IsNullOrWhiteSpace(defProperty.Attributes.Dimension) || defProperty.Attributes.Dimension.Trim() == "1")
                {
                    var parameter_mo = new UnitParameter()
                    {
                        Name = defProperty.Name,
                        Value = this.GetPropertyModelicaValue(defProperty, true)
                    };

                    componentAssembly_mo.Parameters.Add(parameter_mo);
                }
            }

            foreach (var metric in ca.Children.MetricCollection)
            {
                var metric_mo = new Metric()
                {
                    Name = metric.Name,
                    Description = metric.Attributes.Description,
                };

                componentAssembly_mo.Metrics.Add(metric_mo);
            }

            // ------- ComponentAssemblies -------
            foreach (var innerComponentAssembly in ca.Children.ComponentAssemblyCollection)
            {
                if (this.ContainsDynamicComponents(innerComponentAssembly) == false)
                {
                    this.Logger.WriteWarning(
                        "Component Assembly '{0}' inside '{1}' does not contain any dynamic models, it will not be generated.", 
                        innerComponentAssembly.Name,
                        ca.Name);
                    continue;
                }

                var innerCAFullName = componentAssembly_mo.FullName.Substring(0, componentAssembly_mo.FullName.LastIndexOf('.'));

                bool innerCAHasChildren = innerComponentAssembly.Children.ComponentAssemblyCollection.Count() > 0;
                if (innerCAHasChildren)
                {
                    innerCAFullName += "." + innerComponentAssembly.Name;
                }

                innerCAFullName += "." + innerComponentAssembly.Name;

                var innerComponentAssembly_mo = new ComponentAssembly(innerComponentAssembly)
                {
                    FullName = innerCAFullName,
                    ParentComponentAssembly = componentAssembly_mo,
                    HasInnerCAs = innerCAHasChildren,
                    ConstrainedBys = this.modelicaSettings.GenerateConstrainedBys
                };

                this.testBench_mo.ComponentAssemblies.Add(innerComponentAssembly_mo);

                // Make sure there are margins to the upper- and left-border
                int canvasX = innerComponentAssembly.GenericAspect.X > ScaleFactor * 3 * ComponentIconSize ? innerComponentAssembly.GenericAspect.X : ScaleFactor * 3 * ComponentIconSize;
                int canvasY = innerComponentAssembly.GenericAspect.Y > ScaleFactor * 2 * ComponentIconSize ? innerComponentAssembly.GenericAspect.Y : ScaleFactor * 2 * ComponentIconSize;

                // Make sure there are margins to the bottom- and right-border
                componentAssembly_mo.CanvasXMax = canvasX + (ScaleFactor * 3 * ComponentIconSize) > componentAssembly_mo.CanvasXMax ? canvasX + (ScaleFactor * 3 * ComponentIconSize) : componentAssembly_mo.CanvasXMax;
                componentAssembly_mo.CanvasYMax = canvasY + (ScaleFactor * 2 * ComponentIconSize) > componentAssembly_mo.CanvasYMax ? canvasY + (ScaleFactor * 2 * ComponentIconSize) : componentAssembly_mo.CanvasYMax;

                var innerComponentAssemblyInstance_mo = new ComponentAssemblyInstance(innerComponentAssembly)
                {
                    InstanceOf = innerComponentAssembly_mo,
                    CanvasX = canvasX,
                    CanvasY = canvasY
                };

                foreach (var parameter in innerComponentAssembly.Children.ParameterCollection)
                {
                    var vf = parameter.SrcConnections.ValueFlowCollection.FirstOrDefault();
                    if (vf != null && vf.ParentContainer.ID == ca.ID)
                    {
                        var parameter_mo = this.GetArgumentParameter(ca.ID, parameter, vf);
                        innerComponentAssemblyInstance_mo.Parameters.Add(parameter_mo);
                    }
                }

                componentAssembly_mo.ComponentAssemblyInstances.Add(innerComponentAssemblyInstance_mo);

                string componentAssemblyInstanceURI = componentAssembly_mo.Name + "." + innerComponentAssemblyInstance_mo.Name;
                var parentCA = parentComponentAssembly_mo;
                while (parentCA != null)
                {
                    componentAssemblyInstanceURI = parentCA.Name + "." + componentAssemblyInstanceURI;
                    parentCA = parentCA.ParentComponentAssembly;
                }

                var componentAssemblyInfo = new ComponentInfo(innerComponentAssembly.Impl as GME.MGA.IMgaFCO, "PlantAssembly", this.traceability);

                this.instanceURIMap.Add(string.Format("{0}.TestBenches.{1}.{2}", MainPackage, this.testBench_mo.Name, componentAssemblyInstanceURI), componentAssemblyInfo);
                this.modelURIMap.Add(innerComponentAssembly_mo.FullName, componentAssemblyInfo);

                this.BuildUpComponentAssembly(innerComponentAssembly_mo, componentAssembly_mo);
            }

            // ------- Components -------
            foreach (var component in ca.Children.ComponentCollection)
            {
                if (this.ComponentIsDynamic(component) == false)
                {
                    this.Logger.WriteWarning(
                        "Component '{0}' inside '{1}' does not contain any dynamic models, it will not be generated.",
                        component.Name,
                        ca.Name);
                    continue;
                }

                if (this.treeComponents.ContainsKey(component.DerivedFrom().ID) == false)
                {
                    this.Logger.WriteDebug(
                        "Component-instance {0}, does not have a generated component. Probably since the component does not have a ModelicaModel.",
                        component.Name);
                    continue;
                }

                this.AddComponent(componentAssembly_mo, parentComponentAssembly_mo, component);
            }

            // ------- ModelicaConnectors -------
            foreach (var connector in ca.Children.ModelicaConnectorCollection)
            {
                this.AddModelicaConnector(componentAssembly_mo, parentComponentAssembly_mo, connector);
            }

            // ------- Connectors -------
            foreach (var connectorContainer in ca.Children.ConnectorCollection)
            {
                if (connectorContainer.Children.ModelicaConnectorCollection.Count() != 1)
                {
                    continue;
                }

                this.AddConnector(componentAssembly_mo, parentComponentAssembly_mo, connectorContainer);
            }
        }
        /// <summary>
        /// Adds TestComponent and instance to test-bench. Populates all mapping related to the TestComponent.
        /// </summary>
        /// <param name="testComponent">CyPhy TestComponent.</param>
        /// <param name="modelicaModel">CyPhy ModelicaModel of the testComponent.</param>
        private void AddTestComponent(CyPhy.TestComponent testComponent, CyPhy.ModelicaModel modelicaModel)
        {
            Modelica.Component testComponent_mo = null;

            // META-1624 : TestComponents in the test-bench are all seen as self-contained models 
            //             and will be generated as they appear there inside the Modelica package-tree.
            testComponent_mo = new Component(testComponent)
            {
                FullName = MainPackage + ".TestComponents." + testComponent.Name,
                Extends = modelicaModel.Attributes.Class,
            };

            // Add all defined Parameters at the component-level
            foreach (var cyPhyParameter in testComponent.Children.ParameterCollection)
            {
                var parameter_mo = new UnitParameter()
                {
                    Name = CodeGenerator.ParameterPrefix + cyPhyParameter.Name,
                    Value = this.GetParameterModelicaValue(cyPhyParameter),
                    Modifier = this.GetParameterModifier(cyPhyParameter)
                };

                testComponent_mo.CyPhyParameters.Add(parameter_mo);
            }

            // Add all modelicaParameters from the ModelicaModel.
            foreach (var parameter in modelicaModel.Children.ModelicaParameterCollection)
            {
                var value = this.GetModelicaParameterValue(parameter);
                if (string.IsNullOrWhiteSpace(value) == false)
                {
                    testComponent_mo.Parameters.Add(
                        new UnitParameter()
                        {
                            Name = parameter.Name,
                            Value = new ModelicaValue(value)
                        });
                }
            }

            // Add all modelicaRedeclares from the ModelicaModel.
            foreach (var redeclareParameter in modelicaModel.Children.ModelicaRedeclareCollection)
            {
                var value = redeclareParameter.Attributes.Value;

                if (string.IsNullOrWhiteSpace(value) == false)
                {
                    testComponent_mo.Parameters.Add(
                        new UnitRedeclareParameter(redeclareParameter)
                        {
                            Value = new ModelicaValue(value)
                        });
                }
            }

            this.testBench_mo.TestComponents.Add(testComponent_mo);

            // Make sure there are margins to the upper- and left-border
            int canvasX = testComponent.GenericAspect.X > ScaleFactor * ComponentIconSize ? 
                testComponent.GenericAspect.X : ScaleFactor * ComponentIconSize;
            int canvasY = testComponent.GenericAspect.Y > ScaleFactor * ComponentIconSize ? 
                testComponent.GenericAspect.Y : ScaleFactor * ComponentIconSize;

            // Make sure there are margins to the bottom- and right-border
            this.testBench_mo.CanvasXMax = canvasX + (ScaleFactor * ComponentIconSize) > this.testBench_mo.CanvasXMax ? 
                canvasX + (ScaleFactor * ComponentIconSize) : this.testBench_mo.CanvasXMax;
            this.testBench_mo.CanvasYMax = canvasY + (ScaleFactor * ComponentIconSize) > this.testBench_mo.CanvasYMax ? 
                canvasY + (ScaleFactor * ComponentIconSize) : this.testBench_mo.CanvasYMax;

            var testComponentInstance_mo = new ComponentInstance(testComponent)
            {
                InstanceOf = testComponent_mo,
                CanvasX = canvasX,
                CanvasY = canvasY
            };

            var testComponentInfo = new ComponentInfo(testComponent.Impl as GME.MGA.IMgaFCO, "ContextModel", this.traceability);
            this.instanceURIMap.Add(string.Format("{0}.TestBenches.{1}.{2}", MainPackage, this.testBench_mo.Name, testComponent.Name), testComponentInfo);
            var uri = MainPackage + ".TestComponents." + testComponent.Name;
            if (this.modelURIMap.ContainsKey(uri) == false)
            {
                this.modelURIMap.Add(uri, testComponentInfo);
            }

            if (this.extendsURIMap.ContainsKey(testComponent_mo.Extends) == false)
            {
                var testComponentExtendInfo = new ComponentInfo(modelicaModel.Impl as GME.MGA.IMgaFCO, "ContextModel", this.traceability);
                this.extendsURIMap.Add(testComponent_mo.Extends, testComponentExtendInfo);
            }

            // Parameters of instance
            foreach (var parameter in testComponent.Children.ParameterCollection)
            {
                var vf = parameter.SrcConnections.ValueFlowCollection.FirstOrDefault();
                if (vf != null && vf.ParentContainer.ID == this.testBench_mo.Impl.ID)
                {
                    var parameter_mo = this.GetArgumentParameter(this.testBench_mo.Impl.ID, parameter, vf);
                    testComponentInstance_mo.Parameters.Add(parameter_mo);
                }
            }

            this.testBench_mo.TestComponentInstances.Add(testComponentInstance_mo);

            // ModelicaConnectors
            foreach (var port in testComponent.Children.ModelicaConnectorCollection)
            {
                foreach (var dstPort in port.DstConnections.PortCompositionCollection
                    .Select(c => c.DstEnds.ModelicaConnector)
                    .Where(p => p.ParentContainer is CyPhy.ModelicaModel == false))
                {
                    CyPhy.ModelicaConnector srcConnector = this.GetModelicaModelConnectorFromComponentPort(port);
                    if (srcConnector == null)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector dstConnector = null;

                    if (dstPort.ParentContainer is CyPhy.TestComponent)
                    {
                        dstConnector = this.GetModelicaModelConnectorFromComponentPort(dstPort);
                    }
                    else if (dstPort.ParentContainer is CyPhy.ComponentAssembly)
                    {
                        dstConnector = dstPort;
                    }
                    else if (dstPort.ParentContainer is CyPhy.Environment)
                    {
                        dstConnector = dstPort;
                    }

                    // The Fidelty Selected might not have this Connection - don't make it.
                    // Or it might be a floating connector with no purpose.
                    if (dstConnector == null)
                    {
                        continue;
                    }

                    var connection_mo = new Connection(srcConnector.Name, dstConnector.Name)
                    {
                        SrcInstanceName = testComponent.Name,
                        DstInstanceName = dstPort.ParentContainer.Name,
                        Type = srcConnector.Attributes.Class
                    };

                    this.testBench_mo.Connections.Add(connection_mo);
                }
            }

            // Connectors - aka portContainers
            foreach (var portContainer in testComponent.Children.ConnectorCollection)
            {
                if (portContainer.Children.ModelicaConnectorCollection.Count() != 1)
                {
                    continue;
                }

                foreach (var dstPortContainer in portContainer.DstConnections.ConnectorCompositionCollection.Select(c => c.DstEnds.Connector))
                {
                    if (dstPortContainer.Children.ModelicaConnectorCollection.Count() != 1)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector srcConnector = this.GetModelicaModelConnectorFromComponentPortContainer(portContainer);
                    if (srcConnector == null)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector dstConnector = null;

                    string dstConnectorName = "ERROR No Name Assigned";

                    if (dstPortContainer.ParentContainer is CyPhy.TestComponent)
                    {
                        dstConnector = this.GetModelicaModelConnectorFromComponentPortContainer(dstPortContainer);
                        dstConnectorName = dstConnector.Name;
                    }
                    else if (dstPortContainer.ParentContainer is CyPhy.ComponentAssembly)
                    {
                        dstConnector = dstPortContainer.Children.ModelicaConnectorCollection.FirstOrDefault();
                        dstConnectorName = dstPortContainer.Name.Replace(' ', '_');
                    }
                    else if (dstPortContainer.ParentContainer is CyPhy.Environment)
                    {
                        this.Logger.WriteDebug("Environment connected in Connector-chains not supported!");
                        continue;
                    }

                    // The Fidelty Selected might not have this Connection - don't make it.
                    // Or it might be a floating connector with no purpose.
                    if (dstConnector == null)
                    {
                        continue;
                    }

                    var connection_mo = new Connection(srcConnector.Name, dstConnectorName)
                    {
                        SrcInstanceName = testComponent.Name,
                        DstInstanceName = dstPortContainer.ParentContainer.Name,
                        Type = srcConnector.Attributes.Class
                    };

                    this.testBench_mo.Connections.Add(connection_mo);
                }
            }
        }
        /// <summary>
        /// Does most of the work for GenerateModelicaCode()
        /// </summary>
        private void BuildUpTestBench()
        {
            var testBench = this.testBench_mo.Impl;
            this.instanceURIMap.Add(
                string.Format("{0}.TestBenches.{1}", MainPackage, testBench.Name),
                new ComponentInfo(testBench.Impl as GME.MGA.IMgaFCO, "ContextAssembly", this.traceability));

            // ------- Parameters/Properties & Metrics ---------
            foreach (var defParameter in testBench.Children.ParameterCollection)
            {
                var parameter_mo = new UnitParameter()
                {
                    Name = defParameter.Name,
                    Value = this.GetParameterModelicaValue(defParameter),
                    Modifier = this.GetParameterModifier(defParameter)
                };

                this.testBench_mo.Parameters.Add(parameter_mo);
            }

            foreach (var defProperty in testBench.Children.PropertyCollection)
            {
                var parameter_mo = new UnitParameter()
                {
                    Name = defProperty.Name,
                    Value = this.GetPropertyModelicaValue(defProperty, true)
                };

                this.testBench_mo.Parameters.Add(parameter_mo);
            }

            foreach (var metric in testBench.Children.MetricCollection)
            {
                var metric_mo = new Metric()
                {
                    Name = metric.Name,
                    Description = metric.Attributes.Description,
                };

                if (metric.SrcConnections.PPOutput2MetricCollection.Count() == 1)
                {
                    metric_mo.PostProcessing = true;
                }

                this.testBench_mo.Metrics.Add(metric_mo);
            }

            var ca = testBench.Children.ComponentAssemblyCollection.FirstOrDefault();
            var componentAssemblyFullName = string.Format("{0}.ComponentAssemblies.{1}", MainPackage, ca.Name);
            var hasInnerCAs = ca.Children.ComponentAssemblyCollection.Count() > 0;
            if (hasInnerCAs)
            {
                componentAssemblyFullName += "." + ca.Name;
            }

            var componentAssembly_mo = new ComponentAssembly(ca)
            {
                FullName = componentAssemblyFullName,
                HasInnerCAs = hasInnerCAs,
                ConstrainedBys = this.modelicaSettings.GenerateConstrainedBys
            };

            this.testBench_mo.ComponentAssemblies.Add(componentAssembly_mo);

            // Make sure there are margins to the upper- and left-border
            int canvasX = ca.GenericAspect.X > ScaleFactor * 3 * ComponentIconSize ? ca.GenericAspect.X : ScaleFactor * 3 * ComponentIconSize;
            int canvasY = ca.GenericAspect.Y > ScaleFactor * 2 * ComponentIconSize ? ca.GenericAspect.Y : ScaleFactor * 2 * ComponentIconSize;

            // Make sure there are margins to the bottom- and right-border
            this.testBench_mo.CanvasXMax = canvasX + (ScaleFactor * 3 * ComponentIconSize);
            this.testBench_mo.CanvasYMax = canvasY + (ScaleFactor * 2 * ComponentIconSize);

            var componentAssemblyInstance_mo = new ComponentAssemblyInstance(ca)
            {
                InstanceOf = componentAssembly_mo,
                CanvasX = canvasX,
                CanvasY = canvasY
            };

            foreach (var parameter in ca.Children.ParameterCollection)
            {
                var vf = parameter.SrcConnections.ValueFlowCollection.FirstOrDefault();

                // The Value flow is in the TestBench (if in the CA it's dealt with of the definition of the Parameter)
                if (vf != null && vf.ParentContainer.ID == testBench.ID)
                {
                    var parameter_mo = this.GetArgumentParameter(testBench.ID, parameter, vf);

                    componentAssemblyInstance_mo.Parameters.Add(parameter_mo);
                }
            }

            var componentAssemblyInfo = new ComponentInfo(ca.Impl as GME.MGA.IMgaFCO, "PlantAssembly", this.traceability);
            this.instanceURIMap.Add(string.Format("{0}.TestBenches.{1}.{2}", MainPackage, this.testBench_mo.Name, ca.Name), componentAssemblyInfo);
            this.modelURIMap.Add(string.Format("{0}.ComponentAssemblies.{1}.{1}", MainPackage, ca.Name), componentAssemblyInfo);

            this.testBench_mo.ComponentAssemblyInstances.Add(componentAssemblyInstance_mo);

            // ---------- SystemUnderTest (ComponentAssembly)-------
            this.BuildUpComponentAssembly(componentAssembly_mo, null);

            // ----------- TestComponents ----------
            foreach (var testComponent in testBench.Children.TestComponentCollection)
            {
                var modelicaModel = testComponent.Children.ModelicaModelCollection.FirstOrDefault();
                if (modelicaModel == null)
                {
                    continue;
                }

                this.AddTestComponent(testComponent, modelicaModel);
            }

            // -------- Environments ------
            foreach (var environment in testBench.Children.EnvironmentCollection)
            {
                this.AddEnvironment(environment);
                this.instanceURIMap.Add(
                string.Format("{0}.TestBenches.{1}.{2}", MainPackage, testBench.Name, environment.Name),
                    new ComponentInfo(environment.Impl as GME.MGA.IMgaFCO, "Environment", this.traceability));
            }
        }
        /// <summary>
        /// Recursive call for BuildUpAllComponents
        /// </summary>
        /// <param name="folder">Folder at the current depth.</param>
        /// <param name="package_mo">modelica package at the current depth</param>
        /// <param name="lvl">depth (used for indentation).</param>
        private void BuildUpAllComponentsRec(FolderTreeNode folder, Package package_mo, int lvl = 1)
        {
            foreach (var component in folder.Children.OfType<ComponentTreeNode>().Select(c => c.Component))
            {
                var isInDesign = string.IsNullOrEmpty((component.Impl as GME.MGA.IMgaFCO).RegistryNode["IsInDesign"].Value) == false;

                if (isInDesign == false && this.GenerateUnusedComponents == false)
                {
                    continue;
                }

                var modelicaModel = this.GetModelicaModelFromComponent(component);
                if (modelicaModel == null)
                {
                    continue;
                }

                // Don't check the rules twice for components in the design
                if (isInDesign == false)
                {
                    if (this.CheckRulesOnComponent(component, modelicaModel) == false)
                    {
                        this.Logger.WriteDebug("Component, {0}, will not be generated in package.", component.Name);
                        continue;
                    }
                }

                var component_mo = new Component(component)
                {
                    FullName = package_mo.FullName + "." + component.Name,
                    Extends = modelicaModel.Attributes.Class
                };

                // Add all defined Parameters at the component-level
                foreach (var cyPhyParameter in component.Children.ParameterCollection)
                {
                    // META-3622
                    if (String.IsNullOrWhiteSpace(cyPhyParameter.Attributes.Dimension) || cyPhyParameter.Attributes.Dimension.Trim() == "1")
                    {
                        var parameter_mo = new UnitParameter()
                        {
                            Name = CodeGenerator.ParameterPrefix + cyPhyParameter.Name,
                            Value = this.GetParameterModelicaValue(cyPhyParameter),
                            Modifier = this.GetParameterModifier(cyPhyParameter)
                        };

                        component_mo.CyPhyParameters.Add(parameter_mo);
                    }
                }

                // Add all modelicaParameter from the ModelicaModel
                foreach (var parameter in modelicaModel.Children.ModelicaParameterCollection)
                {
                    var value = this.GetModelicaParameterValue(parameter, true);
                    if (string.IsNullOrWhiteSpace(value) == false)
                    {
                        component_mo.Parameters.Add(
                            new UnitParameter()
                            {
                                Name = parameter.Name,
                                Value = new ModelicaValue(value)
                            });
                    }
                }

                // Add all modelicaRedeclares from the ModelicaModel
                foreach (var redeclareParameter in modelicaModel.Children.ModelicaRedeclareCollection)
                {
                    var value = redeclareParameter.Attributes.Value;

                    if (string.IsNullOrWhiteSpace(value) == false)
                    {
                        component_mo.Parameters.Add(
                            new UnitRedeclareParameter(redeclareParameter)
                            {
                                Value = new ModelicaValue(value)
                            });
                    }
                }

                this.treeComponents.Add(component.ID, component_mo);
                package_mo.Models.Add(component_mo);
            }

            lvl += 1;
            foreach (var subFolder in folder.Children.OfType<FolderTreeNode>())
            {
                var subPackage_mo = new Package
                {
                    Name = subFolder.Name,
                    FullName = package_mo.FullName + "." + subFolder.Name,
                    IndentLevel = lvl,
                };

                package_mo.Children.Add(subPackage_mo);
                this.BuildUpAllComponentsRec(subFolder as FolderTreeNode, subPackage_mo, lvl);
            }
        }
        /// <summary>
        /// Adds the component to componentAssembly_mo as an instance.
        /// </summary>
        /// <param name="componentAssembly_mo">ComponentAssembly that contains the component.</param>
        /// <param name="parentComponentAssembly_mo">ComponentAssembly that contains componentAssembly_mo.</param>
        /// <param name="component">CyPhy Component to add.</param>
        private void AddComponent(ComponentAssembly componentAssembly_mo, ComponentAssembly parentComponentAssembly_mo, CyPhy.Component component)
        {
            var ca = componentAssembly_mo.Impl;
            var modelicaModel = this.GetModelicaModelFromComponent(component);

            // Make sure there are margins to the top- and left-border
            int canvasX = component.GenericAspect.X > ScaleFactor * ComponentIconSize ? 
                component.GenericAspect.X : ScaleFactor * ComponentIconSize;
            int canvasY = component.GenericAspect.Y > ScaleFactor * ComponentIconSize ? 
                component.GenericAspect.Y : ScaleFactor * ComponentIconSize;

            // Make sure there are margins to the bottom- and right-border
            componentAssembly_mo.CanvasXMax = canvasX + (ScaleFactor * ComponentIconSize) > componentAssembly_mo.CanvasXMax ? 
                canvasX + (ScaleFactor * ComponentIconSize) : componentAssembly_mo.CanvasXMax;
            componentAssembly_mo.CanvasYMax = canvasY + (ScaleFactor * ComponentIconSize) > componentAssembly_mo.CanvasYMax ? 
                canvasY + (ScaleFactor * ComponentIconSize) : componentAssembly_mo.CanvasYMax;

            var componentInstance_mo = new ComponentInstance(component)
            {
                InstanceOf = this.treeComponents[component.DerivedFrom().ID],
                CanvasX = canvasX,
                CanvasY = canvasY
            };

            foreach (var parameter in component.Children.ParameterCollection)
            {
                // META-3622
                if (String.IsNullOrWhiteSpace(parameter.Attributes.Dimension) || parameter.Attributes.Dimension.Trim() == "1")
                {
                    var vf = parameter.SrcConnections.ValueFlowCollection.FirstOrDefault();
                    if (vf != null && vf.ParentContainer.ID == ca.ID)
                    {
                        var parameter_mo = this.GetArgumentParameter(ca.ID, parameter, vf);
                        componentInstance_mo.Parameters.Add(parameter_mo);
                    }
                }
            }

            // META-2189 Overwrite ModelicaParameters connected to properties with formulated values in the design.
            foreach (var modelicaParameter in modelicaModel.Children.ModelicaParameterCollection)
            {
                var connection = modelicaParameter.SrcConnections.ModelicaParameterPortMapCollection.FirstOrDefault();
                if (connection != null && connection.SrcEnds.Property != null)
                {
                    double temp;
                    var value = modelicaParameter.Attributes.Value.Trim();
                    if (double.TryParse(modelicaParameter.Attributes.Value, out temp) || value == "true" || value == "false" || 
                        (value.StartsWith("\"") && value.EndsWith("\"")))
                    {
                        var parameter_mo = new UnitParameter();
                        parameter_mo.Name = modelicaParameter.Name;
                        parameter_mo.Value = new ModelicaValue(modelicaParameter.Attributes.Value.Trim());
                        componentInstance_mo.Parameters.Add(parameter_mo);
                    }
                }
            }

            componentAssembly_mo.ComponentInstances.Add(componentInstance_mo);

            string componentModelicaURI = componentAssembly_mo.Name + "." + componentInstance_mo.Name;
            var parentCA = parentComponentAssembly_mo;
            while (parentCA != null)
            {
                componentModelicaURI = parentCA.Name + "." + componentModelicaURI;
                parentCA = parentCA.ParentComponentAssembly;
            }

            this.ExtractPCCInputs(component, componentModelicaURI);


            string modelType;
            if (modelicaModel is CyPhy.CyberModel)
            {
                modelType = "ControllerModel";
            }
            else
            {
                modelType = "PlantModel";
            }

            var componentInfo = new ComponentInfo(component.Impl as GME.MGA.IMgaFCO, modelType, this.traceability);
            this.instanceURIMap.Add(string.Format("{0}.TestBenches.{1}.{2}", MainPackage, this.testBench_mo.Name, componentModelicaURI), componentInfo);
            if (this.modelURIMap.ContainsKey(componentInstance_mo.InstanceOf.FullName) == false)
            {
                this.modelURIMap.Add(componentInstance_mo.InstanceOf.FullName, componentInfo);
            }

            if (this.extendsURIMap.ContainsKey(componentInstance_mo.InstanceOf.Extends) == false)
            {
                var componentExtendInfo = new ComponentInfo(modelicaModel.Impl as GME.MGA.IMgaFCO, modelType, this.traceability);
                this.extendsURIMap.Add(componentInstance_mo.InstanceOf.Extends, componentExtendInfo);
            }

            // Iterate over all ports and look for connections FROM the port. These connections will generate equations in the 
            // component assembly if the connections is not entering a ModelicaModel.

            // Connections from ModelicaConnectors (Components)
            foreach (var port in component.Children.ModelicaConnectorCollection)
            {
                foreach (var dstPort in port.DstConnections.PortCompositionCollection
                    .Select(c => c.DstEnds.ModelicaConnector)
                    .Where(p => p.ParentContainer is CyPhy.ModelicaModel == false))
                {
                    CyPhy.ModelicaConnector srcConnector = this.GetModelicaModelConnectorFromComponentPort(port);
                    if (srcConnector == null)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector dstConnector = null;

                    if (dstPort.ParentContainer is CyPhy.Component)
                    {
                        dstConnector = this.GetModelicaModelConnectorFromComponentPort(dstPort);
                    }
                    else if (dstPort.ParentContainer is CyPhy.ComponentAssembly)
                    {
                        dstConnector = dstPort;
                    }

                    // The Fidelty Selected might not have this Connection - don't make it.
                    // Or it might be a floating connector with no purpose.
                    if (dstConnector == null)
                    {
                        continue;
                    }

                    var connection_mo = new Connection(srcConnector.Name, dstConnector.Name)
                    {
                        SrcInstanceName = component.Name,
                        Type = srcConnector.Attributes.Class
                    };

                    if (dstPort.ParentContainer.ID != ca.ID)
                    {
                        connection_mo.DstInstanceName = dstPort.ParentContainer.Name;
                    }

                    componentAssembly_mo.Connections.Add(connection_mo);
                }
            }

            // Connections from Connectors (Components)
            foreach (var portContainer in component.Children.ConnectorCollection)
            {
                if (portContainer.Children.ModelicaConnectorCollection.Count() != 1)
                {
                    continue;
                }

                foreach (var dstPortContainer in portContainer.DstConnections.ConnectorCompositionCollection.Select(c => c.DstEnds.Connector))
                {
                    if (dstPortContainer.Children.ModelicaConnectorCollection.Count() != 1)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector srcConnector = this.GetModelicaModelConnectorFromComponentPortContainer(portContainer);
                    if (srcConnector == null)
                    {
                        continue;
                    }

                    CyPhy.ModelicaConnector dstConnector = null;

                    string dstConnectorName = "ERROR No Name Assigned";
                    if (dstPortContainer.ParentContainer is CyPhy.Component)
                    {
                        var portComponent = CyPhyClasses.Component.Cast(dstPortContainer.ParentContainer.Impl);
                        if (this.ComponentIsDynamic(portComponent) == false)
                        {
                            this.Logger.WriteWarning("'{0}' does not contain any dynamic-components, connections to it skipped.", portComponent.Name);
                            continue;
                        }

                        dstConnector = this.GetModelicaModelConnectorFromComponentPortContainer(dstPortContainer);
                        if (dstConnector != null)
                        {
                            dstConnectorName = dstConnector.Name;
                        }
                    }
                    else if (dstPortContainer.ParentContainer is CyPhy.ComponentAssembly)
                    {
                        var portCA = dstPortContainer.ParentContainer.Impl;
                        if (this.ContainsDynamicComponents(CyPhyClasses.ComponentAssembly.Cast(portCA)) == false)
                        {
                            this.Logger.WriteWarning("'{0}' does not contain any dynamic-components, connections to it skipped.", portCA.Name);
                            continue;
                        }

                        dstConnector = dstPortContainer.Children.ModelicaConnectorCollection.FirstOrDefault();
                        dstConnectorName = dstPortContainer.Name.Replace(' ', '_');
                    }

                    // The Fidelty Selected might not have this Connection - don't make it.
                    // Or it might be a floating connector with no purpose.
                    if (dstConnector == null)
                    {
                        continue;
                    }

                    var connection_mo = new Connection(srcConnector.Name, dstConnectorName)
                    {
                        SrcInstanceName = component.Name,
                        Type = srcConnector.Attributes.Class
                    };

                    if (dstPortContainer.ParentContainer.ID != ca.ID)
                    {
                        connection_mo.DstInstanceName = dstPortContainer.ParentContainer.Name;
                    }

                    componentAssembly_mo.Connections.Add(connection_mo);
                }
            }

            // Add limit-checks for the component to the test-bench
            foreach (var modelicaModelLimit in modelicaModel.Children.LimitCheckCollection)
            {
                // TODO: When META-1124 and META-1129 both are merged, merge Limit and LimitCheck class.
                var limit = new Limit(modelicaModelLimit)
                {
                    ComponentModelicaUri = componentModelicaURI
                };
                this.testBench_mo.Limits.Add(limit);
                var limitCheck = new LimitCheck()
                {
                    ParentKind = modelicaModelLimit.ParentContainer.Kind,
                    LimitFullPath = modelicaModelLimit.Path,
                    LimitName = modelicaModelLimit.Name,
                    VariableName = modelicaModelLimit.Attributes.VariableName,
                    Type = modelicaModelLimit.Attributes.LimitType.ToString(),
                    Value = modelicaModelLimit.Attributes.Value,
                    VariableFullPath = string.Format("{0}.{1}", componentModelicaURI, modelicaModelLimit.Attributes.VariableName),
                    ModelicaRecordName = string.Format("Limit{0}", this.testBench_mo.Limits.Count)
                };

                this.LimitDefintion.LimitChecks.Add(limitCheck);

            }
        }