Exemple #1
0
 public static bool WriteFileMCA(string importPath, bool useSplatmaps, ASCData source, string filename, int subsampling, Bounds bounds)
 {
     if (subsampling < 1)
     {
         subsampling = 1;
     }
     float[,] grid = new float[bounds.NumCols / subsampling, bounds.NumRows / subsampling];
     for (int x = 0; x < grid.GetLength(0); x++)
     {
         for (int y = 0; y < grid.GetLength(1); y++)
         {
             grid[x, y] = source.data[bounds.xMin + x * subsampling, bounds.yMin + y * subsampling];
         }
     }
     try {
         if (!filename.EndsWith(".mca"))
         {
             filename += ".mca";
         }
         IExporter exporter = new MCWorldExporter(importPath, grid, true, useSplatmaps);
         ExportUtility.WriteFile(exporter, filename, ExportUtility.GetFormatFromIdenfifier("MCA"));
         return(true);
     } catch (Exception e) {
         Program.WriteError("Failed to create Minecraft region file!");
         Program.WriteLine(e.ToString());
         return(false);
     }
 }
Exemple #2
0
        public static bool WriteWorldSave(ExportJob job, bool decorate, bool useSplatmaps)
        {
            IExporter exporter = new MCWorldExporter(job, decorate, useSplatmaps);

            ExportUtility.WriteFile(exporter, job.FilePath, ExportUtility.GetFormatFromIdenfifier("MCW"));
            return(true);
        }
        protected void ExportDataSet(DataSet ds)
        {
            ExportUtility exp = new ExportUtility();
            string        relativePathFilename = string.Empty;
            string        absoluteFilename     = string.Empty;

            try
            {
                FileNamingUtility.GetCsvFileName(Page.Session, ref absoluteFilename, ref relativePathFilename);
                exp.ExportDataSetToCSV(ds, absoluteFilename);

                //On the Page load we will open a new window so that the user may choose
                //to save or open the export.
                //RegisterExportFileWindow(relativePathFilename);

                //Commented out the line above, because the window would not work on the First Tier
                //The First Tier is where the application sits
                //This will prompt the user to save the file to there own machine.
                //we know that the file will be opened in Excel. So we replace the
                DownloadFile(absoluteFilename);
            }
            catch (Exception ex)
            {
                throw ex; //Allow the exception to flow up the call stack.
            }
        }
Exemple #4
0
        //Caesar: Download function:
        public void DownloadContractOverview()
        {
            //Test
            var             currentUser = manager.FindById(User.Identity.GetUserId());
            List <Contract> contracts   = db.Contracts.ToList();

            //Endtest

            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(ms);
                ExportUtility.ContractExport(contracts, sw);
                bytes = ms.ToArray();
            }

            Response.Clear();
            Response.ClearHeaders();

            Response.AddHeader("Content-Length", bytes.Length.ToString());
            Response.ContentType = "text-plain";
            Response.AppendHeader("content-disposition", "attachment;filename=\"Report.csv\"");

            Response.Write(bytes);
            Response.End();
        }
Exemple #5
0
        public Task <IActionResult> ExportState(string startDate = "0", string endDate = "0")
        {
            var t_result = Task.Factory.StartNew <IActionResult>((arg) => {
                try
                {
                    var t_inputs = arg as Tuple <string, string>;
                    var invoices = _customRepo.GetCompanyStatus(
                        t_inputs.Item1 == "0" ? DateTime.MinValue : Convert.ToDateTime(t_inputs.Item1),
                        t_inputs.Item2 == "0" ? DateTime.Now : Convert.ToDateTime(t_inputs.Item2));


                    string requestLanguage = "EN";
                    var languageIdHeader   = this.Request.Headers["languageid"];
                    requestLanguage        = languageIdHeader.FirstOrDefault() ?? "es";
                    var excelData          = ExportUtility.GetExcelData <CompanyStateModel>(invoices, requestLanguage, this.languageKeys.ToList());
                    var excelStream        = ExcelImport.CreateXlsStream(
                        excelData.Item1,
                        excelData.Item2
                        );
                    if (invoices != null && excelStream != null && excelStream.Length > 0)
                    {
                        return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                    }
                    return(BadRequest(new { status = -1, message = "Documento no existe" }));
                }
                catch (Exception ex)
                {
                    return(Ok(new { status = -1, message = ex.Message }));
                }
            }, new Tuple <string, string>(startDate, endDate));

            return(t_result);
        }
        public IActionResult ExportToExcel(long branchOfficeId = 0, long warehouseId = 0, long productId = 0)
        {
            try
            {
                var data = _baseRepo.GetAll <Inventory>(x => x.Include(i => i.Product)
                                                        .Include(i => i.Warehouse)
                                                        .Include(i => i.BranchOffice)
                                                        .Include(i => i.Unit)
                                                        , y => y.Active == true &&
                                                        (branchOfficeId > 0 ? y.BranchOfficeId == branchOfficeId : y.BranchOfficeId > 0) &&
                                                        (warehouseId > 0 ? y.WarehouseId == warehouseId : y.WarehouseId > 0) &&
                                                        (productId > 0 ? y.ProductId == productId : y.ProductId > 0));
                string requestLanguage  = "EN";
                var    languageIdHeader = this.Request.Headers["languageid"];
                requestLanguage = languageIdHeader.FirstOrDefault() ?? "ES";
                var excelData   = ExportUtility.GetExcelData <Inventory>(data, requestLanguage, this.languageKeys.ToList());
                var excelStream = ExcelImport.CreateXlsStream(
                    excelData.Item1,
                    excelData.Item2
                    );
                if (data != null && excelStream != null && excelStream.Length > 0)
                {
                    return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                }
                return(BadRequest(new { status = -1, message = "Documento no existe" }));
            }

            catch (Exception ex)
            {
                return(Ok(new { status = -1, message = ex.Message }));
            }
        }
        public IActionResult GetTaxesReportExcel(string initialDate = "0", string endDate = "0")
        {
            try
            {
                DateTime?startDate = null;
                startDate = initialDate != "0" ? Convert.ToDateTime(initialDate) : startDate;

                DateTime?finalDate = null;
                finalDate = endDate != "0" ? Convert.ToDateTime(endDate) : finalDate;

                var    data             = businessStateRepository.GetTaxesReport(startDate, finalDate);
                string requestLanguage  = "EN";
                var    languageIdHeader = this.Request.Headers["languageid"];
                requestLanguage = languageIdHeader.FirstOrDefault() ?? "es";
                var excelData   = ExportUtility.GetExcelData <InvoiceTax>(data.SelectMany(x => x.Taxes), requestLanguage, this.languageKeys.ToList());
                var excelStream = ExcelImport.CreateXlsStream(
                    excelData.Item1,
                    excelData.Item2
                    );
                if (data != null && excelStream != null && excelStream.Length > 0)
                {
                    return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                }
                return(BadRequest(new { status = -1, message = "Documento no existe" }));
            }

            catch (Exception ex)
            {
                return(Ok(new { status = -1, message = ex.Message }));
            }
        }
        public Task <IActionResult> ExportComissionsReport([FromBody] ComissionsSearch search)
        {
            var t_result = Task.Factory.StartNew <IActionResult>((arg) => {
                try
                {
                    var t_inputs = arg as Tuple <ComissionsSearch, ISellerRepository>;
                    var invoices = t_inputs.Item1.ReportType == 0 ?
                                   t_inputs.Item2.SalesComissions(t_inputs.Item1) : t_inputs.Item2.PaymentsComissions(t_inputs.Item1);


                    string requestLanguage = "EN";
                    var languageIdHeader   = this.Request.Headers["languageid"];
                    requestLanguage        = languageIdHeader.FirstOrDefault() ?? "es";
                    var excelData          = ExportUtility.GetExcelData <ComissionDetail>(invoices.ComissionsByCyrrencies.SelectMany(x => x.Details), requestLanguage, this.languageKeys.ToList());
                    var excelStream        = ExcelImport.CreateXlsStream(
                        excelData.Item1,
                        excelData.Item2
                        );
                    if (invoices != null && excelStream != null && excelStream.Length > 0)
                    {
                        return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                    }
                    return(BadRequest(new { status = -1, message = "Documento no existe" }));
                }
                catch (Exception ex)
                {
                    return(Ok(new { status = -1, message = ex.Message }));
                }
            }, new Tuple <ComissionsSearch, ISellerRepository>(search, _repositoryFactory.GetCustomDataRepositories <ISellerRepository>()));

            return(t_result);
        }
        public IActionResult AccountStateExport(long customerId)
        {
            try
            {
                var    data             = _repositoryFactory.GetCustomDataRepositories <ICustomerBalanceRepository>().CustomerState(customerId);
                string requestLanguage  = "EN";
                var    languageIdHeader = this.Request.Headers["languageid"];
                requestLanguage = languageIdHeader.FirstOrDefault() ?? "es";
                var excelData   = ExportUtility.GetExcelData <CustomerStateModel>(data.Data, requestLanguage, this.languageKeys.ToList());
                var excelStream = ExcelImport.CreateXlsStream(
                    excelData.Item1,
                    excelData.Item2
                    );
                if (data != null && excelStream != null && excelStream.Length > 0)
                {
                    return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                }
                return(BadRequest(new { status = -1, message = "Documento no existe" }));
            }

            catch (Exception ex)
            {
                return(Ok(new { status = -1, message = ex.Message }));
            }
        }
