示例#1
0
        public static void Run()
        {
            var site = new Site {
            };
            var mode = new ModelDefine
                       (
                new Selector(".//div[@class='result']"),
                new[]
            {
                new Field("Keyword", "Keyword", SelectorType.Enviroment),
                new Field(".//h3[@class='c-title']/a", "Title"),
                new Field(".//h3[@class='c-title']/a/@href", "Url"),
                new Field(".//div/p[@class='c-author']/text()", "Website"),
                new Field(".//div/span/a[@class='c-cache']/@href", "Snapshot"),
                new Field(".//div[@class='c-summary c-row ']", "Details"),
                new Field(".", "PlainText"),
                new Field("today", "atime", SelectorType.Enviroment, DataType.Date)
            }
                , new TableInfo("baidu", "search"), null);
            var processor = new ModelProcessor(mode);
            var spider    = Spider.Create(site, processor);
            var word      = "可乐|雪碧";

            spider.AddStartUrl(string.Format("http://news.baidu.com/ns?word={0}&tn=news&from=news&cl=2&pn=0&rn=20&ct=1", word), new Dictionary <string, dynamic> {
                { "Keyword", word }
            });
            spider.AddPipeline(new MySqlEntityPipeline());
            spider.Run();
        }
示例#2
0
        private void MergeFiles(IEnumerable <string> relativeNames, string srcDir, string destDir,
                                bool onlyIfNotExists)
        {
            foreach (var relativeName in relativeNames)
            {
                FileInfo input = new FileInfo(Path.Combine(srcDir, relativeName));
                FileInfo output;

                if (onlyIfNotExists)
                {
                    output = new FileInfo(Path.Combine(destDir, relativeName));
                }
                else
                {
                    output = new FileInfo(Path.Combine(destDir, relativeName.Split('\\').Last()));
                }

                if (onlyIfNotExists && output.Exists && !ModelProcessor.IsMarkedToOverride(output.FullName))
                {
                    continue;
                }

                Directory.CreateDirectory(output.Directory.FullName);

                File.WriteAllText(output.FullName, File.ReadAllText(input.FullName));
            }
        }
示例#3
0
文件: Program.cs 项目: tudway/Codge
        static Model LoadModel(IReadOnlyCollection <string> paths, string modelName, ILogger logger)
        {
            var model = new ModelLoader(logger).LoadModel(paths, modelName);

            var typeSystem = new TypeSystem();
            var compiler   = new ModelProcessor(new LoggerFactory());

            return(compiler.Compile(typeSystem, model));
        }