Exemple #10
0
        public IActionResult GetOwedExpensesReport(long branchOfficeId = 0, long supplierId = 0, long currencyId = 0, string startDate = "0", string endDate = "0")
        {
            try
            {
                DateTime?start = null;
                start = startDate != "0" ? Convert.ToDateTime(startDate) : start;
                DateTime?end = null;
                end = endDate != "0" ? Convert.ToDateTime(endDate) : DateTime.Now;
                var    data             = _repo.GetDebsToPay(start, end, supplierId, currencyId, branchOfficeId);
                string requestLanguage  = "EN";
                var    languageIdHeader = this.Request.Headers["languageid"];
                requestLanguage = languageIdHeader.FirstOrDefault() ?? "es";
                var excelData   = ExportUtility.GetExcelData <Expense>(data, requestLanguage, this.languageKeys.ToList());
                var excelStream = ExcelImport.CreateXlsStream(
                    excelData.Item1,
                    excelData.Item2
                    );
                if (data != null && excelStream != null && excelStream.Length > 0)
                {
                    return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                }
                return(BadRequest(new { status = -1, message = "Documento no existe" }));
            }

            catch (Exception ex)
            {
                return(Ok(new { status = -1, message = ex.Message }));
            }
        }
Exemple #11
0
        public virtual IActionResult ExportToExcel()
        {
            try
            {
                var    data             = _baseRepo.GetAll <T>(x => x.Where(y => y.Active == true));
                string requestLanguage  = "EN";
                var    languageIdHeader = this.Request.Headers["languageid"];
                requestLanguage = languageIdHeader.FirstOrDefault() ?? "es";
                var excelData   = ExportUtility.GetExcelData <T>(data, requestLanguage, this.languageKeys.ToList());
                var excelStream = ExcelImport.CreateXlsStream(
                    excelData.Item1,
                    excelData.Item2
                    );
                if (data != null && excelStream != null && excelStream.Length > 0)
                {
                    return(File(excelStream.ToArray(), "application/octet-stream", $"{new T().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                }
                return(BadRequest(new { status = -1, message = "Documento no existe" }));
            }

            catch (Exception ex)
            {
                return(Ok(new { status = -1, message = ex.Message }));
            }
        }
Exemple #12
0
        bool WriteFileImage(HeightData source, string filename, FileFormat ff)
        {
            float[,] grid = source.GetDataGrid();
            IExporter exporter = new ImageGenerator(grid, source.cellSize, ff.GetImageType(), source.lowPoint, source.highPoint);

            ExportUtility.WriteFile(exporter, filename, ff);
            return(true);
        }
        public virtual Task <IActionResult> ExportReceipts(long branchOfficeId = 0, long customerId = 0, long currencyId = 0, long paymentTypeId = 0, string startDate = "0", string endDate = "0")
        {
            DateTime?start = new DateTime();

            if (startDate != "0")
            {
                start = Convert.ToDateTime(startDate);
            }
            else
            {
                start = null;
            }
            DateTime?end = new DateTime();

            if (endDate != "0")
            {
                end = Convert.ToDateTime(endDate);
            }
            else
            {
                end = null;
            }
            var t_result = Task.Factory.StartNew <IActionResult>((arg) => {
                try
                {
                    var t_inputs = arg as Tuple <long, long, long, long, DateTime?, DateTime?>;
                    var invoices = base._repositoryFactory.GetCustomDataRepositories <ICustomerPaymentRepository>().IncomesReport(
                        t_inputs.Item3,
                        t_inputs.Item1,
                        t_inputs.Item2,
                        t_inputs.Item4,
                        t_inputs.Item5,
                        t_inputs.Item6

                        );
                    string requestLanguage = "EN";
                    var languageIdHeader   = this.Request.Headers["languageid"];
                    requestLanguage        = languageIdHeader.FirstOrDefault() ?? "es";
                    var excelData          = ExportUtility.GetExcelData <CustomerPayment>(invoices, requestLanguage, this.languageKeys.ToList());
                    var excelStream        = ExcelImport.CreateXlsStream(
                        excelData.Item1,
                        excelData.Item2
                        );
                    if (invoices != null && excelStream != null && excelStream.Length > 0)
                    {
                        return(File(excelStream.ToArray(), "application/octet-stream", $"{new Product().GetType().Name}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls"));
                    }
                    return(BadRequest(new { status = -1, message = "Documento no existe" }));
                }
                catch (Exception ex)
                {
                    return(Ok(new { status = -1, message = ex.Message }));
                }
            }, new Tuple <long, long, long, long, DateTime?, DateTime?>(customerId, currencyId, branchOfficeId, paymentTypeId, start, end));

            return(t_result);
        }
Exemple #14
0
        void AssertExport(HeightData data, string filetype, string path)
        {
            var format = ExportUtility.GetFormatFromIdenfifier(filetype);

            path = Path.ChangeExtension(Path.Combine(outputPath, path), format.Extension);
            var job = new ExportJob(data, format, new ExportSettings(), outputPath, path);

            job.Export();
            Assert.IsTrue(File.Exists(path), "Written file not found");
        }
        /// <summary>
        /// Exports the report data to a comma seperated value file (csv)
        /// </summary>
        /// <param name="reportPath">The folder and file name complete path to where the report data
        /// is to be exported to</param>
        protected virtual void ExportCSVReport(string reportPath)
        {
            ExportUtility exp = new ExportUtility();

            try
            {
                SetReportParameters();
                exp.ExportDataSetToCSV(ReportData, reportPath);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("An unexpected error occurred trying to export the report: " + ex.ToString(), ex);
            }
        }
Exemple #16
0
        /// <summary>
        /// Generic Export
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        public virtual ActionResult Export(List <FilterEntity> filters, string format)
        {
            //1. Data
            //var list= GetList();


            //2. Get View
            var view     = ViewService.Get(typeof(Entity), typeof(Tree));
            var treeView = view.Layout as Tree;


            string[] propiedades = (from m in treeView.Fields
                                    select m.Name).ToArray();;

            MemberInfo[] Members = null;

            BindingFlags memberFlags = BindingFlags.Public | BindingFlags.Instance;

            var type = typeof(Entity);

            Members = type.GetProperties(memberFlags);

            MemberInfo[] membersFilter = (from m in Members
                                          where propiedades.Any(val => m.Name.ToUpper() == val.ToUpper())
                                          select m).ToArray();


            var data = EntityService.GetList(filters).ToList();

            //TODO: ExportUtility.ExportExcel. Internamente se usa EPPlus el cual utiliza DescriptionAttribute de las propiedades
            //pasadas "membersFilter" para establecer los nombres de las columnas
            //se deberia adaptar para soportar el valor de "String" del campo en las vistas

            var file = ExportUtility.ExportExcel <Entity>(data, membersFilter);

            if (file != null)
            {
                //TODO: Nombre mas fecha ??
                var nameFile = string.Format("{0}.xlsx", typeof(Entity).GetDescription());

                return(new FileContentResult(file,
                                             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName = nameFile
                });
            }

            return(View("Index"));
        }
Exemple #17
0
 public override bool Export(ExportJob job)
 {
     if (job.format.IsFormat("MCR") || job.format.IsFormat("MCR-RAW"))
     {
         return(WriteFileMCA(job, !job.format.IsFormat("MCR-RAW"), job.settings.GetCustomSetting("mcaUseSplatmaps", false)));
     }
     else if (job.format.IsFormat("IMG_MCR"))
     {
         ExportUtility.WriteFile(new OverviewmapExporter(job.data.filename, true), job.FilePath, job.format);
     }
     else if (job.format.IsFormat("MCW"))
     {
         return(WriteWorldSave(job, true, job.settings.GetCustomSetting("mcaUseSplatmaps", false)));
     }
     return(false);
 }
Exemple #18
0
 static bool GetExportSettings(bool batch)
 {
     if (!GetExportOptions(batch))
     {
         return(false);
     }
     while (!ExportUtility.ValidateExportSettings(currentJob.exportSettings, currentJob.CurrentData))
     {
         WriteError("Cannot export with the current settings / format!");
         if (!GetExportOptions(batch))
         {
             return(false);
         }
     }
     return(true);
 }
Exemple #19
0
 public static void Initialize(string pluginPath)
 {
     ConsoleOutput.Initialize();
     ImportManager.RegisterHandler(new StandardImporter());
     ExportUtility.RegisterHandler(new StandardExporter());
     CommandHandler.commandHandlers.Add(new StandardCommands());
     if (!string.IsNullOrEmpty(pluginPath))
     {
         PluginLoader.LoadPlugins(pluginPath);
     }
     else
     {
         WriteLine("Plugin loading has been disabled");
     }
     CommandHandler.Initialize();
     isInitialized = true;
 }
Exemple #20
0
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            context.Response.ContentType = "text/plain";
            string DTdata   = context.Request["DTdata"];
            string criteria = context.Request.Form["criteria"];
            string filename = context.Request.Form["filename"];
            //string filename = HttpContext.Current.Server.UrlPathEncode(context.Request.Form["filename"]); //中文檔名

            DataTable dt       = JsonHelper.JsonToDataTable(DTdata);
            bool      bUtility = true;

            if (bUtility)
            {
                #region 蓬益
                ExportUtility exportUtility = new ExportUtility();
                exportUtility.Data      = dt;
                exportUtility.SheetName = filename;
                //exportUtility.FileName = filename + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                exportUtility.FileName = filename + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                //exportUtility.ExportExcel(); // closedXML
                exportUtility.ExportExcelNPOI();
                #endregion
            }
            else
            {
                MemoryStream ms = NPOIHelper.RenderDataTableToExcel(dt) as MemoryStream;
                context.Response.Clear();

                // xlsx
                //context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                // xls
                //context.Response.ContentType = "application/vnd.ms-excel";

                // 設定強制下載標頭。
                //Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", fileName));
                context.Response.AddHeader("Content-Disposition", "attachment; filename= ExportFile.xls");
                // 輸出檔案。
                context.Response.BinaryWrite(ms.ToArray());
                ms.Close();
                ms.Dispose();
                context.Response.End();
            }
        }
Exemple #21
0
 protected void LBExport2Excel_Click(object sender, EventArgs e)
 {
     try
     {
         if (DT == null)
         {
             throw new Exception("Data not available to export to excel!!!");
         }
         else
         {
             DS.Tables.Add(DT);
             ExportUtility.exportToExcel(DS, "EmployeeData");
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error Occured", ex.Message);
     }
 }
Exemple #22
0
        bool WriteFile3D(HeightData source, string filename, FileFormat ff)
        {
            var meshList = new List <(List <Vector3> verts, List <int> tris, List <Vector2> uvs)>();
            int sizeX    = source.GridWidth - 1;
            int sizeY    = source.GridHeight - 1;
            int splitX   = (int)Math.Ceiling(sizeX / 128f);
            int splitY   = (int)Math.Ceiling(sizeY / 128f);
            int y        = 0;

            while (y < sizeY)
            {
                int cellsY = (int)Math.Ceiling(sizeY / (float)splitY);
                int x      = 0;
                while (x < sizeX)
                {
                    int cellsX = (int)Math.Ceiling(sizeX / (float)splitX);
                    meshList.Add(CreateMeshData(source, x, y, x + cellsX, y + cellsY));
                    x += cellsX;
                }
                y += cellsY;
            }
            try {
                IExporter exporter;
                if (exported3dFiles < 50)
                {
                    exporter = new Aspose3DExporter(meshList);
                }
                else
                {
                    ConsoleOutput.WriteWarning("Aspose3D's export limit was reached! Attempting to export using Assimp, which may throw an error.");
                    exporter = new Assimp3DExporter(meshList);
                }
                ExportUtility.WriteFile(exporter, filename, ff);
            } catch (Exception e) {
                ConsoleOutput.WriteError("Failed to create 3D file!");
                ConsoleOutput.WriteLine(e.ToString());
                return(false);
            }
            exported3dFiles++;
            return(true);
        }
        public HttpResponseMessage ExportAdditionalReport([FromBody] AdditionalReportCriteria data)
        {
            //ExcelPackage pckg = new ExcelPackage();
            //try
            //{
            //    ReportWriter writer = new ExcelWriter();
            //    writer.SetWriter = pckg;
            //    NMART.BusinessLayer.ExportAdditionalReport.ExportReport(writer, data);
            //}
            //catch (Exception ex)
            //{
            //    if (ex.Message == "INVALID_API_PARAMS")
            //        return new HttpResponseMessage(HttpStatusCode.NoContent);
            //    else
            //        return new HttpResponseMessage() { Content = new StringContent(ex.Message), RequestMessage = Request };
            //}
            //MemoryStream stream = new MemoryStream();
            //pckg.SaveAs(stream);
            //return CreateExcelResponse(stream, string.Format("{0}_{1}_{2}.xlsx", data.ApiResource, data.REPORT_TYPE.ToString(), DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss")));

            DAILYBL dailyBL = new DAILYBL();
            DataSet ds      = null;

            ds = dailyBL.DailyHoursReport("All", data.DailyTypeIDs, "All", "All", data.StartDate, "All");
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            {
                return(new HttpResponseMessage()
                {
                    Content = new StringContent("No Data"), RequestMessage = Request
                });
            }

            MemoryStream        stream   = dailyBL.GetStreamForHoursReport(ds);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            return(ExportUtility.CreateExcelResponse(Request, response, stream, "abc.xlsx"));
        }
Exemple #24
0
        internal static void LoadPlugins(string pluginPath)
        {
            loadedPlugins = new Dictionary <string, HMConPlugin>();
            var dllFiles = Directory.GetFiles(pluginPath, "*.dll");

            foreach (var path in dllFiles)
            {
                try
                {
                    var assembly = Assembly.LoadFrom(path);
                    foreach (var t in assembly.GetTypes())
                    {
                        if (t.BaseType != null && t.BaseType.Name == typeof(HMConPlugin).Name && !t.IsAbstract)
                        {
                            var    plugin = (HMConPlugin)Activator.CreateInstance(t);
                            string info   = "";

                            var i = plugin.GetImportHandler();
                            if (i != null)
                            {
                                ImportManager.RegisterHandler(i);
                                info += info.Length > 0 ? "+I" : "I";
                            }
                            var e = plugin.GetExportHandler();
                            if (e != null)
                            {
                                ExportUtility.RegisterHandler(e);
                                info += info.Length > 0 ? "+E" : "E";
                            }
                            var c = plugin.GetCommandHandler();
                            if (c != null)
                            {
                                CommandHandler.commandHandlers.Add(c);
                                info += info.Length > 0 ? "+C" : "C";
                            }


                            var    attribute = t.GetCustomAttribute <PluginInfoAttribute>();
                            string pluginID;
                            string pluginAttr;
                            if (attribute != null)
                            {
                                pluginAttr = attribute.Name;
                                pluginID   = attribute.ID.ToUpper();
                            }
                            else
                            {
                                ConsoleOutput.WriteWarning($"Plugin with class '{t.FullName}' does not specify a Plugin name!");
                                pluginID   = "[" + t.Name + "]";
                                pluginAttr = t.Name;
                            }
                            if (loadedPlugins.ContainsKey(pluginID))
                            {
                                continue;
                            }
                            loadedPlugins.Add(pluginID, plugin);
                            ConsoleOutput.WriteLine($"Loaded Plugin '{pluginAttr}' [{info}]");
                        }
                    }
                    //ConsoleOutput.WriteWarning("Not a plugin dll: " + path);
                }
                catch
                {
                    //ConsoleOutput.WriteWarning("Failed to load dll: " + path);
                }
            }
        }
        public override void OnInspectorGUI()
        {
            if (!hasCheckedRenderType)
            {
                CheckGazeRenderType();
                hasCheckedRenderType = true;
            }

            var p = (CognitiveVR_Preferences)target;

            p.ApplicationKey   = EditorGUILayout.TextField("Application Key", p.ApplicationKey);
            p.EnableLogging    = EditorGUILayout.Toggle("Enable Logging", p.EnableLogging);
            p.EnableDevLogging = EditorGUILayout.Toggle("Enable Development Logging", p.EnableDevLogging);

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("3D Player Tracking", EditorStyles.boldLabel);
            //TODO change tooltip based on selected gaze type
            p.GazeType = (GazeType)EditorGUILayout.EnumPopup("Gaze Type", p.GazeType);
            if (GUI.changed)
            {
                CheckGazeRenderType();
            }
            p.SnapshotInterval            = EditorGUILayout.FloatField("Snapshot Interval", p.SnapshotInterval);
            p.DynamicObjectSearchInParent = EditorGUILayout.Toggle(new GUIContent("Dynamic Object Search in Parent", "When capturing gaze on a Dynamic Object, also search in the collider's parent for the dynamic object component"), p.DynamicObjectSearchInParent);

            bool eyetracking = false;

#if CVR_TOBIIVR || CVR_FOVE || CVR_NEURABLE || CVR_PUPIL || CVR_AH || CVR_SNAPDRAGON || CVR_VIVEPROEYE || CVR_VARJO
            eyetracking = true;
#endif

            if (p.GazeType == GazeType.Physics || eyetracking)
            {
                LayerMask gazeMask = new LayerMask();
                gazeMask.value  = p.GazeLayerMask;
                gazeMask        = EditorGUILayout.MaskField("Gaze Layer Mask", gazeMask, (UnityEditorInternal.InternalEditorUtility.layers));
                p.GazeLayerMask = gazeMask.value;
            }

            LayerMask dynamicMask = new LayerMask();
            dynamicMask.value  = p.DynamicLayerMask;
            dynamicMask        = EditorGUILayout.MaskField("Dynamic Object Layer Mask", dynamicMask, (UnityEditorInternal.InternalEditorUtility.layers));
            p.DynamicLayerMask = dynamicMask.value;

            p.TrackGPSLocation = EditorGUILayout.Toggle(new GUIContent("Track GPS Location", "Record GPS location and compass direction at the interval below"), p.TrackGPSLocation);

            EditorGUI.BeginDisabledGroup(!p.TrackGPSLocation);
            EditorGUI.indentLevel++;
            gpsFoldout = EditorGUILayout.Foldout(gpsFoldout, "GPS Options");
            if (gpsFoldout)
            {
                p.SyncGPSWithGaze = EditorGUILayout.Toggle(new GUIContent("Sync with Player Update", "Request new GPS location every time the player position and gaze is recorded"), p.SyncGPSWithGaze);
                EditorGUI.BeginDisabledGroup(p.SyncGPSWithGaze);
                p.GPSInterval = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("GPS Update Interval", "Interval in seconds to record new GPS location data"), p.GPSInterval), 0.1f, 60f);
                EditorGUI.EndDisabledGroup();
                p.GPSAccuracy = Mathf.Clamp(EditorGUILayout.FloatField(new GUIContent("GPS Accuracy", "Desired accuracy in meters. Using higher values like 500 may not require GPS and may save battery power"), p.GPSAccuracy), 1f, 500f);
            }
            EditorGUI.indentLevel--;
            EditorGUI.EndDisabledGroup();

            p.RecordFloorPosition = EditorGUILayout.Toggle(new GUIContent("Record Floor Position", "Includes the floor position below the HMD in a VR experience"), p.RecordFloorPosition);

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("360 Player Tracking", EditorStyles.boldLabel);
            p.SnapshotInterval = EditorGUILayout.FloatField("Snapshot Interval", p.SnapshotInterval);
            p.SnapshotInterval = Mathf.Clamp(p.SnapshotInterval, 0.1f, 10);

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Sending Data Batches", EditorStyles.boldLabel);

            //gaze
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Gaze", EditorStyles.boldLabel);
            EditorGUI.indentLevel--;
            p.GazeSnapshotCount = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Gaze Snapshot Batch Size", "The number of Gaze datapoints to record before automatically sending a web request to the dashboard"), p.GazeSnapshotCount), 64, 1500);

            //transactions
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Events", EditorStyles.boldLabel);
            EditorGUI.indentLevel--;
            p.TransactionSnapshotCount        = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Event Snapshot Batch Size", "The number of Events to record before automatically sending a web request to the dashboard"), p.TransactionSnapshotCount), 1, 1000);
            p.TransactionExtremeSnapshotCount = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Event Extreme Batch Size", "Threshold for ignoring the Event Minimum Timer. If this many Events have been recorded, immediately send"), p.TransactionExtremeSnapshotCount), p.TransactionSnapshotCount, 1000);
            p.TransactionSnapshotMinTimer     = EditorGUILayout.IntField(new GUIContent("Event Minimum Timer", "Time (in seconds) that must be elapsed before sending a new batch of Event data. Ignored if the batch size reaches Event Extreme Limit"), Mathf.Clamp(p.TransactionSnapshotMinTimer, 1, 10));
            p.TransactionSnapshotMaxTimer     = EditorGUILayout.IntField(new GUIContent("Event Automatic Send Timer", "The time (in seconds) to automatically send any outstanding Event data"), Mathf.Clamp(p.TransactionSnapshotMaxTimer, p.TransactionSnapshotMinTimer, 60));

            //dynamics
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Dynamics", EditorStyles.boldLabel);
            EditorGUI.indentLevel--;
            p.DynamicSnapshotCount        = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Dynamic Snapshot Batch Size", "The number of Dynamic snapshots and manifest entries to record before automatically sending a web request to the dashboard"), p.DynamicSnapshotCount), 16, 1500);
            p.DynamicExtremeSnapshotCount = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Dynamic Extreme Batch Size", "Threshold for ignoring the Dynamic Minimum Timer. If this many Dynamic snapshots have been recorded, immediately send"), p.DynamicExtremeSnapshotCount), p.DynamicSnapshotCount, 1500);
            p.DynamicSnapshotMinTimer     = EditorGUILayout.IntField(new GUIContent("Dynamic Minimum Timer", "Time (in seconds) that must be elapsed before sending a new batch of Dynamic data. Ignored if the batch size reaches Dynamic Extreme Limit"), Mathf.Clamp(p.DynamicSnapshotMinTimer, 1, 60));
            p.DynamicSnapshotMaxTimer     = EditorGUILayout.IntField(new GUIContent("Dynamic Automatic Send Timer", "The time (in seconds) to automatically send any outstanding Dynamic snapshots or Manifest entries"), Mathf.Clamp(p.DynamicSnapshotMaxTimer, 1, 600));

            //sensors
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Sensors", EditorStyles.boldLabel);
            EditorGUI.indentLevel--;
            p.SensorSnapshotCount        = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Sensor Snapshot Batch Size", "The number of Sensor datapoints to record before automatically sending a web request to the dashboard"), p.SensorSnapshotCount), 64, 1500);
            p.SensorExtremeSnapshotCount = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Sensor Extreme Batch Size", "Threshold for ignoring the Sensor Minimum Timer. If this many Sensor datapoints have been recorded, immediately send"), p.SensorExtremeSnapshotCount), p.SensorSnapshotCount, 1500);
            p.SensorSnapshotMinTimer     = EditorGUILayout.IntField(new GUIContent("Sensor Minimum Timer", "Time (in seconds) that must be elapsed before sending a new batch of Sensor data. Ignored if the batch size reaches Sensor Extreme Limit"), Mathf.Clamp(p.SensorSnapshotMinTimer, 1, 60));
            p.SensorSnapshotMaxTimer     = EditorGUILayout.IntField(new GUIContent("Sensor Automatic Send Timer", "The time (in seconds) to automatically send any outstanding Sensor data"), Mathf.Clamp(p.SensorSnapshotMaxTimer, p.SensorSnapshotMinTimer, 600));

            //fixations
            EditorGUI.indentLevel++;
            EditorGUILayout.LabelField("Fixations", EditorStyles.boldLabel);
            EditorGUI.indentLevel--;
            p.FixationSnapshotCount        = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Fixation Snapshot Batch Size", "The number of Fixations to record before automatically sending a web request to the dashboard"), p.FixationSnapshotCount), 1, 1000);
            p.FixationExtremeSnapshotCount = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Fixation Extreme Batch Size", "Threshold for ignoring the Fixation Minimum Timer. If this many Fixations have been recorded, immediately send"), p.FixationExtremeSnapshotCount), p.FixationSnapshotCount, 1000);
            p.FixationSnapshotMinTimer     = EditorGUILayout.IntField(new GUIContent("Fixation Minimum Timer", "Time (in seconds) that must be elapsed before sending a new batch of Fixation data. Ignored if the batch size reaches Fixation Extreme Limit"), Mathf.Clamp(p.FixationSnapshotMinTimer, 1, 10));
            p.FixationSnapshotMaxTimer     = EditorGUILayout.IntField(new GUIContent("Fixation Automatic Send Timer", "The time (in seconds) to automatically send any outstanding Fixation data"), Mathf.Clamp(p.FixationSnapshotMaxTimer, p.FixationSnapshotMinTimer, 60));

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Local Data Cache", EditorStyles.boldLabel);
            //local storage
            GUILayout.BeginHorizontal();
            p.LocalStorage = EditorGUILayout.Toggle("Save data to Local Cache if no internet connection", p.LocalStorage);
            if (GUILayout.Button("Open Local Cache Folder"))
            {
                EditorUtility.RevealInFinder(Application.persistentDataPath);
            }
            GUILayout.EndHorizontal();
            EditorGUI.BeginDisabledGroup(!p.LocalStorage);
            GUILayout.BeginHorizontal();
            p.LocalDataCacheSize = EditorGUILayout.LongField("Cache Size", p.LocalDataCacheSize);
            if (p.LocalDataCacheSize < 1048576)
            {
                p.LocalDataCacheSize = 1048576;
            }                                                                       //at least 1mb of storage (1048576 bytes)
            EditorGUILayout.LabelField(EditorUtility.FormatBytes(p.LocalDataCacheSize), GUILayout.Width(100));
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Sending Data", EditorStyles.boldLabel);
            CognitiveVR_Preferences.Instance.Protocol  = EditorGUILayout.TextField(new GUIContent("Custom Protocol", "https"), CognitiveVR_Preferences.Instance.Protocol);
            CognitiveVR_Preferences.Instance.Gateway   = EditorGUILayout.TextField(new GUIContent("Custom Gateway", "data.cognitive3d.com"), CognitiveVR_Preferences.Instance.Gateway);
            CognitiveVR_Preferences.Instance.Viewer    = EditorGUILayout.TextField(new GUIContent("Custom Viewer", "viewer.cognitive3d.com/scene/"), CognitiveVR_Preferences.Instance.Viewer);
            CognitiveVR_Preferences.Instance.Dashboard = EditorGUILayout.TextField(new GUIContent("Custom Dashboard", "app.cognitive3d.com"), CognitiveVR_Preferences.Instance.Dashboard);
            p.SendDataOnHMDRemove = EditorGUILayout.Toggle("Send Data on HMD Remove", p.SendDataOnHMDRemove);
            p.SendDataOnLevelLoad = EditorGUILayout.Toggle("Send Data on Level Load", p.SendDataOnLevelLoad);
            p.SendDataOnQuit      = EditorGUILayout.Toggle("Send Data on Quit", p.SendDataOnQuit);
            p.SendDataOnPause     = EditorGUILayout.Toggle("Send Data on Pause", p.SendDataOnPause);
            p.SendDataOnHotkey    = EditorGUILayout.Toggle("Send Data on Hotkey", p.SendDataOnHotkey);
            EditorGUI.indentLevel++;
            EditorGUI.BeginDisabledGroup(!p.SendDataOnHotkey);
            GUILayout.BeginHorizontal();

            p.SendDataHotkey = (KeyCode)EditorGUILayout.EnumPopup("Hotkey", p.SendDataHotkey);

            if (p.HotkeyShift)
            {
                GUI.color = Color.green;
            }
            if (GUILayout.Button("Shift", EditorStyles.miniButtonLeft))
            {
                p.HotkeyShift = !p.HotkeyShift;
            }
            GUI.color = Color.white;

            if (p.HotkeyCtrl)
            {
                GUI.color = Color.green;
            }
            if (GUILayout.Button("Ctrl", EditorStyles.miniButtonMid))
            {
                p.HotkeyCtrl = !p.HotkeyCtrl;
            }
            GUI.color = Color.white;

            if (p.HotkeyAlt)
            {
                GUI.color = Color.green;
            }
            if (GUILayout.Button("Alt", EditorStyles.miniButtonRight))
            {
                p.HotkeyAlt = !p.HotkeyAlt;
            }
            GUI.color = Color.white;

            /*if (remapHotkey)
             * {
             *  GUILayout.Button("Any Key", EditorStyles.miniButton, GUILayout.Width(100));
             *  Event e = Event.current;
             *
             *  if (e.type == EventType.keyDown && e.keyCode != KeyCode.None && e.keyCode != KeyCode.LeftShift && e.keyCode != KeyCode.RightShift && e.keyCode != KeyCode.LeftControl && e.keyCode != KeyCode.RightControl && e.keyCode != KeyCode.LeftAlt && e.keyCode != KeyCode.RightAlt)
             *  {
             *      p.HotkeyAlt = e.alt;
             *      p.HotkeyShift = e.shift;
             *      p.HotkeyCtrl = e.control;
             *      p.SendDataHotkey = e.keyCode;
             *      remapHotkey = false;
             *      Repaint();
             *  }
             * }
             * else
             * {
             *  if (GUILayout.Button("Remap", EditorStyles.miniButton,GUILayout.Width(100)))
             *  {
             *      remapHotkey = true;
             *  }
             * }*/

            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();
            EditorGUI.indentLevel--;

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Scene Export", EditorStyles.boldLabel);
            EditorGUI.indentLevel++;

            var v = CognitiveVR_Preferences.FindCurrentScene();
            if (v == null || string.IsNullOrEmpty(v.SceneId))
            {
                EditorGUILayout.LabelField("Current Scene: " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "     Version: not uploaded");
            }
            else
            {
                EditorGUILayout.LabelField("Current Scene: " + v.SceneName + "     Version: " + v.VersionNumber);
            }
            EditorGUILayout.Space();

            GUIContent[] textureQualityNames = new GUIContent[] { new GUIContent("Full"), new GUIContent("Half"), new GUIContent("Quarter") /*, new GUIContent("Eighth"), new GUIContent("Sixteenth"), new GUIContent("Thirty Second"), new GUIContent("Sixty Fourth") */ };
            int[]        textureQualities    = new int[] { 1, 2, 4 /*, 8, 16, 32, 64 */ };
            p.TextureResize = EditorGUILayout.IntPopup(new GUIContent("Texture Export Quality", "Reduce textures when uploading to scene explorer"), p.TextureResize, textureQualityNames, textureQualities);
            //EditorCore.ExportSettings.TextureQuality = EditorGUILayout.IntPopup(new GUIContent("Texture Export Quality", "Reduce textures when uploading to scene explorer"), EditorCore.ExportSettings.TextureQuality, textureQualityNames, textureQualities);
            p.ExportSceneLODLowest = EditorGUILayout.Toggle("Export Lowest LOD from LODGroup components", p.ExportSceneLODLowest);
            p.ExportAOMaps         = EditorGUILayout.Toggle("Export AO Maps", p.ExportAOMaps);
            GUILayout.BeginHorizontal();
            //GUILayout.Space(15);

            //TODO texture export settings

            //the full process
            //refresh scene versions
            //save screenshot
            //export scene
            //decimate scene
            //confirm upload of scene. new scene? new version?
            //export dynamics
            //confirm uploading dynamics
            //confirm upload manifest

            if (GUILayout.Button("Export", "ButtonLeft"))
            {
                if (string.IsNullOrEmpty(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name))
                {
                    if (EditorUtility.DisplayDialog("Export Failed", "Cannot export scene that is not saved.\n\nDo you want to save now?", "Save", "Cancel"))
                    {
                        if (UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes())
                        {
                        }
                        else
                        {
                            return;//cancel from save scene window
                        }
                    }
                    else
                    {
                        return;//cancel from 'do you want to save' popup
                    }
                }
                ExportUtility.ExportGLTFScene();

                string fullName             = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name;
                string objPath              = EditorCore.GetSubDirectoryPath(fullName);
                string jsonSettingsContents = "{ \"scale\":1,\"sceneName\":\"" + fullName + "\",\"sdkVersion\":\"" + Core.SDK_VERSION + "\"}";
                System.IO.File.WriteAllText(objPath + "settings.json", jsonSettingsContents);

                string debugContent = DebugInformationWindow.GetDebugContents();
                System.IO.File.WriteAllText(objPath + "debug.log", debugContent);
                CognitiveVR_Preferences.AddSceneSettings(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
                UnityEditor.AssetDatabase.SaveAssets();
            }

            bool hasUploadFiles = EditorCore.HasSceneExportFolder(CognitiveVR_Preferences.FindCurrentScene());

            EditorGUI.BeginDisabledGroup(!hasUploadFiles);
            if (GUILayout.Button("Upload", "ButtonRight"))
            {
                System.Action completedmanifestupload = delegate()
                {
                    ExportUtility.UploadAllDynamicObjectMeshes(true);
                };

                System.Action completedRefreshSceneVersion2 = delegate()
                {
                    ManageDynamicObjects.AggregationManifest manifest = new ManageDynamicObjects.AggregationManifest();
                    ManageDynamicObjects.AddOrReplaceDynamic(manifest, ManageDynamicObjects.GetDynamicObjectsInScene());
                    ManageDynamicObjects.UploadManifest(manifest, completedmanifestupload);
                };

                //upload dynamics
                System.Action completeSceneUpload = delegate() {
                    EditorCore.RefreshSceneVersion(completedRefreshSceneVersion2); //likely completed in previous step, but just in case
                };

                //upload scene
                System.Action completedRefreshSceneVersion1 = delegate() {
                    CognitiveVR_Preferences.SceneSettings current = CognitiveVR_Preferences.FindCurrentScene();

                    if (current == null || string.IsNullOrEmpty(current.SceneId))
                    {
                        //new scene
                        if (EditorUtility.DisplayDialog("Upload New Scene", "Upload " + current.SceneName + " to SceneExplorer?", "Ok", "Cancel"))
                        {
                            ExportUtility.UploadDecimatedScene(current, completeSceneUpload);
                        }
                    }
                    else
                    {
                        //new version
                        if (EditorUtility.DisplayDialog("Upload New Version", "Upload a new version of this existing scene? Will archive previous version", "Ok", "Cancel"))
                        {
                            ExportUtility.UploadDecimatedScene(current, completeSceneUpload);
                        }
                    }
                };

                //get the latest verion of the scene
                if (string.IsNullOrEmpty(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name))
                {
                    if (EditorUtility.DisplayDialog("Upload Failed", "Cannot upload scene that is not saved.\n\nDo you want to save now?", "Save", "Cancel"))
                    {
                        if (UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes())
                        {
                            EditorCore.RefreshSceneVersion(completedRefreshSceneVersion1);
                        }
                        else
                        {
                            return;//cancel from save scene window
                        }
                    }
                    else
                    {
                        return;//cancel from 'do you want to save' popup
                    }
                }
                else
                {
                    EditorCore.RefreshSceneVersion(completedRefreshSceneVersion1);
                }
            }

            GUIContent ButtonContent = new GUIContent("Upload Screenshot");
            if (v == null)
            {
                GUILayout.Button(ButtonContent);
            }
            else
            {
                if (GUILayout.Button(ButtonContent))
                {
                    EditorCore.UploadCustomScreenshot();
                }
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.EndDisabledGroup();
            EditorGUI.indentLevel--;
            GUILayout.EndHorizontal();

            if (GUILayout.Button(new GUIContent("Refresh Latest Scene Versions", "Get the latest versionnumber and versionid for this scene"))) //ask scene explorer for all the versions of this active scene. happens automatically post scene upload
            {
                EditorCore.RefreshSceneVersion(null);
            }

            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(serializedObject.FindProperty("sceneSettings"), true);
            serializedObject.ApplyModifiedProperties();
            serializedObject.Update();

            if (GUI.changed)
            {
                EditorUtility.SetDirty(p);
            }
        }
Exemple #26
0
        private void OnGUI()
        {
            if (needsRefreshDevKey == true)
            {
                EditorCore.CheckForExpiredDeveloperKey(GetDevKeyResponse);
                needsRefreshDevKey = false;
            }
            GUI.skin = EditorCore.WizardGUISkin;

            GUI.DrawTexture(new Rect(0, 0, 500, 550), EditorGUIUtility.whiteTexture);

            var currentscene = CognitiveVR_Preferences.FindCurrentScene();

            if (string.IsNullOrEmpty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name))
            {
                GUI.Label(steptitlerect, "DYNAMIC OBJECTS   Scene Not Saved", "steptitle");
            }
            else if (currentscene == null || string.IsNullOrEmpty(currentscene.SceneId))
            {
                GUI.Label(steptitlerect, "DYNAMIC OBJECTS   Scene Not Uploaded", "steptitle");
            }
            else
            {
                GUI.Label(steptitlerect, "DYNAMIC OBJECTS   " + currentscene.SceneName + " Version: " + currentscene.VersionNumber, "steptitle");
            }

            GUI.Label(new Rect(30, 45, 440, 440), "These are the active <color=#8A9EB7FF>Dynamic Object components</color> currently found in your scene.", "boldlabel");

            //headers
            Rect mesh = new Rect(30, 95, 120, 30);

            GUI.Label(mesh, "Mesh Name", "dynamicheader");
            Rect gameobject = new Rect(190, 95, 120, 30);

            GUI.Label(gameobject, "GameObject", "dynamicheader");
            //Rect ids = new Rect(320, 95, 120, 30);
            //GUI.Label(ids, "Ids", "dynamicheader");
            Rect uploaded = new Rect(380, 95, 120, 30);

            GUI.Label(uploaded, "Exported Mesh", "dynamicheader");
            //IMPROVEMENT get list of uploaded mesh names from dashboard


            //content
            DynamicObject[] tempdynamics = GetDynamicObjects;

            if (tempdynamics.Length == 0)
            {
                GUI.Label(new Rect(30, 120, 420, 270), "No objects found.\n\nHave you attached any Dynamic Object components to objects?\n\nAre they active in your hierarchy?", "button_disabledtext");
            }

            DynamicObjectIdPool[] poolAssets = EditorCore.GetDynamicObjectPoolAssets;


            Rect innerScrollSize = new Rect(30, 0, 420, (tempdynamics.Length + poolAssets.Length) * 30);

            dynamicScrollPosition = GUI.BeginScrollView(new Rect(30, 120, 440, 285), dynamicScrollPosition, innerScrollSize, false, true);

            Rect dynamicrect;
            int  GuiOffset = 0;

            for (; GuiOffset < tempdynamics.Length; GuiOffset++)
            {
                if (tempdynamics[GuiOffset] == null)
                {
                    RefreshSceneDynamics(); GUI.EndScrollView(); return;
                }
                dynamicrect = new Rect(30, GuiOffset * 30, 460, 30);
                DrawDynamicObject(tempdynamics[GuiOffset], dynamicrect, GuiOffset % 2 == 0);
            }
            for (int i = 0; i < poolAssets.Length; i++)
            {
                //if (poolAssets[i] == null) { RefreshSceneDynamics(); GUI.EndScrollView(); return; }
                dynamicrect = new Rect(30, (i + GuiOffset) * 30, 460, 30);
                DrawDynamicObjectPool(poolAssets[i], dynamicrect, (i + GuiOffset) % 2 == 0);
            }
            GUI.EndScrollView();
            GUI.Box(new Rect(30, 120, 425, 285), "", "box_sharp_alpha");

            //buttons

            string scenename     = "Not Saved";
            int    versionnumber = 0;

            //string buttontextstyle = "button_bluetext";
            if (currentscene == null || string.IsNullOrEmpty(currentscene.SceneId))
            {
                //buttontextstyle = "button_disabledtext";
            }
            else
            {
                scenename     = currentscene.SceneName;
                versionnumber = currentscene.VersionNumber;
            }

            int selectionCount = 0;

            foreach (var v in Selection.gameObjects)
            {
                if (v.GetComponentInChildren <DynamicObject>())
                {
                    selectionCount++;
                }
            }

            //IMPROVEMENT enable mesh upload from selected dynamic object id pool that has exported mesh files
            //if (Selection.activeObject.GetType() == typeof(DynamicObjectIdPool))
            //{
            //    var pool = Selection.activeObject as DynamicObjectIdPool;
            //    if (EditorCore.HasDynamicExportFiles(pool.MeshName))
            //    {
            //        selectionCount++;
            //    }
            //}

            //texture resolution

            if (CognitiveVR_Preferences.Instance.TextureResize > 4)
            {
                CognitiveVR_Preferences.Instance.TextureResize = 4;
            }

            //resolution settings here
            EditorGUI.BeginDisabledGroup(DisableButtons);
            if (GUI.Button(new Rect(30, 415, 140, 35), new GUIContent("1/4 Resolution", DisableButtons?"":"Quarter resolution of dynamic object textures"), CognitiveVR_Preferences.Instance.TextureResize == 4 ? "button_blueoutline" : "button_disabledtext"))
            {
                CognitiveVR_Preferences.Instance.TextureResize = 4;
            }
            if (CognitiveVR_Preferences.Instance.TextureResize != 4)
            {
                GUI.Box(new Rect(30, 415, 140, 35), "", "box_sharp_alpha");
            }

            if (GUI.Button(new Rect(180, 415, 140, 35), new GUIContent("1/2 Resolution", DisableButtons ? "" : "Half resolution of dynamic object textures"), CognitiveVR_Preferences.Instance.TextureResize == 2 ? "button_blueoutline" : "button_disabledtext"))
            {
                CognitiveVR_Preferences.Instance.TextureResize = 2;
            }
            if (CognitiveVR_Preferences.Instance.TextureResize != 2)
            {
                GUI.Box(new Rect(180, 415, 140, 35), "", "box_sharp_alpha");
            }

            if (GUI.Button(new Rect(330, 415, 140, 35), new GUIContent("1/1 Resolution", DisableButtons ? "" : "Full resolution of dynamic object textures"), CognitiveVR_Preferences.Instance.TextureResize == 1 ? "button_blueoutline" : "button_disabledtext"))
            {
                CognitiveVR_Preferences.Instance.TextureResize = 1;
            }
            if (CognitiveVR_Preferences.Instance.TextureResize != 1)
            {
                GUI.Box(new Rect(330, 415, 140, 35), "", "box_sharp_alpha");
            }
            EditorGUI.EndDisabledGroup();


            EditorGUI.BeginDisabledGroup(currentscene == null || string.IsNullOrEmpty(currentscene.SceneId) || selectionCount == 0);
            if (GUI.Button(new Rect(30, 460, 200, 30), new GUIContent("Upload " + selectionCount + " Selected Meshes", DisableButtons ? "" : "Export and Upload to " + scenename + " version " + versionnumber)))
            {
                EditorCore.RefreshSceneVersion(() =>
                {
                    foreach (var go in Selection.gameObjects)
                    {
                        var dyn = go.GetComponent <DynamicObject>();
                        if (dyn == null)
                        {
                            continue;
                        }
                        //check if export files exist
                        if (!EditorCore.HasDynamicExportFiles(dyn.MeshName))
                        {
                            ExportUtility.ExportDynamicObject(dyn);
                        }
                        //check if thumbnail exists
                        if (!EditorCore.HasDynamicObjectThumbnail(dyn.MeshName))
                        {
                            EditorCore.SaveDynamicThumbnailAutomatic(dyn.gameObject);
                        }
                    }

                    EditorCore.RefreshSceneVersion(delegate()
                    {
                        var manifest = new AggregationManifest();
                        AddOrReplaceDynamic(manifest, GetDynamicObjectsInScene());
                        ManageDynamicObjects.UploadManifest(manifest, () => ExportUtility.UploadSelectedDynamicObjectMeshes(true));
                    });
                });
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.BeginDisabledGroup(currentscene == null || string.IsNullOrEmpty(currentscene.SceneId));
            if (GUI.Button(new Rect(270, 460, 200, 30), new GUIContent("Upload All Meshes", DisableButtons ? "" : "Export and Upload to " + scenename + " version " + versionnumber)))
            {
                EditorCore.RefreshSceneVersion(() =>
                {
                    var dynamics          = GameObject.FindObjectsOfType <DynamicObject>();
                    List <GameObject> gos = new List <GameObject>();
                    foreach (var v in dynamics)
                    {
                        gos.Add(v.gameObject);
                    }

                    Selection.objects = gos.ToArray();

                    foreach (var go in Selection.gameObjects)
                    {
                        var dyn = go.GetComponent <DynamicObject>();
                        if (dyn == null)
                        {
                            continue;
                        }
                        //check if export files exist
                        if (!EditorCore.HasDynamicExportFiles(dyn.MeshName))
                        {
                            ExportUtility.ExportDynamicObject(dyn);
                        }
                        //check if thumbnail exists
                        if (!EditorCore.HasDynamicObjectThumbnail(dyn.MeshName))
                        {
                            EditorCore.SaveDynamicThumbnailAutomatic(dyn.gameObject);
                        }
                    }

                    EditorCore.RefreshSceneVersion(delegate()
                    {
                        var manifest = new AggregationManifest();
                        AddOrReplaceDynamic(manifest, GetDynamicObjectsInScene());
                        ManageDynamicObjects.UploadManifest(manifest, () => ExportUtility.UploadSelectedDynamicObjectMeshes(true));
                    });
                });
            }
            EditorGUI.EndDisabledGroup();

            DrawFooter();
            Repaint(); //manually repaint gui each frame to make sure it's responsive
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            var script            = serializedObject.FindProperty("m_Script");
            var updateRate        = serializedObject.FindProperty("UpdateRate");
            var positionThreshold = serializedObject.FindProperty("PositionThreshold");
            var rotationThreshold = serializedObject.FindProperty("RotationThreshold");
            var scaleThreshold    = serializedObject.FindProperty("ScaleThreshold");
            var useCustomId       = serializedObject.FindProperty("UseCustomId");
            var customId          = serializedObject.FindProperty("CustomId");
            var commonMeshName    = serializedObject.FindProperty("CommonMesh");
            var meshname          = serializedObject.FindProperty("MeshName");
            var useCustomMesh     = serializedObject.FindProperty("UseCustomMesh");
            var isController      = serializedObject.FindProperty("IsController");
            var syncWithGaze      = serializedObject.FindProperty("SyncWithPlayerGazeTick");
            var idPool            = serializedObject.FindProperty("IdPool");

            foreach (var t in serializedObject.targetObjects) //makes sure a custom id is valid
            {
                var dynamic = t as DynamicObject;
                if (dynamic.editorInstanceId != dynamic.GetInstanceID() || string.IsNullOrEmpty(dynamic.CustomId)) //only check if something has changed on a dynamic, or if the id is empty
                {
                    if (dynamic.UseCustomId && idType == 0)
                    {
                        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(dynamic.gameObject)))//scene asset
                        {
                            dynamic.editorInstanceId = dynamic.GetInstanceID();
                            CheckCustomId();
                        }
                        else //project asset
                        {
                            dynamic.editorInstanceId = dynamic.GetInstanceID();
                            if (string.IsNullOrEmpty(dynamic.CustomId))
                            {
                                string s = System.Guid.NewGuid().ToString();
                                dynamic.CustomId = "editor_" + s;
                            }
                        }
                    }
                }
            }

            //display script on component
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
            EditorGUI.EndDisabledGroup();

            //use custom mesh and mesh text field
            GUILayout.BeginHorizontal();
            UnityEditor.EditorGUILayout.PropertyField(useCustomMesh);
            bool anycustomnames = false;

            foreach (var t in targets)
            {
                var dyn = t as DynamicObject;
                if (dyn.UseCustomMesh)
                {
                    anycustomnames = true;
                    if (string.IsNullOrEmpty(dyn.MeshName))
                    {
                        dyn.MeshName = dyn.gameObject.name.ToLower().Replace(" ", "_").Replace("<", "_").Replace(">", "_").Replace("|", "_").Replace("?", "_").Replace("*", "_").Replace("\"", "_").Replace("/", "_").Replace("\\", "_").Replace(":", "_");
                        if (!Application.isPlaying)
                        {
                            UnityEditor.EditorUtility.SetDirty(dyn);
                            UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
                        }
                    }
                    if (targets.Length == 1)
                    {
                        dyn.MeshName = UnityEditor.EditorGUILayout.TextField("", dyn.MeshName);
                    }
                }
            }
            if (!anycustomnames)
            {
                UnityEditor.EditorGUILayout.PropertyField(commonMeshName, new GUIContent(""));
            }
            GUILayout.EndHorizontal();

            if (idType == -1)
            {
                var dyn = target as DynamicObject;
                if (dyn.UseCustomId)
                {
                    idType = 0;
                }
                else if (dyn.IdPool != null)
                {
                    idType = 2;
                }
                else
                {
                    idType = 1;
                }
            }
            GUILayout.BeginHorizontal();
            idType = EditorGUILayout.Popup(new GUIContent("Id Source"), idType, idTypeNames);

            if (idType == 0) //custom id
            {
                EditorGUILayout.PropertyField(customId, new GUIContent(""));
                useCustomId.boolValue       = true;
                idPool.objectReferenceValue = null;
            }
            else if (idType == 1) //generate id
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.LabelField(new GUIContent("Id will be generated at runtime", "This object will not be included in aggregation metrics on the dashboard"));
                EditorGUI.EndDisabledGroup();
                customId.stringValue        = string.Empty;
                useCustomId.boolValue       = false;
                idPool.objectReferenceValue = null;
            }
            else if (idType == 2) //id pool
            {
                EditorGUILayout.ObjectField(idPool, new GUIContent("", "Provides a consistent list of Ids to be used at runtime. Allows aggregated data from objects spawned at runtime"));
                customId.stringValue  = string.Empty;
                useCustomId.boolValue = false;
            }
            GUILayout.EndHorizontal();

            if (idType == 2) //id pool
            {
                var dyn = target as DynamicObject;
                if (dyn.IdPool == null)
                {
                    if (GUILayout.Button("New Dynamic Object Id Pool"))
                    {
                        var pool = ScriptableObject.CreateInstance <DynamicObjectIdPool>();
                        //write some values
                        pool.Ids = new string[1] {
                            System.Guid.NewGuid().ToString()
                        };
                        pool.MeshName   = dyn.MeshName;
                        pool.PrefabName = dyn.gameObject.name;
                        //save to root assets folder
                        AssetDatabase.CreateAsset(pool, "Assets/" + pool.MeshName + " Id Pool.asset");
                        AssetDatabase.SaveAssets();
                        AssetDatabase.Refresh();
                        //get reference to file
                        idPool.objectReferenceValue = pool;
                    }
                }
            }

            foldout = EditorGUILayout.Foldout(foldout, "Advanced");
            if (foldout)
            {
                if (useCustomMesh.boolValue)
                {
                    //Mesh
                    GUILayout.Label("Export and Upload", EditorStyles.boldLabel);
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("Export Mesh", "ButtonLeft", GUILayout.Height(30)))
                    {
                        ExportUtility.ExportAllSelectedDynamicObjects();
                    }

                    EditorGUI.BeginDisabledGroup(!EditorCore.HasDynamicExportFiles(meshname.stringValue));
                    if (GUILayout.Button("Thumbnail from\nSceneView", "ButtonMid", GUILayout.Height(30)))
                    {
                        foreach (var v in serializedObject.targetObjects)
                        {
                            EditorCore.SaveDynamicThumbnailSceneView((v as DynamicObject).gameObject);
                        }
                    }
                    EditorGUI.EndDisabledGroup();

                    EditorGUI.BeginDisabledGroup(!EditorCore.HasDynamicExportFiles(meshname.stringValue));
                    if (GUILayout.Button("Upload Mesh", "ButtonRight", GUILayout.Height(30)))
                    {
                        ExportUtility.UploadSelectedDynamicObjectMeshes(true);
                    }
                    EditorGUI.EndDisabledGroup();

                    //texture export settings
                    GUILayout.EndHorizontal();
                    GUIContent[] textureQualityNames = new GUIContent[] { new GUIContent("Full"), new GUIContent("Half"), new GUIContent("Quarter") /*, new GUIContent("Eighth"), new GUIContent("Sixteenth"), new GUIContent("Thirty Second"), new GUIContent("Sixty Fourth") */ };
                    int[]        textureQualities    = new int[] { 1, 2, 4 /*, 8, 16, 32, 64*/ };
                    CognitiveVR_Preferences.Instance.TextureResize = EditorGUILayout.IntPopup(new GUIContent("Texture Export Quality", "Reduce textures when uploading to scene explorer"), CognitiveVR_Preferences.Instance.TextureResize, textureQualityNames, textureQualities);
                    GUILayout.Space(5);

                    //ID upload
                    var dyn = target as DynamicObject;
                    if (dyn.UseCustomId)
                    {
                        EditorGUI.BeginDisabledGroup(!EditorCore.HasDynamicExportFiles(meshname.stringValue));
                        if (GUILayout.Button("Upload Custom ID for aggregation"))
                        {
                            Debug.Log("upload custom id to scene");
                            //ExportUtility.UploadSelectedDynamicObjectMeshes(true);
                            EditorCore.RefreshSceneVersion(delegate()
                            {
                                ManageDynamicObjects.AggregationManifest manifest = new ManageDynamicObjects.AggregationManifest();
                                manifest.objects.Add(new ManageDynamicObjects.AggregationManifest.AggregationManifestEntry(dyn.gameObject.name, dyn.MeshName, dyn.CustomId));
                                ManageDynamicObjects.UploadManifest(manifest, null);
                            });
                        }
                        EditorGUI.EndDisabledGroup();
                    }
                    else if (dyn.IdPool != null)
                    {
                        EditorGUI.BeginDisabledGroup(!EditorCore.HasDynamicExportFiles(meshname.stringValue));
                        if (GUILayout.Button("Upload ID Pool for aggregation"))
                        {
                            Debug.Log("upload id pool to scene");
                            //ExportUtility.UploadSelectedDynamicObjectMeshes(true);
                            EditorCore.RefreshSceneVersion(delegate()
                            {
                                ManageDynamicObjects.AggregationManifest manifest = new ManageDynamicObjects.AggregationManifest();
                                for (int i = 0; i < dyn.IdPool.Ids.Length; i++)
                                {
                                    manifest.objects.Add(new ManageDynamicObjects.AggregationManifest.AggregationManifestEntry(dyn.gameObject.name, dyn.MeshName, dyn.IdPool.Ids[i]));
                                }
                                ManageDynamicObjects.UploadManifest(manifest, null);
                            });
                        }
                        EditorGUI.EndDisabledGroup();
                    }
                }

                //Snapshot Threshold

                GUILayout.Label("Data Snapshot", EditorStyles.boldLabel);

                //controller stuff
                GUILayout.BeginHorizontal();

                UnityEditor.EditorGUILayout.PropertyField(isController, new GUIContent("Is Controller", "If true, this will record user's inputs and display the inputs in a popup on SceneExplorer"));

                if (targets.Length == 1)
                {
                    var dyn = targets[0] as DynamicObject;

                    if (dyn.IsController)
                    {
                        dyn.ControllerType = (DynamicObject.ControllerDisplayType)EditorGUILayout.EnumPopup(dyn.ControllerType);
                    }

                    if (dyn.IsController)
                    {
                        EditorGUILayout.LabelField("Is Right", GUILayout.Width(60));
                        dyn.IsRight = EditorGUILayout.Toggle(dyn.IsRight, GUILayout.Width(20));
                    }
                }

                GUILayout.EndHorizontal();

                EditorGUILayout.PropertyField(syncWithGaze, new GUIContent("Sync with Gaze", "Records the transform of the dynamic object on the same frame as gaze. This may smooth movement of this object in SceneExplorer relative to the player's position"));
                EditorGUI.BeginDisabledGroup(syncWithGaze.boolValue);
                EditorGUILayout.PropertyField(updateRate, new GUIContent("Update Rate", "This is the Snapshot interval in the Tracker Options Window"), GUILayout.MinWidth(50));
                updateRate.floatValue = Mathf.Max(0.1f, updateRate.floatValue);
                EditorGUI.EndDisabledGroup();

                EditorGUILayout.PropertyField(positionThreshold, new GUIContent("Position Threshold", "Meters the object must move to write a new snapshot. Checked each 'Tick'"));
                positionThreshold.floatValue = Mathf.Max(0, positionThreshold.floatValue);

                EditorGUILayout.PropertyField(rotationThreshold, new GUIContent("Rotation Threshold", "Degrees the object must rotate to write a new snapshot. Checked each 'Tick'"));
                rotationThreshold.floatValue = Mathf.Max(0, rotationThreshold.floatValue);

                EditorGUILayout.PropertyField(scaleThreshold, new GUIContent("Scale Threshold", "Scale multiplier that must be exceeded to write a new snapshot. Checked each 'Tick'"));
                scaleThreshold.floatValue = Mathf.Max(0, scaleThreshold.floatValue);

                EditorGUI.EndDisabledGroup();
            } //advanced foldout


            if (GUI.changed)
            {
                foreach (var t in targets)
                {
                    var dyn = t as DynamicObject;
                    if (dyn.UseCustomMesh)
                    {
                        //replace all invalid characters <>|?*"/\: with _
                        dyn.MeshName = dyn.MeshName.Replace(" ", "_").Replace("<", "_").Replace(">", "_").Replace("|", "_").Replace("?", "_").Replace("*", "_").Replace("\"", "_").Replace("/", "_").Replace("\\", "_").Replace(":", "_");
                    }
                }

                //IMPROVEMENT should check that some meaningful property changed, not just foldout
                if (!Application.isPlaying)
                {
                    foreach (var t in targets)
                    {
                        EditorUtility.SetDirty(t);
                    }
                    UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
                }
            }

            serializedObject.ApplyModifiedProperties();
            serializedObject.Update();
        }