示例#4
0
        private static int Main(string[] args)
        {
            ComputeTemplatePath();

            bool          overrideFile = false;
            List <string> files        = new List <string>();

            foreach (var arg in args)
            {
                if (IsOverrideArg(arg))
                {
                    overrideFile = true;
                }
                else
                {
                    FileInfo xml = new FileInfo(arg);
                    if (!xml.Exists)
                    {
                        Console.WriteLine("File not found: " + xml.FullName);
                        return(-1);
                    }
                    files.Add(arg);
                }
            }

            if (files.Count < 1)
            {
                Console.WriteLine("Model# "
                                  + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                Console.WriteLine("");
                Console.WriteLine("Use:");
                Console.WriteLine("    ModelSharp [-override] <model.ms>");
                return(1);
            }

            int ret = 0;

            foreach (var file in files)
            {
                var modelProcessor = new ModelProcessor(templatesPath, file, overrideFile);
                modelProcessor.Logger = new Logger();

                var result = modelProcessor.Process();
                if (!result.Success)
                {
                    ret = -1;
                }
            }

            if (ret != 0)
            {
                Console.WriteLine("Finished with error(s)");
            }
            return(ret);
        }
示例#5
0
 public AddChildToAMaleThrowsException()
 {
     _modelProcessor = GivenASampleTree();
     try
     {
         WhenAChildIsAddedToAMale();
     }
     catch (Exception e)
     {
         _exception = e;
     }
 }
 public UnknownPersonQueryThrowsException()
 {
     _modelProcessor = GivenASampleTree();
     try
     {
         WhenARelationshipForAnUnknownPersonIsQueried();
     }
     catch (Exception e)
     {
         _exception = e;
     }
 }
示例#7
0
        static void Main(string[] args)
        {
            const string tnameTest = "Test6 Tenant";
            const string mnameTest = "Test6 Model";

            using (var ctxTarget = new ModelMateEFModel9Context())
            {
                ctxTarget.Database.Log = Console.Write;
                Console.WriteLine("LazyLoadingEnabled: " + ctxTarget.Configuration.LazyLoadingEnabled.ToString());
                //ctx.Configuration.LazyLoadingEnabled = false;
                //Console.WriteLine("LazyLoadingEnabled: " + ctx.Configuration.LazyLoadingEnabled.ToString());

                ModelMigrator.PreloadAllTables(ctxTarget);

                var tTarget = ModelFinder.FindTenant(ctxTarget, null, tnameTest);
                //var tenants = ModelFinder.FindTenants(ctx, null, tnameTest);
                //var tenant = tenants.ElementAt<tenant>(0);
                Console.WriteLine("tenant.identifier: " + tTarget.identifier);

                var models  = ModelFinder.FindModels(ctxTarget, tTarget, null, mnameTest);
                var mTarget = models.ElementAt <model>(0);
                Console.WriteLine("model.identifier: " + mTarget.identifier);
                var model0 = ModelFinder.FindModel(ctxTarget, tTarget, null, mnameTest);
                Console.WriteLine("model0.identifier: " + model0.identifier);

                string  modelSchemaFile = @"..\..\..\PSN.ModelMate.Schema\Schema\ModelMateModel9.xsd";
                DataSet dsModel         = new DataSet();
                dsModel.ReadXmlSchema(modelSchemaFile);
                dsModel.Tables["element"].MinimumCapacity      = ctxTarget.element.Count();
                dsModel.Tables["properties"].MinimumCapacity   = ctxTarget.properties.Count();
                dsModel.Tables["property"].MinimumCapacity     = ctxTarget.property.Count();
                dsModel.Tables["value"].MinimumCapacity        = ctxTarget.value.Count();
                dsModel.Tables["relationship"].MinimumCapacity = ctxTarget.relationship.Count();

                var mmpModel = new ModelProcessor(ModelProcessor.ConvertModel2AMEFFDataSet);
                mmpModel.ProcessModel(dsModel, (DbContext)ctxTarget, new Collection <model> {
                    model0
                });
                //dsModel.WriteXml("model0ds.xml", XmlWriteMode.IgnoreSchema);
                string filename = "model7archi.xml";
                mmpModel.SaveAMEFFDataSetAsXML(dsModel, filename);

                ctxTarget.SaveChanges();
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
示例#8
0
        public static void Run()
        {
            Instance instance = Instance.LoadFrom("sohu.xml");

            var table  = new TableInfo("websites", "html");
            var fields = new[]
            {
                new FieldSelector(".//title", "title"),
                new FieldSelector(Env.UrlPropertyKey, "url", SelectorType.Enviroment),
                new FieldSelector(".//body", "content", SelectorType.XPath, DataType.String, int.MaxValue),
                new FieldSelector("is_match", "is_match", SelectorType.XPath, DataType.Bool),
                new FieldSelector("matchs", "matchs", SelectorType.XPath, DataType.String, int.MaxValue),
                new FieldSelector("id", "id", SelectorType.Enviroment, DataType.Int)
                {
                    IsPrimary = true
                },
            };
            var targetRequestSelector = new TargetRequestSelector
            {
                XPaths          = instance.TargetXpaths,
                Patterns        = instance.TargetPatterns,
                ExcludePatterns = instance.ExcludePatterns
            };
            var model         = new ModelDefinition(null, fields, table, targetRequestSelector);
            var modeProcessor = new ModelProcessor(model);

            modeProcessor.CleanPound = true;
            modeProcessor.AddDataHanlder(new MyDataHandler());
            var site = new Site {
                EncodingName = instance.Encording
            };

            site.AddRequests(instance.Url);
            Spider spider = Spider.Create(site,
                                          new QueueDuplicateRemovedScheduler(),
                                          modeProcessor)
                            .AddPipeline(new MySqlEntityPipeline());

            if (instance.Downloader.ToLower() == "chrome")
            {
                spider.Downloader = new WebDriverDownloader(Browser.Chrome, new Option {
                    Headless = true
                });
            }

            spider.Run();
        }
示例#9
0
        static void Main(string[] args)
        {
            const string tTargetName       = "Tenant 2 Test";
            string       tTargetIdentifier = Util.MakeIdentifierRootIdentifier(typeof(tenant).Name, Util.TrimWhitespace(tTargetName));

            const string mTargetName       = "Model 2 Test";
            string       mTargetIdentifier = Util.MakeIdentifierFromParentIdentifier(
                Util.MakeIdentifierRootIdentifier(typeof(tenant).Name, tTargetName),
                typeof(model).Name, Util.TrimWhitespace(mTargetName));

            tenant tTarget = null;
            model  mTarget = null;

            using (var ctxTarget = new ModelMateEFModel9Context())
            {
                ctxTarget.Database.Log = Console.Write;

                tTarget = ModelFinder.FindTenant(ctxTarget, tTargetIdentifier, "");
                ModelDump.DisplayDBPropertyValues("tTarget", ctxTarget.Entry(tTarget).CurrentValues, null);

                folders fs0 = tTarget.folders.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("fs0", ctxTarget.Entry(fs0).CurrentValues, null);
                folder f0 = fs0.folder.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("f0", ctxTarget.Entry(f0).CurrentValues, null);

                mTarget = ModelFinder.FindModel(ctxTarget, tTarget, mTargetIdentifier, null);
                ModelDump.DisplayDBPropertyValues("mTarget", ctxTarget.Entry(mTarget).CurrentValues, null);

                string  modelSchemaFile = @"..\..\..\PSN.ModelMate.Schema\Schema\ModelMateModel9.xsd";
                DataSet dsModel         = new DataSet();
                dsModel.ReadXmlSchema(modelSchemaFile);
                //DataSet ds3 = dsModel.Copy();
                //var mmpModel = new ModelMateProcessor();
                var mmpModel = new ModelProcessor(ModelProcessor.ConvertModel2AMEFFDataSet);
                mmpModel.ProcessModel(dsModel, (DbContext)ctxTarget, new Collection <model> {
                    mTarget
                });
                //dsModel.WriteXml("modelds.xml", XmlWriteMode.IgnoreSchema);
                string filename = "model4archi.xml";
                mmpModel.SaveAMEFFDataSetAsXML(dsModel, filename);

                Console.WriteLine("Press Enter to exit...");
                Console.ReadLine();
            }
        }
示例#10
0
    private static void FormatModel()
    {
        List <ModelImporter> modelImporters = new List <ModelImporter>();
        var objs = Selection.objects;

        foreach (var o in objs)
        {
            string path = AssetDatabase.GetAssetPath(o);
            modelImporters.AddRange(GetImporterByPath <ModelImporter>(path));
        }
        List <TextureImporter> textureImporters = new List <TextureImporter>();

        foreach (var o in objs)
        {
            string path = AssetDatabase.GetAssetPath(o);
            textureImporters.AddRange(GetImporterByPath <TextureImporter>(path));
        }
        int   totalCount = modelImporters.Count + textureImporters.Count;
        float index      = 0;

        foreach (var modelImporter in modelImporters)
        {
            index++;
            EditorUtility.DisplayProgressBar("正在格式化资源", modelImporter.assetPath, index / totalCount);
            ModelProcessor.FormatModel(modelImporter);
        }

        foreach (var importer in textureImporters)
        {
            index++;
            EditorUtility.DisplayProgressBar("正在格式化资源", importer.assetPath, index / totalCount);
            TextureProcessor.FormatTexture(importer);
        }

        EditorUtility.ClearProgressBar();
    }
示例#11
0
        private void GenerateCode(object sender, GenerationEventArgs e)
        {
            e.OutputFileExtension = ".dot";

            string templatesDir = GetInstallPath("templates");

            if (!Directory.Exists(templatesDir))
            {
                e.GenerateError("Missing templates from install: " + templatesDir);
                return;
            }

            string libDll = GetInstallPath(GetInstallPath(@"lib\ModelSharp.Lib.dll"));

            if (!Directory.Exists(templatesDir))
            {
                e.GenerateError("Missing dll from install: " + libDll);
                return;
            }

            string tempFile = Path.GetTempFileName();
            string tempDir  = null;

            try
            {
                tempDir = Directory.CreateDirectory(tempFile + "_dir").FullName;

                var modelProcessor = new ModelProcessor(templatesDir, e.InputFilePath, true);
                modelProcessor.BaseOutputPath = tempDir;
                modelProcessor.GlobalConfig.ProjectNamespace = e.Namespace;

                var result = modelProcessor.Process();

                // Output to console
//				foreach (var msg in result.Messages)
//				{
//					string txt;
//					if (msg.Line > 0)
//						txt = String.Format("[{0}] [{1:0000} : {2:000}] {3}",
//						                                msg.Error ? "ERROR" : "INFO ", msg.Line, msg.Column,
//						                                msg.Description);
//					else
//						txt = String.Format("[{0}] {1}", msg.Error ? "ERROR" : "INFO ", msg.Description);
//
//					Console.WriteLine(txt);
//				}

                if (!result.Success)
                {
                    e.GenerateError("Error generating model");

                    foreach (var msg in result.Messages)
                    {
                        if (msg.Error)
                        {
                            if (msg.Line > 0)
                            {
                                e.GenerateError(msg.Description, msg.Line - 1, msg.Column);
                            }
                            else
                            {
                                e.GenerateError(msg.Description);
                            }
                        }
                    }
                    return;
                }

                //string filename = Path.Combine(tempDir, names.First());
                //foreach (var line in File.ReadLines(filename))
                //{
                //    e.OutputCode.AppendLine(line);
                //}

                string inputDir = new FileInfo(e.InputFilePath).DirectoryName;

                MergeFiles(result.NotToChangeFilenames, tempDir, inputDir, false);
                MergeFiles(result.EditableFilenames, tempDir, inputDir, true);

                SetSubItems(e, inputDir, result.NotToChangeFilenames);
                AddToProject(e, inputDir, result.EditableFilenames);

                EnsureDllIsInProject(e, libDll);
            }
            finally
            {
                if (tempDir != null)
                {
                    foreach (var file in Directory.GetFiles(tempDir))
                    {
                        if (file == "." || file == "..")
                        {
                            continue;
                        }

                        DeleteFile(Path.Combine(tempDir, file), e);
                    }

                    DeleteDir(tempDir, e);
                }

                DeleteFile(tempFile, e);
            }
        }
示例#12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString.Count != 0)
        {
            Response.Redirect("RunModel.aspx?" + Request.QueryString.ToString());
        }
        //Path Settings
        else
        {
            //W00ds1de337
            Response.Redirect("RunModel.aspx?CaseName=SAMPLE_TEST3&ClientKey=OilWebDemo17&ModelType=OILSPILL&StartDate=20170501T12:00:00&simLength=24&WaterTemp=72.6F&IncLat=33.856999&IncLon=-118.541794&Winds=390&Currents=765&EcopWinds=GFS_WINDS&EcopCurrents=HYCOM_global_Navy_currents&Duration=6&Location=WORLD&&Volume=1000&group=7f22adb83ed7431f824df84a41a7f038&every1share=true&OilType=Heavy%20Crude%20Oil&OilUnits=5&FullPath=true&scriptid=Model2Shape&description=test");
        }
        _sWebPath   = Path.GetDirectoryName(Server.MapPath("ModelRunMapPath.txt"));
        _OutputFile = "ERROR: an unknown error has occured in Page_Load";

        double timeout = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ProccessTimeout"]);

        //Parse the Query String
        string qsProcessed = processQueryString();

        if (qsProcessed != "")
        {
            Response.Write(qsProcessed);
            return;
        }

        if (!(Directory.Exists(_sWebPath + "\\ModelData\\LogFile")))
        {
            Directory.CreateDirectory(_sWebPath + "\\ModelData\\LogFile");
        }

        using (StreamWriter sw = new StreamWriter(_sWebPath + "\\ModelData\\LogFile\\LogFile.txt", true))
        {
            sw.WriteLine(String.Format("{0},{1},{2}", DateTime.Now.ToString(), HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], Request.QueryString.ToString()));
        }

        string sOutputPath = "\\ModelData\\" + _sLocation;

        CheckOutputPath(_sWebPath + sOutputPath);

        string sPrefixFile = _sWebPath + sOutputPath + "\\Winds\\Prefix.txt";

        if (File.Exists(sPrefixFile))
        {
            _sWindsPrefix = File.ReadAllText(sPrefixFile);  //System.Configuration.ConfigurationManager.AppSettings["WindFilePrefix"];
        }
        sPrefixFile = _sWebPath + sOutputPath + "\\Currents\\CurrentsPrefix.txt";
        if (File.Exists(sPrefixFile))
        {
            _sCurrentsPrefix = File.ReadAllText(sPrefixFile); //System.Configuration.ConfigurationManager.AppSettings["CurrentFilePrefix"];
        }
        //if (_bIsRivers)
        //{
        // sPrefixFile = _sWebPath + sOutputPath + "\\Currents\\RiverPrefix.txt";
        //if (File.Exists(sPrefixFile))
        //  _sCurrentsPrefix = File.ReadAllText(sPrefixFile); //System.Configuration.ConfigurationManager.AppSettings["RiverCurrentFilePrefix"];
        //}

        //Set up the aggregator
        EDSProcessor myProcessor = new EDSProcessor();

        string windsStat = "";

        if (_Winds == m_cLocal)
        {
            //Process the winds
            _AggEngine = new AggregatorEngine(_Winds, _StartDate, _EndDate, _AOI, _sWebPath, _sWebPath + sOutputPath + "\\WINDS\\", _bIsRivers);
            windsStat  = _AggEngine.getWinds(_sWindsPrefix, _FileName);
            if (windsStat.Contains("ERROR"))
            {
                Response.Write(windsStat + " WINDS");
                return;
            }
        }
        else if (_Winds == m_cConstant)
        {
            windsStat = _sWebPath + sOutputPath + "\\WINDS\\" + _FileName + ".WNE";
            CreateWNEFile(windsStat, _WindMag, _WindDir);
        }
        else if (_Winds != m_cNoData) //EDS Winds
        {
            string sFilename = myProcessor.GetDataFile(_ClientKey, _Winds, _StartDate, _EndDate, _AOI);
            string sResult   = myProcessor.GetStatus(sFilename);
            if (sResult == "COMPLETE")
            {
                string sOutFilename = _sWebPath + sOutputPath + "\\winds\\" + _FileName + ".NC";
                myProcessor.DownloadDataFile(sOutFilename, sFilename);
                windsStat = sFilename;
            }
            else
            {
                windsStat = sResult;
            }
        }

        _AggEngine = null;

        //Process the currents
        string currStat = "";

        if (_Currents == m_cLocal)
        {
            string currentsDataPath = _sWebPath;
            _AggEngine = new AggregatorEngine(_Currents, _StartDate, _EndDate, _AOI, _sWebPath, _sWebPath + sOutputPath + "\\Currents\\", _bIsRivers);
            currStat   = _AggEngine.getCurrents(_sCurrentsPrefix, _FileName);
            if (currStat.Contains("ERROR"))
            {
                Response.Write(currStat + " CURRENTS");
                return;
            }
        }
        else if (_Currents == m_cConstant)
        {
            currStat = "";
        }
        else if (_Currents != m_cNoData)
        {
            string sFilename = myProcessor.GetDataFile(_ClientKey, _Currents, _StartDate, _EndDate, _AOI);
            string sResult   = myProcessor.GetStatus(sFilename);
            if (sResult == "COMPLETE")
            {
                string sOutFilename = _sWebPath + sOutputPath + "\\currents\\" + _FileName + ".NC";
                myProcessor.DownloadDataFile(sOutFilename, sFilename);
                currStat = sFilename;
            }
            else
            {
                currStat = sResult;
            }
        }

        //Run the model
        _ModelProcessor = new ModelProcessor(_eModelType, timeout);
        if (_eModelType == ModelType.OilModel)
        {
            OilInputData oilInput = new OilInputData(_sWebPath, _sLocation);
            oilInput.bBox          = _AOI;
            oilInput.caseName      = _sCaseName;
            oilInput.incidentSite  = _IncidentSite;
            oilInput.start         = _StartDate;
            oilInput.end           = _EndDate;
            oilInput.currentFile   = currStat;
            oilInput.windsFile     = windsStat;
            oilInput.ecopCurrents  = _EcopCurrents;
            oilInput.ecopWinds     = _EcopWinds;
            oilInput.fileName      = _FileName;
            oilInput.spillDuration = _Duration;
            oilInput.SpillAmount   = _SpillAmount;
            oilInput.SpillUnits    = _OilUnits;
            oilInput.WaterTemp     = _WaterTemp;
            oilInput.groupID       = _groupIDShare;
            oilInput.every1        = _ShareEveryone;

            if (_ModelMethod) //fast
            {
                oilInput.timeStep = 60;
            }
            else //comprehensive
            {
                oilInput.timeStep = 10;
            }

            if (_Currents == m_cConstant)
            {
                oilInput.CurrMag = _CurrMag;
                oilInput.CurrDir = _CurrDir;
            }
            else
            {
                oilInput.CurrMag = -999;
                oilInput.CurrDir = -999;
            }

            oilInput.oilType = _OilType;

            /*if ((_Currents > 0) || (_Winds > 0))
             * {
             *  oilInput.coastLineFile = Path.GetDirectoryName(oilInput.coastLineFile) + "\\LANDPOLY.BDM";
             * }*/
            _OutputFile = _ModelProcessor.runOilModel(oilInput);
        }

        if (_eModelType == ModelType.ChemModel)
        {
            ChemInputData chemInput = new ChemInputData(_sWebPath, _sLocation);
            chemInput.bBox          = _AOI;
            chemInput.caseName      = _sCaseName;
            chemInput.incidentSite  = _IncidentSite;
            chemInput.start         = _StartDate;
            chemInput.end           = _EndDate;
            chemInput.currentFile   = currStat;
            chemInput.windsFile     = windsStat;
            chemInput.fileName      = _FileName;
            chemInput.chemType      = _ChemType;
            chemInput.spillDuration = _Duration;
            chemInput.ModelMethod   = _ModelMethod;

            /*if ((_Currents > 0) || (_Winds > 0))
             *  chemInput.coastLineFile = Path.GetDirectoryName(chemInput.coastLineFile) + "\\LANDPOLY.BDM";*/
            _OutputFile = _ModelProcessor.runChemModel(chemInput);
        }

        //Rout the output to the user
        if (_OutputFile != "")
        {
            if (Request.QueryString["FullPath"] != null)
            {
                if (Request.QueryString["FullPath"] == "true")
                {
                    Response.Write("\\\\" + Environment.MachineName + "\\" + _sWebPath.Remove(0, 3) + sOutputPath + "\\Outdata\\" + _OutputFile + ".INP");
                }
                else
                {
                    Response.Write(_OutputFile);
                }
            }
            else
            {
                //Response.Write("\\\\" + Environment.MachineName + "\\" + _sWebPath.Remove(0, 3) + sOutputPath + "\\Outdata\\" + _OutputFile + ".INP");
                Response.Write(_OutputFile);
            }
        }
        else
        {
            Response.Write("ERROR: An error occurred while running the model.");
        }
    }
        protected override void DrawCore(RenderContext context)
        {
            modelProcessor = SceneInstance.GetCurrent(context).GetProcessor<ModelProcessor>();
            lightProcessor = SceneInstance.GetCurrent(context).GetProcessor<LightProcessor>();

            // No light processors means no light in the scene, so we can early exit
            if (lightProcessor == null || modelProcessor == null)
            {
                return;
            }

            // Not in the context of a SceneCameraRenderer? just exit
            sceneCameraRenderer = context.Tags.Get(SceneCameraRenderer.Current);
            sceneCamera = context.Tags.Get(CameraComponentRenderer.Current);
            if (sceneCameraRenderer == null || sceneCamera == null)
            {
                return;
            }
            sceneCullingMask = sceneCameraRenderer.CullingMask;

            // Setup the callback on the ModelRenderer and shadow map LightGroupRenderer
            if (!isModelComponentRendererSetup)
            {
                // TODO: Check if we could discover declared renderers in a better way than just hacking the tags of a component
                var modelRenderer = ModelComponentRenderer.GetAttached(sceneCameraRenderer);
                if (modelRenderer == null)
                {
                    return;
                }

                modelRenderer.Callbacks.PreRenderModel += PrepareRenderModelForRendering;
                modelRenderer.Callbacks.PreRenderMesh += PreRenderMesh;

                // TODO: Make this pluggable
                // TODO: Shadows should work on mobile platforms
                if (context.GraphicsDevice.Features.Profile >= GraphicsProfile.Level_10_0
                    && (Platform.Type == PlatformType.Windows || Platform.Type == PlatformType.WindowsStore || Platform.Type == PlatformType.Windows10))
                {
                    shadowMapRenderer = new ShadowMapRenderer(modelRenderer.EffectName);
                    shadowMapRenderer.Renderers.Add(typeof(LightDirectional), new LightDirectionalShadowMapRenderer());
                    shadowMapRenderer.Renderers.Add(typeof(LightSpot), new LightSpotShadowMapRenderer());
                }

                isModelComponentRendererSetup = true;
            }

            // Collect all visible lights
            CollectVisibleLights();

            // Draw shadow maps
            if (shadowMapRenderer != null)
                shadowMapRenderer.Draw(context, visibleLightsWithShadows);

            // Prepare active renderers in an ordered list (by type and shadow on/off)
            CollectActiveLightRenderers(context);

            currentModelLightShadersPermutationEntry = null;
            currentModelShadersParameters = null;
            currentShadowReceiver = true;

            // Clear the cache of parameter entries
            lightParameterEntries.Clear();
            parameterCollectionEntryPool.Clear();

            // Clear association between model and lights
            modelToLights.Clear();

            // Clear all data generated by shader entries
            foreach (var shaderEntry in shaderEntries)
            {
                shaderEntry.Value.ResetGroupDatas();
            }
        }
示例#14
0
        static void Main(string[] args)
        {
            const string tTargetName = "Test6 Tenant";
            const string mTargetName = "Test6 Model";

            string tSourceName = tTargetName;
            string mSourceName = mTargetName;

            //DirectoryInfo di = new DirectoryInfo(@"..\..\MyUsers4ModelMate");
            DirectoryInfo di = new DirectoryInfo(@"..\..\Test Assemblies");
            //DirectoryInfo di = new DirectoryInfo(@"..\..\Web Assemblies");

            string test1 = "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

            //"System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

            //"System.Collections.Generic.IDictionary`2<System.String,System.Data.Entity.Infrastructure.Annotations.AnnotationValues> System.Data.Entity.Migrations.Model.AlterTableOperation::_annotations";

            //"System.Collections.Generic.IDictionary`2<System.String,System.Data.Entity.Infrastructure.Annotations.AnnotationValues> System.Data.Entity.Migrations.Model.AlterTableOperation::_annotations";

            //"System.Data.Entity.DbSet`1<VetContext1.DataModel1.AnimalType>";

            string test1Namespace  = Cecil2ModelMate.GetNamespaceFromFQName(test1);
            string test1Name       = Cecil2ModelMate.GetNameFromFQName(test1);
            string test1ObjectType = Cecil2ModelMate.DetermineArchiMateObjectType(test1).ToString();

            Console.WriteLine("test1: " + test1);
            Console.WriteLine("test1Namespace: " + test1Namespace);
            Console.WriteLine("test1Name: " + test1Name);
            Console.WriteLine("test1ObjectType: " + test1ObjectType);
            test1ObjectType = Cecil2ModelMate.DetermineArchiMateObjectType(test1Name).ToString();
            Console.WriteLine("test1ObjectType: " + test1ObjectType);
            test1ObjectType = Cecil2ModelMate.DetermineArchiMateObjectType(test1Namespace).ToString();
            Console.WriteLine("test1ObjectType: " + test1ObjectType);

            //test1 = "a.b.c.d";
            //test1Name = Cecil2ModelMate.GetNameFromFQName(test1);
            //test1Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test1);
            //Console.WriteLine("test1: " + test1);
            //Console.WriteLine("test1Namespace: " + test1Namespace);
            //Console.WriteLine("test1Name: " + test1Name);

            //string test2 = "System.Data.Entity.DbSet`1<VetContext1.DataModel1.AnimalType>";
            //string test2Name = Cecil2ModelMate.DetermineArchiMateObjectType(test2).ToString();
            //Console.WriteLine("test2: " + test2);
            //Console.WriteLine("test2Name: " + test2Name);

            //test2 = "System.Data.Entity.DbSet`1";
            //test2Name = Cecil2ModelMate.DetermineArchiMateObjectType(test2).ToString();
            //Console.WriteLine("test2: " + test2);
            //Console.WriteLine("test2Name: " + test2Name);

            //string test3 = "System.Data.Entity.Infrastructure.Interception.MutableInterceptionContext`1<TResult>";
            //string test3Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test3);
            //string test3Name = Cecil2ModelMate.DetermineArchiMateInterfaceType(test3).ToString();
            //Console.WriteLine("test3: " + test3);
            //Console.WriteLine("test3Namespace: " + test3Namespace);
            //Console.WriteLine("test3Name: " + test3Name);

            //test3 = "System.Data";
            //test3Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test3);
            //test3Name = Cecil2ModelMate.DetermineArchiMateInterfaceType(test3).ToString();
            //Console.WriteLine("test3: " + test3);
            //Console.WriteLine("test3Namespace: " + test3Namespace);
            //Console.WriteLine("test3Name: " + test3Name);

            //test3 = "System";
            //test3Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test3);
            //test3Name = Cecil2ModelMate.DetermineArchiMateInterfaceType(test3).ToString();
            //Console.WriteLine("test3: " + test3);
            //Console.WriteLine("test3Namespace: " + test3Namespace);
            //Console.WriteLine("test3Name: " + test3Name);

            //test3 = "S";
            //test3Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test3);
            //test3Name = Cecil2ModelMate.DetermineArchiMateInterfaceType(test3).ToString();
            //Console.WriteLine("test3: " + test3);
            //Console.WriteLine("test3Namespace: " + test3Namespace);
            //Console.WriteLine("test3Name: " + test3Name);

            //test3 = "";
            //test3Namespace = Cecil2ModelMate.GetNamespaceFromFQName(test3);
            //test3Name = Cecil2ModelMate.DetermineArchiMateInterfaceType(test3).ToString();
            //Console.WriteLine("test3: " + test3);
            //Console.WriteLine("test3Namespace: " + test3Namespace);
            //Console.WriteLine("test3Name: " + test3Name);

            model mSource = Cecil2ModelMate.Migrate2ModelMate(tSourceName, mSourceName, di);

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();

            using (var ctxTarget = new ModelMateEFModel9Context())
            {
                //var oldLog = ctxTarget.Database.Log;
                //ctxTarget.Database.Log = Console.Write;

                Console.WriteLine("propertydefs.Count: " + ctxTarget.propertydefs.Local.Count().ToString());

                ModelMigrator.PreloadAllTables(ctxTarget);

                var tTarget = ModelFinder.FindTenant(ctxTarget, null, tTargetName);
                //var tenants = ModelFinder.FindTenants(ctxTarget, null, tnameTest);
                //var tenant = tenants.ElementAt<tenant>(0);
                Console.WriteLine("tenant.identifier: " + tTarget.identifier);

                folders fs0 = tTarget.folders.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("fs0", ctxTarget.Entry(fs0).CurrentValues, null);
                folder f0 = fs0.folder.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("f0", ctxTarget.Entry(f0).CurrentValues, null);

                var models  = ModelFinder.FindModels(ctxTarget, tTarget, null, mTargetName);
                var mTarget = models.ElementAt <model>(0);
                Console.WriteLine("model.identifier: " + mTarget.identifier);
                var model0 = ModelFinder.FindModel(ctxTarget, tTarget, null, mTargetName);
                Console.WriteLine("model0.identifier: " + model0.identifier);

                ModelMigrator.MigrateModel(ctxTarget, tTarget, f0,
                                           mSource, PCOOperation.merge, PCOOperation.merge, true);

                string  modelSchemaFile = @"..\..\..\PSN.ModelMate.Schema\Schema\ModelMateModel9.xsd";
                DataSet dsModel         = new DataSet();
                dsModel.ReadXmlSchema(modelSchemaFile);
                var mmpModel = new ModelProcessor(ModelProcessor.ConvertModel2AMEFFDataSet);
                mmpModel.ProcessModel(dsModel, (DbContext)ctxTarget, new Collection <model> {
                    model0
                });
                //dsModel.WriteXml("model0ds.xml", XmlWriteMode.IgnoreSchema);
                string filename = "model8archi.xml";
                mmpModel.SaveAMEFFDataSetAsXML(dsModel, filename);

                //ctxTarget.Database.Log = oldLog;
                ctxTarget.SaveChanges();
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
示例#15
0
        public void BasicMeshTests()
        {
            var input = CreateBasicMesh();

            var processorContext = new ProcessorContext(TargetPlatform.Windows, "dummy.xnb");
            var processor        = new ModelProcessor
            {
                RotationX = 10,
                RotationY = 20,
                RotationZ = 30
            };
            var output = processor.Process(input, processorContext);

            // The transform the processor above is applying to the model.
            var processorXform = Matrix.CreateRotationZ(MathHelper.ToRadians(30)) *
                                 Matrix.CreateRotationX(MathHelper.ToRadians(10)) *
                                 Matrix.CreateRotationY(MathHelper.ToRadians(20));

            // Test some basics.
            Assert.NotNull(output);
            Assert.NotNull(output.Meshes);
            Assert.AreEqual(2, output.Meshes.Count);
            Assert.NotNull(output.Bones);
            Assert.AreEqual(3, output.Bones.Count);
            Assert.NotNull(output.Root);
            Assert.AreEqual(output.Root, output.Bones[0]);

            // Stuff to make the tests below cleaner.
            var inputMesh1 = input.Children[0] as MeshContent;

            Assert.NotNull(inputMesh1);
            var inputMesh2 = input.Children[1] as MeshContent;

            Assert.NotNull(inputMesh2);

            // Test the bones.
            Assert.AreEqual("Root", output.Bones[0].Name);
            Assert.That(input.Transform, Is.EqualTo(output.Bones[0].Transform).Using(MatrixComparer.Epsilon));
            Assert.AreEqual("Mesh1", output.Bones[1].Name);
            Assert.That(Matrix.Identity, Is.EqualTo(output.Bones[1].Transform).Using(MatrixComparer.Epsilon));
            Assert.AreEqual("Mesh2", output.Bones[2].Name);
            Assert.That(Matrix.Identity, Is.EqualTo(output.Bones[2].Transform).Using(MatrixComparer.Epsilon));

            // Test the first mesh.
            {
                var mesh = output.Meshes[0];
                Assert.AreEqual("Mesh1", mesh.Name);
                Assert.AreEqual(output.Bones[1], mesh.ParentBone);
                Assert.AreEqual(inputMesh1, mesh.SourceMesh);
                Assert.AreEqual(new BoundingSphere(Vector3.Zero, 0), mesh.BoundingSphere);

                Assert.NotNull(mesh.MeshParts);
                Assert.AreEqual(1, mesh.MeshParts.Count);

                var part = mesh.MeshParts[0];
                Assert.NotNull(part);
                Assert.IsNull(part.IndexBuffer);
                Assert.IsNull(part.VertexBuffer);
                Assert.AreEqual(0, part.NumVertices);
                Assert.AreEqual(0, part.PrimitiveCount);
                Assert.AreEqual(0, part.StartIndex);
                Assert.AreEqual(0, part.VertexOffset);

                Assert.IsAssignableFrom <BasicMaterialContent>(part.Material);
                var material = part.Material as BasicMaterialContent;
                Assert.NotNull(material);
                Assert.IsNotEmpty(material.OpaqueData);
                Assert.IsNull(material.Name);
                Assert.IsNull(material.Identity);
                Assert.IsNull(material.Alpha);
                Assert.IsNull(material.DiffuseColor);
                Assert.IsNull(material.EmissiveColor);
                Assert.IsNull(material.SpecularColor);
                Assert.IsNull(material.SpecularPower);
                Assert.IsNull(material.Texture);
                Assert.IsEmpty(material.Textures);
                Assert.IsTrue(material.OpaqueData.ContainsKey("VertexColorEnabled"));
                Assert.IsNotNull(material.VertexColorEnabled);
                Assert.IsFalse(material.VertexColorEnabled.Value);
            }

            // Test the second mesh.
            {
                var mesh = output.Meshes[1];
                Assert.AreEqual("Mesh2", mesh.Name);
                Assert.AreEqual(output.Bones[2], mesh.ParentBone);
                Assert.AreEqual(inputMesh2, mesh.SourceMesh);
                Assert.That(new BoundingSphere(new Vector3(0.3809527f, 0.5858122f, 0.5115654f), 0.8660253f),
                            Is.EqualTo(mesh.BoundingSphere).Using(BoundingSphereComparer.Epsilon));

                Assert.NotNull(mesh.MeshParts);
                Assert.AreEqual(1, mesh.MeshParts.Count);

                var part = mesh.MeshParts[0];
                Assert.NotNull(part);
                Assert.AreEqual(1, part.PrimitiveCount);
                Assert.AreEqual(0, part.StartIndex);
                Assert.AreEqual(0, part.VertexOffset);
                Assert.AreEqual(3, part.NumVertices);

                Assert.NotNull(part.IndexBuffer);
                Assert.AreEqual(3, part.IndexBuffer.Count);
                Assert.AreEqual(0, part.IndexBuffer[0]);
                Assert.AreEqual(1, part.IndexBuffer[1]);
                Assert.AreEqual(2, part.IndexBuffer[2]);

                Assert.NotNull(part.VertexBuffer);
                Assert.NotNull(part.VertexBuffer.VertexData);
                var vertexData = part.VertexBuffer.VertexData;
                Assert.AreEqual(36, vertexData.Length);
                var positionArray = ArrayUtil.ConvertTo <Vector3>(vertexData);
                Assert.AreEqual(3, positionArray.Length);
                Assert.AreEqual(Vector3.Transform(new Vector3(0, 0, 0), processorXform), positionArray[0]);
                Assert.AreEqual(Vector3.Transform(new Vector3(1, 0, 0), processorXform), positionArray[1]);
                Assert.AreEqual(Vector3.Transform(new Vector3(1, 1, 1), processorXform), positionArray[2]);

                Assert.IsAssignableFrom <BasicMaterialContent>(part.Material);
                var material = part.Material as BasicMaterialContent;
                Assert.NotNull(material);
                Assert.IsNotEmpty(material.OpaqueData);
                Assert.AreEqual("Material1", material.Name);
                Assert.IsNull(material.Identity);
                Assert.IsTrue(material.OpaqueData.ContainsKey("Alpha"));
                Assert.NotNull(material.Alpha);
                Assert.AreEqual(0.5f, material.Alpha.Value);
                Assert.IsTrue(material.OpaqueData.ContainsKey("DiffuseColor"));
                Assert.NotNull(material.DiffuseColor);
                Assert.AreEqual(Color.Red.ToVector3(), material.DiffuseColor.Value);
                Assert.IsNull(material.EmissiveColor);
                Assert.IsNull(material.SpecularColor);
                Assert.IsNull(material.SpecularPower);
                Assert.IsNull(material.Texture);
                Assert.IsEmpty(material.Textures);
                Assert.IsTrue(material.OpaqueData.ContainsKey("VertexColorEnabled"));
                Assert.IsNotNull(material.VertexColorEnabled);
                Assert.IsFalse(material.VertexColorEnabled.Value);
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Path Settings
        if (Request.QueryString.Count == 0)
        {
            //W00ds1de337 //woodside
            Response.Redirect("RunModel.aspx?CaseName=SAMPLE2&ClientKey=OilWebDemo17&ModelType=OILSPILL&StartDate=20180911T22:00:00&simLength=24&WaterTemp=72.6F&IncLat=33.856999&IncLon=-118.541794&Winds=390&Currents=765&EcopWinds=GFS_WINDS&EcopCurrents=HYCOM_global_Navy_currents&Duration=6&Location=WORLD&&Volume=1000&group=7f22adb83ed7431f824df84a41a7f038&every1share=true&OilType=Heavy%20Crude%20Oil&OilUnits=5&FullPath=true&scriptid=Model2Shape&description=test&WNEID=Wanaea_Okha_FPSO&CMTID=Wanaea_Okha_FPSO");//&WNEID=Wanaea_Okha_FPSO&CMTID=Wanaea_Okha_FPSO
        }
        _sWebPath   = Path.GetDirectoryName(Server.MapPath("ModelRunMapPath.txt"));
        _OutputFile = "ERROR: an unknown error has occured in Page_Load";

        double timeout = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ProccessTimeout"]);

        //Parse the Query String
        string qsProcessed = processQueryString();

        if (qsProcessed != "")
        {
            Response.Write(qsProcessed);
            return;
        }

        if (!(Directory.Exists(_sWebPath + "\\ModelData\\LogFile")))
        {
            Directory.CreateDirectory(_sWebPath + "\\ModelData\\LogFile");
        }

        using (StreamWriter sw = new StreamWriter(_sWebPath + "\\ModelData\\LogFile\\LogFile.txt", true))
        {
            sw.WriteLine(String.Format("{0},{1},{2}", DateTime.Now.ToString(), HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], Request.QueryString.ToString()));
        }

        string sOutputPath = "\\ModelData\\" + _sLocation;

        CheckOutputPath(_sWebPath + sOutputPath);

        string sPrefixFile = _sWebPath + sOutputPath + "\\Winds\\Prefix.txt";

        _sWindsPrefix = "";
        if (File.Exists(sPrefixFile))
        {
            _sWindsPrefix = File.ReadAllText(sPrefixFile);  //System.Configuration.ConfigurationManager.AppSettings["WindFilePrefix"];
        }
        sPrefixFile      = _sWebPath + sOutputPath + "\\Currents\\CurrentsPrefix.txt";
        _sCurrentsPrefix = "";
        if (File.Exists(sPrefixFile))
        {
            _sCurrentsPrefix = File.ReadAllText(sPrefixFile); //System.Configuration.ConfigurationManager.AppSettings["CurrentFilePrefix"];
        }
        if (_bIsRivers)
        {
            sPrefixFile = _sWebPath + sOutputPath + "\\Currents\\RiverPrefix.txt";
            if (File.Exists(sPrefixFile))
            {
                _sCurrentsPrefix = File.ReadAllText(sPrefixFile); //System.Configuration.ConfigurationManager.AppSettings["RiverCurrentFilePrefix"];
            }
        }

        //Set up the aggregator
        EDSProcessor myProcessor = new EDSProcessor();

        string windsStat = "";

        //For WNE Winds
        if (_WNEWinds != "")
        {
            string sOutFilename = _sWebPath + sOutputPath + "\\winds\\" + _FileName + ".WNE";
            string sDate        = _StartDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string eDate        = _EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ");

            string source_loc       = "woodside_private";
            string station_list_bom = "Truscott, Onslow_Airport,Barrow_Island_Airport,Lombadina_Airport,Kalumburu,Port_Keats_Aero,Browse_Island,Broome_Airport";

            if (station_list_bom.Contains(_WNEWinds))
            {
                source_loc = "woodside_bom";
            }

            string wneURL = "https://data.oceansmap.com/model_data_service/get_data?start_time=" + sDate + "&end_time=" + eDate + "&station_id=" + _WNEWinds + "&type=WNE&token=gen_model_data&source_id=" + source_loc;

            using (var client = new WebClient())
            {
                //"http://data.oceansmap.com/model_data_service/get_data?start_time=2018-09-08T00:00:00Z&end_time=2018-09-10T00:00:00Z&station_id=Kalumburu&type=WNE&source_id=woodside_bom&token=gen_model_data"
                client.DownloadFile(wneURL, sOutFilename);
            }
            windsStat = sOutFilename;

            string sWNLFile = Path.ChangeExtension(sOutFilename, ".WNL");
            using (StreamWriter outfile = new StreamWriter(sWNLFile))
            {
                outfile.WriteLine(_IncidentSite.lon.ToString() + " " + _IncidentSite.lat.ToString());
                outfile.WriteLine("");
            }
        }
        else if (_Winds == m_cLocal)
        {
            //Process the winds
            _AggEngine = new AggregatorEngine(_Winds, _StartDate, _EndDate, _AOI, _sWebPath, _sWebPath + sOutputPath + "\\WINDS\\", _bIsRivers);
            windsStat  = _AggEngine.getWinds(_sWindsPrefix, _FileName);
            if (windsStat.Contains("ERROR"))
            {
                Response.Write(windsStat + " WINDS");
                return;
            }
        }
        else if (_Winds == m_cConstant)
        {
            windsStat = _sWebPath + sOutputPath + "\\WINDS\\" + _FileName + ".WNE";
            CreateWNEFile(windsStat, _WindMag, _WindDir);
        }
        else if (_Winds != m_cNoData) //EDS Winds
        {
            string sFilename = myProcessor.GetDataFile(_ClientKey, _Winds, _StartDate, _EndDate, _AOI);
            string sResult   = myProcessor.GetStatus(sFilename);
            if (sResult == "COMPLETE")
            {
                string sOutFilename = _sWebPath + sOutputPath + "\\winds\\" + _FileName + ".NC";
                myProcessor.DownloadDataFile(sOutFilename, sFilename);
                windsStat = sOutFilename;
            }
            else
            {
                windsStat = sResult;
            }

            if (!(File.Exists(windsStat)))
            {
                windsStat = "";
            }
        }

        _AggEngine = null;

        //Process the currents
        string currStat = "";

        //For CMT Currents
        if (_CMTCurrents != "")
        {
            string sOutFilename = _sWebPath + sOutputPath + "\\currents\\" + _FileName + ".CMT";
            string sDate        = _StartDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string eDate        = _EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string cmtURL       = "https://data.oceansmap.com/model_data_service/get_data?start_time=" + sDate + "&end_time=" + eDate + "&station_id=" + _CMTCurrents + "&type=CMT&source_id=woodside_private&token=gen_model_data";
            using (var client = new WebClient())
            {
                //"http://data.oceansmap.com/model_data_service/get_data?start_time=2018-03-04T00:00:00Z&end_time=2018-03-10T00:00:00Z&station_id=46088&type=CMT&source_id=ndbc"
                client.DownloadFile(cmtURL, sOutFilename);
            }
            currStat = sOutFilename;
        }
        else if (_Currents == m_cLocal)
        {
            if (_sCurrentsPrefix.ToUpper().Contains("STATIC"))
            {
                string[] sSplit = _sCurrentsPrefix.Split(new char[] { '-' });
                currStat = _sWebPath + sOutputPath + "\\Currents\\" + sSplit[1];
            }
            else
            {
                string currentsDataPath = _sWebPath;
                _AggEngine = new AggregatorEngine(_Currents, _StartDate, _EndDate, _AOI, _sWebPath, _sWebPath + sOutputPath + "\\Currents\\", _bIsRivers);
                currStat   = _AggEngine.getCurrents(_sCurrentsPrefix, _FileName);
                if (currStat.Contains("ERROR"))
                {
                    Response.Write(currStat + " CURRENTS");
                    return;
                }
            }
        }
        else if (_Currents == m_cConstant)
        {
            currStat = _sWebPath + sOutputPath + "\\Currents\\" + _FileName + ".CMT";
            CreateCMTFile(currStat, _CurrMag, _CurrDir);
        }
        else if (_Currents != m_cNoData)//EDS
        {
            string sFilename = myProcessor.GetDataFile(_ClientKey, _Currents, _StartDate, _EndDate, _AOI);
            string sResult   = myProcessor.GetStatus(sFilename);
            if (sResult == "COMPLETE")
            {
                string sOutFilename = _sWebPath + sOutputPath + "\\currents\\" + _FileName + ".NC";
                myProcessor.DownloadDataFile(sOutFilename, sFilename);
                currStat = sOutFilename;
            }
            else
            {
                currStat = sResult;
            }

            if (!(File.Exists(currStat)))
            {
                currStat = "";
            }
        }

        //Run the model
        _ModelProcessor = new ModelProcessor(_eModelType, timeout);
        if (_eModelType == ModelType.OilModel)
        {
            OilInputData oilInput = new OilInputData(_sWebPath, _sLocation);
            oilInput.bBox          = _AOI;
            oilInput.caseName      = _sCaseName;
            oilInput.incidentSite  = _IncidentSite;
            oilInput.start         = _StartDate;
            oilInput.end           = _EndDate;
            oilInput.currentFile   = currStat;
            oilInput.windsFile     = windsStat;
            oilInput.ecopCurrents  = _EcopCurrents;
            oilInput.ecopWinds     = _EcopWinds;
            oilInput.fileName      = _FileName;
            oilInput.spillDuration = _Duration;
            oilInput.SpillAmount   = _SpillAmount;
            oilInput.SpillUnits    = _OilUnits;
            oilInput.WaterTemp     = _WaterTemp;
            oilInput.evaporationOn = _EvapOn ? 0 : -1;
            oilInput.entrainOn     = _EntrainOn ? 0 : -1;
            // xp added
            oilInput.outputInterval = _OutputInterval;
            oilInput.modelStep      = _ModelStep;
            oilInput.groupID        = _groupIDShare;
            oilInput.every1         = _ShareEveryone;
            oilInput.description    = _description;

            if (_ModelMethod) //fast
            {
                oilInput.timeStep = 60;
            }
            else //comprehensive
            {
                oilInput.timeStep = 10;
            }

            /*if (_Currents == m_cConstant)
             * {
             *  oilInput.CurrMag = _CurrMag;
             *  oilInput.CurrDir = _CurrDir;
             * }
             * else
             * {
             *  oilInput.CurrMag = -999;
             *  oilInput.CurrDir = -999;
             * }*/

            oilInput.oilType = _OilType;

            /*if ((_Currents > 0) || (_Winds > 0))
             * {
             *  oilInput.coastLineFile = Path.GetDirectoryName(oilInput.coastLineFile) + "\\LANDPOLY.BDM";
             * }*/
            _OutputFile = _ModelProcessor.runOilModel(oilInput);
        }

        if (_eModelType == ModelType.ChemModel)
        {
            ChemInputData chemInput = new ChemInputData(_sWebPath, _sLocation);
            chemInput.bBox          = _AOI;
            chemInput.caseName      = _sCaseName;
            chemInput.incidentSite  = _IncidentSite;
            chemInput.start         = _StartDate;
            chemInput.end           = _EndDate;
            chemInput.currentFile   = currStat;
            chemInput.windsFile     = windsStat;
            chemInput.fileName      = _FileName;
            chemInput.chemType      = _ChemType;
            chemInput.spillDuration = _Duration;
            chemInput.ModelMethod   = _ModelMethod;

            /*if ((_Currents > 0) || (_Winds > 0))
             *  chemInput.coastLineFile = Path.GetDirectoryName(chemInput.coastLineFile) + "\\LANDPOLY.BDM";*/
            _OutputFile = _ModelProcessor.runChemModel(chemInput);
        }

        //Rout the output to the user
        if (_OutputFile == "")
        {
            Response.Write("ERROR: An error occurred while running the model.");
        }
        else if (_OutputFile.Contains("ERROR:"))
        {
            Response.Write(_OutputFile);
        }
        else
        {
            if (Request.QueryString["FullPath"] != null)
            {
                if (Request.QueryString["FullPath"] == "true")
                {
                    Response.Write("\\\\" + Environment.MachineName + "\\" + _sWebPath.Remove(0, 3) + sOutputPath + "\\Outdata\\" + _FileName + ".INP");
                }
                else
                {
                    Response.Write(_OutputFile);
                }
            }
            else
            {
                //Response.Write("\\\\" + Environment.MachineName + "\\" + _sWebPath.Remove(0, 3) + sOutputPath + "\\Outdata\\" + _OutputFile + ".INP");
                Response.Write(_OutputFile);
            }

            //if (_AddToDB)
            //  AddScenarioToDatabase();
        }

        //testing with hardcoded version
        //string testCommand = @"F:\groups\rps_data\code\ds_oilmapweb\SyncModelRun\Push2ESRI\Model2Shape_v6.py " + @"F:\groups\rps_data\code\ds_oilmapweb\SyncModelRun\ModelData\WORLD\Outdata\SAMPLE_TEST_109_87799.inp F:\groups\rps_data\code\ds_oilmapweb\SyncModelRun\ModelData";

        //convert the oilmap format to geodatabase
        string fileNameINP = _sWebPath + "\\" + sOutputPath + "\\Outdata\\" + _FileName + ".INP";

        //_sCaseName
        //_StartDate
        //_SpillAmount
        //_OilType
        //_OilUnits
        //_SimLength

        TimeSpan t = _StartDate - new DateTime(1970, 1, 1);
        int      secondsSinceEpoch = (int)t.TotalSeconds;

        string pyCommandInput = _sWebPath + @"\Push2ESRI\" + _scriptID + ".py " + fileNameINP + " " + _sCaseName + " " + secondsSinceEpoch + " " + _SimLength + " " + _SpillAmount + " " + _OilUnits + " \"" + _OilType + "\"" + " \"" + _description + "\"";


        string sPythonPath = "";
        string sArcVersion = "10.3";

        Platform myPlatform = GetPlatform();

        switch (myPlatform)
        {
        case Platform.X64:
            sPythonPath = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\ESRI\\Python" + sArcVersion, "PythonDir", "");
            break;

        default:
            sPythonPath = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\ESRI\\Python" + sArcVersion, "PythonDir", "");
            break;
        }

        //this may be in a different location so best to check all enviormental variables are correct
        //string pyLoc = "\"" + sPythonPath + "ArcGIS" + sArcVersion + "\\python.exe\"";
        string pyLoc = @"C:\Python27\ArcGISx6410.5\python.exe";  //for deploy on server

        Push2ESRI(pyLoc, pyCommandInput);
    }
示例#17
0
        public void DefaultEffectTest()
        {
            NodeContent input;
            {
                input = new NodeContent();

                var mesh = new MeshContent()
                {
                    Name = "Mesh1"
                };
                mesh.Positions.Add(new Vector3(0, 0, 0));
                mesh.Positions.Add(new Vector3(1, 0, 0));
                mesh.Positions.Add(new Vector3(1, 1, 1));

                var geom = new GeometryContent();
                geom.Vertices.Add(0);
                geom.Vertices.Add(1);
                geom.Vertices.Add(2);
                geom.Indices.Add(0);
                geom.Indices.Add(1);
                geom.Indices.Add(2);

                geom.Vertices.Channels.Add(VertexChannelNames.TextureCoordinate(0), new[]
                {
                    new Vector2(0, 0),
                    new Vector2(1, 0),
                    new Vector2(1, 1),
                });

                var wieghts = new BoneWeightCollection();
                wieghts.Add(new BoneWeight("bone1", 0.5f));
                geom.Vertices.Channels.Add(VertexChannelNames.Weights(0), new[]
                {
                    wieghts,
                    wieghts,
                    wieghts
                });

                mesh.Geometry.Add(geom);
                input.Children.Add(mesh);

                var bone1 = new BoneContent {
                    Name = "bone1", Transform = Matrix.CreateTranslation(0, 1, 0)
                };
                input.Children.Add(bone1);

                var anim = new AnimationContent()
                {
                    Name     = "anim1",
                    Duration = TimeSpan.Zero
                };
                input.Animations.Add(anim.Name, anim);
            }

            var processorContext = new ProcessorContext(TargetPlatform.Windows, "dummy.xnb");
            var processor        = new ModelProcessor
            {
                DefaultEffect = MaterialProcessorDefaultEffect.SkinnedEffect,
            };

            var output = processor.Process(input, processorContext);

            // TODO: Not sure why, but XNA always returns a BasicMaterialContent
            // even when we specify SkinnedEffect as the default.  We need to fix
            // the test first before we can enable the assert here.

            //Assert.IsInstanceOf(typeof(SkinnedMaterialContent), output.Meshes[0].MeshParts[0].Material);
        }
 public ReferenceModelTests()
 {
     _modelProcessor = new ModelProcessor(new PersonLookupCache(), new RelationshipResolver(),
                                          "FamilyTree.ReferenceModel.arthur-clan.txt");
 }
示例#19
0
        /// <summary>
        /// Ajoute un élément binaire au document principal.
        /// </summary>
        /// <param name="fichier">Fichier.</param>
        /// <returns>Code embed.</returns>
        private string AddDocumentPart(byte[] fichier)
        {
            _guid = Guid.NewGuid().ToString();

            long          width  = 0;
            long          height = 0;
            ImagePartType imagePartType;

            if (fichier != null && fichier.Length > 0)
            {
                using (MemoryStream imgStream = new MemoryStream((byte[])fichier.Clone())) {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);
                    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
                    {
                        imagePartType = ImagePartType.Png;
                    }
                    else if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
                    {
                        imagePartType = ImagePartType.Gif;
                    }
                    else if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
                    {
                        imagePartType = ImagePartType.Jpeg;
                    }
                    else if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
                    {
                        imagePartType = ImagePartType.Tiff;
                    }
                    else
                    {
                        imagePartType = ImagePartType.Png;
                    }

                    width  = (long)(img.Width * 914400 / img.HorizontalResolution);
                    height = (long)(img.Height * 914400 / img.VerticalResolution);
                }

                IEnumerable <Extent> extentList = this.CurrentElement.Descendants <Extent>();
                foreach (Extent item in extentList)
                {
                    item.Cx = new Int64Value(width);
                    item.Cy = new Int64Value(height);
                    break;
                }

                IEnumerable <Extents> extentsList = this.CurrentElement.Descendants <Extents>();
                foreach (Extents item in extentsList)
                {
                    item.Cx = new Int64Value(width);
                    item.Cy = new Int64Value(height);
                    break;
                }

                IEnumerable <DocProperties> docPropertiesList = this.CurrentElement.Descendants <DocProperties>();
                foreach (DocProperties item in docPropertiesList)
                {
                    item.Id          = Convert.ToUInt32(ModelProcessor.GetNextImageCounter(this.DocumentId.ToString()));
                    item.Description = string.Empty;
                    break;
                }

                IEnumerable <GraphicData> graphicDataList = this.CurrentElement.Descendants <GraphicData>();
                foreach (GraphicData item in graphicDataList)
                {
                    item.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
                    break;
                }

                IEnumerable <GraphicFrameLocks> graphicFrameLocksList = this.CurrentElement.Descendants <GraphicFrameLocks>();
                foreach (GraphicFrameLocks item in graphicFrameLocksList)
                {
                    item.NoChangeAspect = true;
                    item.NoResize       = true;
                    break;
                }

                IEnumerable <NonVisualDrawingProperties> nonVisualDrawingPropertiesList = this.CurrentElement.Descendants <NonVisualDrawingProperties>();
                foreach (NonVisualDrawingProperties item in nonVisualDrawingPropertiesList)
                {
                    item.Description = string.Empty;
                    break;
                }

                using (MemoryStream msImagePart = new MemoryStream(fichier)) {
                    if (this.CurrentPart.GetType() == typeof(HeaderPart))
                    {
                        ImagePart imagePart = ((HeaderPart)this.CurrentPart).AddImagePart(imagePartType, "img" + _guid);
                        imagePart.FeedData(msImagePart);
                    }
                    else if (this.CurrentPart.GetType() == typeof(FooterPart))
                    {
                        ImagePart imagePart = ((FooterPart)this.CurrentPart).AddImagePart(imagePartType, "img" + _guid);
                        imagePart.FeedData(msImagePart);
                    }
                    else
                    {
                        ImagePart imagePart = ((MainDocumentPart)this.CurrentPart).AddImagePart(imagePartType, "img" + _guid);
                        imagePart.FeedData(msImagePart);
                    }
                }

                return("img" + _guid);
            }

            return(string.Empty);
        }
示例#20
0
        protected override void DrawCore(RenderContext context)
        {
            modelProcessor = SceneInstance.GetCurrent(context).GetProcessor <ModelProcessor>();
            lightProcessor = SceneInstance.GetCurrent(context).GetProcessor <LightProcessor>();

            // No light processors means no light in the scene, so we can early exit
            if (lightProcessor == null || modelProcessor == null)
            {
                return;
            }

            // Not in the context of a SceneCameraRenderer? just exit
            sceneCameraRenderer = context.Tags.Get(SceneCameraRenderer.Current);
            sceneCamera         = context.Tags.Get(CameraComponentRenderer.Current);
            if (sceneCameraRenderer == null || sceneCamera == null)
            {
                return;
            }
            sceneCullingMask = sceneCameraRenderer.CullingMask;

            // Setup the callback on the ModelRenderer and shadow map LightGroupRenderer
            if (!isModelComponentRendererSetup)
            {
                // TODO: Check if we could discover declared renderers in a better way than just hacking the tags of a component
                var modelRenderer = ModelComponentRenderer.GetAttached(sceneCameraRenderer);
                if (modelRenderer == null)
                {
                    return;
                }

                modelRenderer.Callbacks.PreRenderModel += PrepareRenderModelForRendering;
                modelRenderer.Callbacks.PreRenderMesh  += PreRenderMesh;

                // TODO: Make this pluggable
                // TODO: Shadows should work on mobile platforms
                if (context.GraphicsDevice.Features.Profile >= GraphicsProfile.Level_10_0 &&
                    (Platform.Type == PlatformType.Windows || Platform.Type == PlatformType.WindowsStore || Platform.Type == PlatformType.Windows10))
                {
                    shadowMapRenderer = new ShadowMapRenderer(modelRenderer.EffectName);
                    shadowMapRenderer.Renderers.Add(typeof(LightDirectional), new LightDirectionalShadowMapRenderer());
                    shadowMapRenderer.Renderers.Add(typeof(LightSpot), new LightSpotShadowMapRenderer());
                }

                isModelComponentRendererSetup = true;
            }

            // Collect all visible lights
            CollectVisibleLights();

            // Draw shadow maps
            if (shadowMapRenderer != null)
            {
                shadowMapRenderer.Draw(context, visibleLightsWithShadows);
            }

            // Prepare active renderers in an ordered list (by type and shadow on/off)
            CollectActiveLightRenderers(context);

            currentModelLightShadersPermutationEntry = null;
            currentModelShadersParameters            = null;
            currentShadowReceiver = true;

            // Clear the cache of parameter entries
            lightParameterEntries.Clear();
            parameterCollectionEntryPool.Clear();

            // Clear association between model and lights
            modelToLights.Clear();

            // Clear all data generated by shader entries
            foreach (var shaderEntry in shaderEntries)
            {
                shaderEntry.Value.ResetGroupDatas();
            }
        }
示例#21
0
        public void DefaultEffectTest()
        {
            NodeContent input;
            {
                input = new NodeContent();

                var mesh = new MeshContent()
                {
                    Name = "Mesh1"
                };
                mesh.Positions.Add(new Vector3(0, 0, 0));
                mesh.Positions.Add(new Vector3(1, 0, 0));
                mesh.Positions.Add(new Vector3(1, 1, 1));

                var geom = new GeometryContent();
                geom.Vertices.Add(0);
                geom.Vertices.Add(1);
                geom.Vertices.Add(2);
                geom.Indices.Add(0);
                geom.Indices.Add(1);
                geom.Indices.Add(2);

                geom.Vertices.Channels.Add(VertexChannelNames.TextureCoordinate(0), new[]
                {
                    new Vector2(0,0),
                    new Vector2(1,0),
                    new Vector2(1,1),
                });

                var wieghts = new BoneWeightCollection();
                wieghts.Add(new BoneWeight("bone1", 0.5f));
                geom.Vertices.Channels.Add(VertexChannelNames.Weights(0), new[]
                {
                    wieghts, 
                    wieghts, 
                    wieghts
                });

                mesh.Geometry.Add(geom);
                input.Children.Add(mesh);

                var bone1 = new BoneContent { Name = "bone1", Transform = Matrix.CreateTranslation(0,1,0) };
                input.Children.Add(bone1);

                var anim = new AnimationContent()
                {
                    Name = "anim1",
                    Duration = TimeSpan.Zero
                };
                input.Animations.Add(anim.Name, anim);
            }

            var processorContext = new TestProcessorContext(TargetPlatform.Windows, "dummy.xnb");
            var processor = new ModelProcessor
            {
                DefaultEffect = MaterialProcessorDefaultEffect.SkinnedEffect,                
            };

            var output = processor.Process(input, processorContext);

            // TODO: Not sure why, but XNA always returns a BasicMaterialContent 
            // even when we specify SkinnedEffect as the default.  We need to fix
            // the test first before we can enable the assert here.

            //Assert.IsInstanceOf(typeof(SkinnedMaterialContent), output.Meshes[0].MeshParts[0].Material);
        }
示例#22
0
        public void BasicMeshTests()
        {
            var input = CreateBasicMesh();

            var processorContext = new TestProcessorContext(TargetPlatform.Windows, "dummy.xnb");
            var processor = new ModelProcessor
            {
                RotationX = 10, 
                RotationY = 20,
                RotationZ = 30
            };
            var output = processor.Process(input, processorContext);

            // The transform the processor above is applying to the model.
            var processorXform =    Matrix.CreateRotationZ(MathHelper.ToRadians(30))*
                                    Matrix.CreateRotationX(MathHelper.ToRadians(10))*
                                    Matrix.CreateRotationY(MathHelper.ToRadians(20));

            // Test some basics.
            Assert.NotNull(output);
            Assert.NotNull(output.Meshes);
            Assert.AreEqual(2, output.Meshes.Count);
            Assert.NotNull(output.Bones);
            Assert.AreEqual(3, output.Bones.Count);
            Assert.NotNull(output.Root);
            Assert.AreEqual(output.Root, output.Bones[0]);

            // Stuff to make the tests below cleaner.
            var inputMesh1 = input.Children[0] as MeshContent;
            Assert.NotNull(inputMesh1);
            var inputMesh2 = input.Children[1] as MeshContent;
            Assert.NotNull(inputMesh2);

            // Test the bones.
            Assert.AreEqual("Root", output.Bones[0].Name);
            Assert.That(input.Transform, Is.EqualTo(output.Bones[0].Transform).Using(MatrixComparer.Epsilon));
            Assert.AreEqual("Mesh1", output.Bones[1].Name);
            Assert.That(Matrix.Identity, Is.EqualTo(output.Bones[1].Transform).Using(MatrixComparer.Epsilon));
            Assert.AreEqual("Mesh2", output.Bones[2].Name);
            Assert.That(Matrix.Identity, Is.EqualTo(output.Bones[2].Transform).Using(MatrixComparer.Epsilon));

            // Test the first mesh.
            {
                var mesh = output.Meshes[0];
                Assert.AreEqual("Mesh1", mesh.Name);
                Assert.AreEqual(output.Bones[1], mesh.ParentBone);
                Assert.AreEqual(inputMesh1, mesh.SourceMesh);
                Assert.AreEqual(new BoundingSphere(Vector3.Zero, 0), mesh.BoundingSphere);

                Assert.NotNull(mesh.MeshParts);
                Assert.AreEqual(1, mesh.MeshParts.Count);

                var part = mesh.MeshParts[0];
                Assert.NotNull(part);
                Assert.IsNull(part.IndexBuffer);
                Assert.IsNull(part.VertexBuffer);
                Assert.AreEqual(0, part.NumVertices);
                Assert.AreEqual(0, part.PrimitiveCount);
                Assert.AreEqual(0, part.StartIndex);
                Assert.AreEqual(0, part.VertexOffset);

                Assert.IsAssignableFrom<BasicMaterialContent>(part.Material);
                var material = part.Material as BasicMaterialContent;
                Assert.NotNull(material);
                Assert.IsNotEmpty(material.OpaqueData);
                Assert.IsNull(material.Name);
                Assert.IsNull(material.Identity);
                Assert.IsNull(material.Alpha);
                Assert.IsNull(material.DiffuseColor);
                Assert.IsNull(material.EmissiveColor);
                Assert.IsNull(material.SpecularColor);
                Assert.IsNull(material.SpecularPower);
                Assert.IsNull(material.Texture);
                Assert.IsEmpty(material.Textures);
                Assert.IsTrue(material.OpaqueData.ContainsKey("VertexColorEnabled"));
                Assert.IsNotNull(material.VertexColorEnabled);
                Assert.IsFalse(material.VertexColorEnabled.Value);
            }

            // Test the second mesh.
            {
                var mesh = output.Meshes[1];
                Assert.AreEqual("Mesh2", mesh.Name);
                Assert.AreEqual(output.Bones[2], mesh.ParentBone);
                Assert.AreEqual(inputMesh2, mesh.SourceMesh);
                Assert.That(new BoundingSphere(new Vector3(0.3809527f, 0.5858122f, 0.5115654f), 0.8660253f),
                Is.EqualTo(mesh.BoundingSphere).Using(BoundingSphereComparer.Epsilon));

                Assert.NotNull(mesh.MeshParts);
                Assert.AreEqual(1, mesh.MeshParts.Count);

                var part = mesh.MeshParts[0];
                Assert.NotNull(part);
                Assert.AreEqual(1, part.PrimitiveCount);
                Assert.AreEqual(0, part.StartIndex);
                Assert.AreEqual(0, part.VertexOffset);
                Assert.AreEqual(3, part.NumVertices);
                
                Assert.NotNull(part.IndexBuffer);
                Assert.AreEqual(3, part.IndexBuffer.Count);
                Assert.AreEqual(0, part.IndexBuffer[0]);
                Assert.AreEqual(1, part.IndexBuffer[1]);
                Assert.AreEqual(2, part.IndexBuffer[2]);

                Assert.NotNull(part.VertexBuffer);
                Assert.NotNull(part.VertexBuffer.VertexData);
                var vertexData = part.VertexBuffer.VertexData;
                Assert.AreEqual(36, vertexData.Length);
                var positionArray = ArrayUtil.ConvertTo<Vector3>(vertexData);
                Assert.AreEqual(3, positionArray.Length);
                Assert.AreEqual(Vector3.Transform(new Vector3(0, 0, 0), processorXform), positionArray[0]);
                Assert.AreEqual(Vector3.Transform(new Vector3(1, 0, 0), processorXform), positionArray[1]);
                Assert.AreEqual(Vector3.Transform(new Vector3(1, 1, 1), processorXform), positionArray[2]);

                Assert.IsAssignableFrom<BasicMaterialContent>(part.Material);
                var material = part.Material as BasicMaterialContent;
                Assert.NotNull(material);
                Assert.IsNotEmpty(material.OpaqueData);
                Assert.AreEqual("Material1", material.Name);
                Assert.IsNull(material.Identity);
                Assert.IsTrue(material.OpaqueData.ContainsKey("Alpha"));
                Assert.NotNull(material.Alpha);
                Assert.AreEqual(0.5f, material.Alpha.Value);
                Assert.IsTrue(material.OpaqueData.ContainsKey("DiffuseColor"));
                Assert.NotNull(material.DiffuseColor);
                Assert.AreEqual(Color.Red.ToVector3(), material.DiffuseColor.Value);
                Assert.IsNull(material.EmissiveColor);
                Assert.IsNull(material.SpecularColor);
                Assert.IsNull(material.SpecularPower);
                Assert.IsNull(material.Texture);
                Assert.IsEmpty(material.Textures);
                Assert.IsTrue(material.OpaqueData.ContainsKey("VertexColorEnabled"));
                Assert.IsNotNull(material.VertexColorEnabled);
                Assert.IsFalse(material.VertexColorEnabled.Value);
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            string modelName = "Model 2 Test";

            ModelFactory.ModelName = modelName;

            //model modelArchisurance = ObjectFactory.NewModel("Archisurance");
            //DataSet dsArchisurance = new DataSet();
            //string xmlArchiSurance = @"..\..\..\PSN.ModelMate.Schema\Samples\Archisurance\Archisurance-psn.xml";
            //dsArchisurance.ReadXml(xmlArchiSurance);
            ////dsArchisurance.WriteXmlSchema("xmlArchiSurance.xsd");
            ////dsArchisurance.WriteXml("xmlArchiSurance.xml");
            //var mmpArchisurance = new ModelMateProcessor(ModelMateProcessor.ConvertAMEFFDataSet2Model);
            //// TODO TODO mmpArchisurance.ProcessModel(dsArchisurance, (DbContext)null, new Collection<model> { modelArchisurance });

            string tenantName = "Tenant 0 " + DateTime.Now.ToString();

            ModelFactory.TenantName = tenantName;

            var tenant0 = ModelFactory.NewTenantWithRootFolder(tenantName);

            tenantName = "Tenant 1 " + DateTime.Now.ToString();
            ModelFactory.TenantName = tenantName;

            var tenant1 = ModelFactory.NewTenant(tenantName,
                                                 ModelFactory.NewFolder("/",
                                                                        new folder[] { ModelFactory.NewFolder("Model Templates"), ModelFactory.NewFolder("Production Models") }
                                                                        )
                                                 );

            ModelConst.PropertyDataType dtStringType = ModelConst.PropertyDataType.stringType;
            propertydef  pdefString = ModelFactory.NewPropertyDef("String Propertydef " + DateTime.Now.ToString(), dtStringType);
            propertydefs pdefs      = ModelFactory.NewPropertyDefs(pdefString);

            ModelConst.ElementType etAC = ModelConst.ElementType.ApplicationComponent;
            element[] elementArray      = new element[10];
            for (int iElement = 0; iElement < 10; iElement++)
            {
                property p = ModelFactory.NewProperty(ModelFactory.NewValue("Element Property Value " + DateTime.Now.ToString()),
                                                      pdefString);
                elementArray[iElement] = ModelFactory.NewElement("Element " + iElement.ToString() + " " + DateTime.Now.ToString(), etAC, p);
            }
            elements elements = ModelFactory.NewElements(elementArray);

            tenantName = "Tenant 2 Test";
            ModelFactory.TenantName = tenantName;

            model model2;
            //var tenant2 = ModelFactory.NewTenant(tenantName,
            //                ModelFactory.NewFolder("/",
            //                    ModelFactory.NewFolder("Production Models",
            //                        ModelFactory.NewFolder("HQ Models Folder " + DateTime.Now.ToString(),
            //                            model2 = ModelFactory.NewModel(modelName, ModelConst.LANG_EN,
            //                                                            elements, pdefs
            //                            )
            //                        )
            //                    )
            //                )
            //              );

            var tenant2 = ModelFactory.NewTenant(tenantName,
                                                 ModelFactory.NewFolder("/",
                                                                        model2 = ModelFactory.NewModel(modelName, ModelConst.LANG_EN,
                                                                                                       elements, pdefs
                                                                                                       )
                                                                        )
                                                 );

            Console.WriteLine("Tenant.tenant_Id " + tenant2.tenant_Id.ToString());
            foreach (folders fs in tenant2.folders)
            {
                Console.WriteLine("Folders.tenant_Id " + fs.tenant_Id.ToString());
                Console.WriteLine("Folders.folders_Id " + fs.folders_Id.ToString());

                foreach (folder f in fs.folder)
                {
                    Console.WriteLine("Folder " + f.folders_Id.ToString());
                    Console.WriteLine("Folder " + f.folder_Id.ToString());
                }
            }

            var name = ModelFactory.NewName("Model 2 Name " + DateTime.Now.ToString());

            model2.name.Add(name);
            var documentation = ModelFactory.NewDocumentation("Model 2 Documentation " + DateTime.Now.ToString());

            model2.documentation.Add(documentation);
            var metadata = ModelFactory.NewMetadata(
                ModelFactory.NewProperty(ModelFactory.NewValue("Model 2 Metadata Value " + DateTime.Now.ToString()), pdefString)
                );

            model2.metadata.Add(metadata);

            var properties = ModelFactory.NewProperties(
                ModelFactory.NewProperty(ModelFactory.NewValue("Model 2 Property Value " + DateTime.Now.ToString()), pdefString)
                );

            model2.properties.Add(properties);

            var relationship1 = ModelFactory.NewRelationship("Association Relationship " + DateTime.Now.ToString(),
                                                             ModelConst.RelationshipType.AssociationRelationship,
                                                             elementArray[0], elementArray[1]
                                                             );
            var relationships = ModelFactory.NewRelationships(relationship1);

            model2.relationships.Add(relationships);

            var organization = ModelFactory.NewOrganization(
                ModelFactory.NewItem(elementArray[0],
                                     ModelFactory.NewItem(null,
                                                          ModelFactory.NewItem(elementArray[1]
                                                                               )
                                                          )
                                     )
                );

            model2.organization.Add(organization);

            var style1 = ModelFactory.NewStyle(
                ModelFactory.NewFillColor(255, 0, 0),
                ModelFactory.NewLineColor(0, 255, 0),
                ModelFactory.NewFont("Times Roman", (float)10.5, "bold", ModelFactory.NewColor(0, 0, 255)), 3
                );
            var style2 = ModelFactory.NewStyle(
                ModelFactory.NewFillColor(255, 0, 0),
                ModelFactory.NewLineColor(0, 255, 0),
                ModelFactory.NewFont("Times Roman", (float)12.5, "bold", ModelFactory.NewColor(0, 0, 255)), 3
                );

            var node0 = ModelFactory.NewNode("Node 0 " + DateTime.Now.ToString(),
                                             0, 0, 0, 50, 50, 50,
                                             elementArray[0], null, null, style1,
                                             new node[] { ModelFactory.NewNode("Sub Node " + DateTime.Now.ToString(),
                                                                               10, 10, 10, 25, 25, 25,
                                                                               elementArray[3]) }
                                             );
            var node1 = ModelFactory.NewNode("Node 1 " + DateTime.Now.ToString(),
                                             100, 100, 100, 50, 50, 50,
                                             elementArray[1], null, null, style2,
                                             null
                                             );

            var bendpoint1  = ModelFactory.NewBendPoint(25, 25, 25);
            var connection1 = ModelFactory.NewConnection("Connection 1 " + DateTime.Now.ToString(),
                                                         node0, node1, relationship1
                                                         );

            connection1.bendpoint.Add(bendpoint1);

            view view2;
            var  views = ModelFactory.NewViews(
                view2 = ModelFactory.NewView("View 2 " + DateTime.Now.ToString(), ModelConst.ViewType.Layered,
                                             new node[] {
                node0, node1
            },
                                             new connection[] { connection1 }
                                             )
                );

            model2.views.Add(views);

            tenant2.processinghistory.Add(
                ModelFactory.NewProcessinghistory(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Processinghistory " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.processinghistory, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            tenant2.usage.Add(
                ModelFactory.NewUsage(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.usage, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            tenant2.performance.Add(
                ModelFactory.NewPerformance(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.performance, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            tenant2.management.Add(
                ModelFactory.NewManagement(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Management " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.management, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );

            model2.processinghistory.Add(
                ModelFactory.NewProcessinghistory(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Processinghistory " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.processinghistory, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            model2.usage.Add(
                ModelFactory.NewUsage(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.usage, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            model2.performance.Add(
                ModelFactory.NewPerformance(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.performance, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            model2.management.Add(
                ModelFactory.NewManagement(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Management " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.management, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );

            elementArray[0].processinghistory.Add(
                ModelFactory.NewProcessinghistory(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Processinghistory " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.processinghistory, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            elementArray[0].usage.Add(
                ModelFactory.NewUsage(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.usage, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            elementArray[0].performance.Add(
                ModelFactory.NewPerformance(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.performance, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            elementArray[0].management.Add(
                ModelFactory.NewManagement(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Management " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.management, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );

            view2.processinghistory.Add(
                ModelFactory.NewProcessinghistory(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Processinghistory " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.processinghistory, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            view2.usage.Add(
                ModelFactory.NewUsage(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.usage, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            view2.performance.Add(
                ModelFactory.NewPerformance(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Performance " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.performance, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );
            view2.management.Add(
                ModelFactory.NewManagement(
                    ModelFactory.NewTimesnap(DateTime.Now, "Timesnap Management " + DateTime.Now.ToString(),
                                             ModelConst.TimesnapCategory.management, "Subcategory " + DateTime.Now.ToString(),
                                             null, null,
                                             ModelFactory.NewProperty(ModelFactory.NewValue("Value " + DateTime.Now.ToString()), pdefString
                                                                      )
                                             )
                    )
                );

            //using (XmlWriter writer = XmlWriter.Create("model2.xml"))
            //{
            //    //XmlSerializer serializer = new XmlSerializer(typeof(model));
            //    DataContractSerializerSettings settings = new DataContractSerializerSettings();
            //    DataContractSerializer serializer = new DataContractSerializer(typeof(model));
            //    serializer.WriteObject(writer, model2);
            //    writer.Close();
            //}

            string xmlSchemaFile = @"..\..\..\PSN.ModelMate.Schema\Schema\Reference ModelGood9.xsd";

            // DataSet ds = new DataSet();
            // ds.ReadXmlSchema(xmlSchemaFile);
            // BUG DataSet ds2 = new DataSet();
            // BUG ds2.ReadXmlSchema(xmlSchemaFile);

            //DataTable dttenant = ds.Tables["tenant"];
            //DataRow drtentant1 = dttenant.NewRow();
            //DataRow drtentant2 = ds.Tables["tenant"].NewRow();

            //DataTable dtfolders = ds.Tables["folders"];
            //DataTable dtfolder = ds.Tables["folder"];
            //DataTable dtmodels = ds.Tables["models"];
            //DataTable dtmodel = ds.Tables["model"];

            //DataTable dtprocessinghistory = ds.Tables["processinghistory"];
            //DataTable dtusage = ds.Tables["usage"];
            //DataTable dtperformance = ds.Tables["performance"];
            //DataTable dtmanagement = ds.Tables["management"];
            //DataTable dttimesnap = ds.Tables["timesnap"];

            //DataTable dtproperties = ds.Tables["properties"];
            //DataTable dtproperty = ds.Tables["property"];

            //DataTable dtpropertydefs = ds.Tables["propertydefs"];
            //DataTable dtpropertydef = ds.Tables["propertydef"];

            //DataTable dtelements = ds.Tables["elements"];
            //DataTable dtelement = ds.Tables["element"];

            //DataTable dtrelationships = ds.Tables["relationships"];
            //DataTable dtrelationship = ds.Tables["relationship"];

            //DataTable dtviews = ds.Tables["views"];
            //DataTable dtview = ds.Tables["view"];
            //DataTable dtconnection = ds.Tables["connection"];
            //DataTable dtnode = ds.Tables["node"];

            //DataTable dtstyle = ds.Tables["style"];
            //DataTable dtfont = ds.Tables["font"];
            //DataTable dtfillColor = ds.Tables["fillColor"];
            //DataTable dtlineColor = ds.Tables["lineColor"];
            //DataTable dtcolor = ds.Tables["color"];
            //DataTable dtbendpoint = ds.Tables["bendpoint"];

            //DataTable dtmetadata = ds.Tables["metadata"];

            //DataTable dtorganization = ds.Tables["organization"];
            //DataTable dtitem = ds.Tables["item"];

            //DataTable dtname = ds.Tables["name"];
            //DataTable dtvalue = ds.Tables["value"];
            //DataTable dtdocumentation = ds.Tables["documentation"];
            //DataTable dtlabel = ds.Tables["label"];

            using (var ctx = new ModelMateEFModel9Context())
            {
                ctx.Database.Log = Console.Write;

                ctx.tenant.Add(tenant0);
                ModelDump.DisplayTrackedEntities("Add tenant0", ctx.ChangeTracker);
                ctx.SaveChanges();
                ModelDump.DisplayTrackedEntities("Save tenant0", ctx.ChangeTracker);

                ctx.tenant.Add(tenant1);
                ctx.SaveChanges();

                ctx.tenant.Add(tenant2);
                ModelDump.DisplayTrackedEntities("Add tenant2", ctx.ChangeTracker);
                ctx.SaveChanges();
                ModelDump.DisplayTrackedEntities("Save tenant2", ctx.ChangeTracker);
                ModelDump.DisplayDBPropertyValues("tenant2", ctx.Entry(tenant2).CurrentValues, null);
                ModelDump.DisplayDBPropertyValues("model2", ctx.Entry(model2).CurrentValues, null);
                Console.WriteLine("Tenant.tenant_Id " + tenant2.tenant_Id.ToString());
                foreach (folders fs in tenant2.folders)
                {
                    Console.WriteLine("Folders.tenant_Id " + fs.tenant_Id.ToString());
                    Console.WriteLine("Folders.folders_Id " + fs.folders_Id.ToString());

                    foreach (folder f in fs.folder)
                    {
                        Console.WriteLine("Folder " + f.folders_Id.ToString());
                        Console.WriteLine("Folder " + f.folder_Id.ToString());
                    }
                }

                folders fs0 = tenant2.folders.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("fs0", ctx.Entry(fs0).CurrentValues, null);

                folder f0 = fs0.folder.ElementAt(0);
                ModelDump.DisplayDBPropertyValues("f0", ctx.Entry(f0).CurrentValues, null);

                Console.WriteLine("RECURSION ==================================================");
                //DataSet dsTenant = new DataSet();
                //dsTenant.ReadXmlSchema(xmlSchemaFile);
                ////dsTenant.Tables["tenant"].Namespace = "http://www.w3.org/XML/1998/namespace";
                ////dsTenant.Tables["tenant"].Prefix = "xml";
                //var tenant = ctx.tenant.Find(new object[] { tenant2.tenant_Id });
                //var mmp = new ModelMateProcessor(ModelMateProcessor.ProcessObjectPopulateXMLDataSet);
                //mmp.ProcessTenant(dsTenant, (DbContext)ctx, new Collection<tenant> { tenant });
                //dsTenant.WriteXml("tentantds.xml");

                string  modelSchemaFile = @"..\..\..\PSN.ModelMate.Schema\Schema\ModelMateModel9.xsd";
                DataSet dsModel         = new DataSet();
                dsModel.ReadXmlSchema(modelSchemaFile);
                //DataSet ds3 = dsModel.Copy();
                //var mmpModel = new ModelMateProcessor();
                var mmpModel = new ModelProcessor(ModelProcessor.ConvertModel2AMEFFDataSet);
                mmpModel.ProcessModel(dsModel, (DbContext)ctx, new Collection <model> {
                    model2
                });
                dsModel.WriteXml("modelds.xml", XmlWriteMode.IgnoreSchema);
                string filename = "modelds2.xml";
                mmpModel.SaveAMEFFDataSetAsXML(dsModel, filename);

                tenant2.version = ModelConst.TENANT_TESTVERSION;
                var name2 = ModelFactory.NewName("Model Name FR " + DateTime.Now.ToString(), ModelConst.LANG_FR);
                model2.name.Add(name2);
                var name3 = ModelFactory.NewName("Model Name EN " + DateTime.Now.ToString());
                model2.name.Add(name3);
                ModelDump.DisplayTrackedEntities("Change tenant2", ctx.ChangeTracker);
                ctx.SaveChanges();
                ModelDump.DisplayTrackedEntities("Save tenant2", ctx.ChangeTracker);

                object[] keys    = { -1702823521 };
                tenant   tenant9 = ctx.tenant.Find(keys);
                //ctx.tenant.Remove(tenantDelete);
                //ctx.SaveChanges();
            }

            Console.WriteLine("Press enter to exist...");
            Console.ReadLine();
        }