Ejemplo n.º 1
0
        public List<AggregateView> GetAggregateVersionsFromFile()
        {
            var import = new Import();
            var allText = File.ReadAllText(HostingEnvironment.MapPath(import.YouTrackJsonFile));

            return new JavaScriptSerializer().Deserialize<List<AggregateView>>(allText);
        }
Ejemplo n.º 2
0
        public virtual void Import(Import import)
        {
            if (Parser == null)
                throw new InvalidOperationException("Parser cannot be null.");

            var file = paths.Concat(new[] { import.Path }).Aggregate("", Path.Combine);

            file = Path.Combine(Path.GetDirectoryName(file), Path.GetFileName(file));

            var contents = FileReader.GetFileContents(file);

            paths.Add(Path.GetDirectoryName(import.Path));

            try
            {
                Imports.Add(file);
                import.InnerRoot = Parser().Parse(contents, file);
            }
            catch
            {
                Imports.Remove(file);
                throw;
            }
            finally
            {
                paths.RemoveAt(paths.Count - 1);
            }
        }
Ejemplo n.º 3
0
 private void PrintInfo(Import import) {
     Log($"Wait ended because import #{import.Id} completed.");
     if (Dictionary.Any())
         Log("\nCurrent Status of Tasks:");
     foreach (var kvp in Dictionary) {
         Log($"Import {kvp.Key}: {kvp.Value.Status}");
     }
 }
Ejemplo n.º 4
0
 internal HTMLLog(Import.DAImport.Common.DIImportFileType importType, int totalTimperiod, int totalSource, int totalData,
     DataTable indicatorLogInfoTable, DataTable unitLogInfoTable, DataTable subgroupLogInfoTable,
     DataTable areaLogInfoTable, DataTable duplicateRecordsInfoTable, DataTable skippedIUSInfoTable, DataTable skippedFiles)
 {
     this.SetBasicValues(importType, totalTimperiod, totalSource, totalData,
     indicatorLogInfoTable, unitLogInfoTable, subgroupLogInfoTable,
     areaLogInfoTable, duplicateRecordsInfoTable, skippedIUSInfoTable, skippedFiles);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Employee View Model Constructor. 
 /// Will load all employees from excel
 /// </summary>
 public EmployeeViewModel()
 {
     RMA_Roots.AppConfig.LoadAppConfiguration("EmployeeOverview");
     _sitzplanSource = new BitmapImage(new Uri(@"D:\sitzplan.png"));
     var import = new Import();
     _employees = import.Employees;
     _employees = _employees.OrderBy(f => f.Vorname).ToList();
     _showSeatingVisibility = Visibility.Hidden;
 }
Ejemplo n.º 6
0
 public ScrubbingService(IInvoicingService invoicingService, IContractRepository contractRepository,                                
     Import.ICallDataImportManager importManager, IAccountRepository accountRepository,
     IInvoiceRepository invoiceRepository)
 {
     _invoicingService = invoicingService;
     _contractRepository = contractRepository;
     _importManager = importManager;
     _accountRepository = accountRepository;
     _invoiceRepository = invoiceRepository;
 }
 public void ReadExcel_CaiWuExcel_ReturnDataTable()
 {
     //arrange
     var filePath = @"D:\Codes\10月对账\10月财务\1.XLS";
     var excelImport = new Import(filePath, 4);
     //act
     var actual = excelImport.ReadCaiWu<CaiWuItem>();
     //assert
     Assert.IsTrue(actual.Count() > 1);
 }
        public ActionResult Create(Import import)
        {
            if (Session["login_status"] != null)
            {
                int[] z = (int[])Session["function_id"];
                if (z.Contains(11))
                {
                    var importer_name = "";
                    var importer_name1 = from i in db.Importers
                                         where i.importer_id == import.importer_id
                                         select i;
                    foreach (var item in importer_name1)
                    {
                        importer_name = item.importer_first_name + " " + item.importer_middle_name + " " + item.importer_last_name;
                    }
                    if (ModelState.IsValid)
                    {
                        var is_exist = (from i in db.Imports
                                        join ir in db.Importers on i.importer_id equals ir.importer_id
                                        join it in db.Importer_Type on ir.importer_type_id equals it.importer_type_id
                                        where i.importer_id == import.importer_id && i.ship_arrival_id == import.ship_arrival_id && it.is_multiple_allowed != true select i).Count();
                        if (is_exist > 0)
                        {
                            TempData["errorMessage"] = "This Import Already Exist";
                        }
                        else
                        {
                            import.payment_id = 1;
                            import.import_code = importer_name;
                            import.importing_status_id = 1;
                            import.created_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                            import.updated_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                            db.Imports.Add(import);
                            db.SaveChanges();
                            import.import_code = import.import_code + "000" + import.import_id;
                            db.Entry(import).State = EntityState.Modified;
                            db.SaveChanges();
                            TempData["errorMessage"] = "Import Added Successfully";
                        }
                        return RedirectToAction("Index");
                    }

                    return View(import);

                }
                else
                {
                    return RedirectToAction("../Home/Dashboard");
                }
            }
            else
            {
                return RedirectToAction("../Home");
            }
        }
Ejemplo n.º 9
0
        public static List<AggregateView> GetAllReleaseFromFile()
        {
            var import = new Import();
            if (File.Exists(HttpContext.Current.Server.MapPath(import.YouTrackJsonFile)) == false)
                import.SaveAllToFile();

            var allText = File.ReadAllText(HttpContext.Current.Server.MapPath(import.YouTrackJsonFile));

            var data = new JavaScriptSerializer().Deserialize<List<AggregateView>>(allText);

            return data;
        }
Ejemplo n.º 10
0
 public Form1()
 {
     syn = SynchronizationContext.Current;
     //MessageBox.Show();
     import = new Import(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
     InitializeComponent();
     worker = new BackgroundWorker();
     worker.DoWork += new DoWorkEventHandler(ThreadFunction);
     worker1 = new BackgroundWorker();
     worker1.DoWork += new DoWorkEventHandler(ThreadCount);
     //worker.WorkerReportsProgress = true;
     //worker.ProgressChanged += (WorkerForChanged);
 }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Import im = new Import();
            Console.WriteLine("文本URL:");
            string path = Console.ReadLine();
            im.readFromTxt(path);

            ExcelProcess exlP = new ExcelProcess(path.Substring(0, path.Count() - 5));

            exlP.ImportExcel(im.GetContent());
            Console.WriteLine("导入成功!");
            Console.Read();
        }
Ejemplo n.º 12
0
        public static IEnumerable<AggregateView> GetRoadmapReleasesFromFile()
        {
            var import = new Import();
            if (File.Exists(HttpContext.Current.Server.MapPath(import.YouTrackJsonFile)) == false)
                import.SaveAllToFile();

            var allText = File.ReadAllText(HttpContext.Current.Server.MapPath(import.YouTrackJsonFile));

            var data = new JavaScriptSerializer().Deserialize<List<AggregateView>>(allText);
            var result = data.Where(x => x.released == false && x.isPatch == false);

            return result;
        }
Ejemplo n.º 13
0
 public static void Start()
 {
     using (DisposableTimer.DebugDuration<YouTrackSync>(() => "YouTrack import executing", () => "YouTrack import complete"))
     {
         try
         {
             var import = new Import();
             import.SaveAllToFile();
         }
         catch (Exception ex)
         {
             LogHelper.Error<YouTrackSync>("Error importing from YouTrack", ex);
         }
     }
 }
Ejemplo n.º 14
0
        public void BuilderVisitorShouldBuildImport()
        {
            #region Arrange Package Node Input

            var root = new RootNode();
            var import = new Node(NodeType.Import, "import");
            var type = new Node(NodeType.ImportModifier, "public");
            var otherMessage = new Node(NodeType.StringLiteral, "other.message");
            import.AddChildren(type, otherMessage);
            root.AddChild(import);

            #endregion Arrange Package Node Input

            var expected = new Import("public", "other.message");
            var sut = new BuilderVisitor();
            root.Accept(sut);

            sut.FileDescriptor.Imports.First().Should().Be(expected);
        }
Ejemplo n.º 15
0
        public Declr MakeModule(String moduleName, IReadOnlyList<IClassItem> moduleItems, bool importPrelude = true)
        {
            IReadOnlyList<IClassItem> modItems;
            if (importPrelude)
                modItems = new Import
                {
                    QualifiedIdent = new Ident("prelude", IdentCategory.Value)
                }.Append(moduleItems).ToList();
            else
                modItems = moduleItems;

            return new Declr(
                new Ident(moduleName, IdentCategory.Value),
                null,
                new New(new Class(modItems)))
            {
                IsVar = true,
                Attributes = new List<Ident> { new Ident("public") }
            };
        }
Ejemplo n.º 16
0
        /// <summary>
        ///  Imports the file inside the import as a dot-less file.
        /// </summary>
        /// <param name="import"></param>
        /// <returns> Whether the file was found - so false if it cannot be found</returns>
        public virtual bool Import(Import import)
        {
            if (Parser == null)
                throw new InvalidOperationException("Parser cannot be null.");

            var file = Paths.Concat(new[] { import.Path }).AggregatePaths(CurrentDirectory);

            if (!FileReader.DoesFileExist(file) && !file.EndsWith(".less"))
            {
                file = file + ".less";
            }

            if (!FileReader.DoesFileExist(file))
            {
                return false;
            }

            var contents = FileReader.GetFileContents(file);

            Paths.Add(Path.GetDirectoryName(import.Path));

            try
            {
                Imports.Add(file);
                import.InnerRoot = Parser().Parse(contents, file);
            }
            catch
            {
                Imports.Remove(file);
                throw;
            }
            finally
            {
                Paths.RemoveAt(Paths.Count - 1);
            }

            return true;
        }
        public ActionResult Create(Import import)
        {
            var importer_name = "";
            var importer_name1 = from i in db.Importers
                                 where i.importer_id == import.importer_id
                                 select i;
            foreach (var item in importer_name1)
            {
                importer_name = item.importer_first_name + " " + item.importer_middle_name + " " + item.importer_last_name;
            }
            if (ModelState.IsValid)
            {
                var is_exist = (from i in db.Imports where i.importer_id == import.importer_id && i.ship_arrival_id == import.ship_arrival_id select i).Count();
                if (is_exist > 0)
                {
                    TempData["errorMessage"] = "This Import Already Exist";
                }
                else
                {
                    import.payment_id = 1;
                    import.import_code = importer_name;
                    import.importing_status_id = 1;
                    import.created_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                    import.updated_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                    db.Imports.Add(import);
                    db.SaveChanges();
                    import.import_code = import.import_code + "000" + import.import_id;
                    db.Entry(import).State = EntityState.Modified;
                    db.SaveChanges();
                    TempData["errorMessage"] = "Import Added Successfully";
                }
                return RedirectToAction("Index");
            }

            return View(import);
        }
Ejemplo n.º 18
0
 public Builder_Data(Model.DatabaseType dbType)
 {
     this.createInstance = Factory.Factory.CreateCreateCodeInstance(dbType);
     this.databaseInstance = Factory.Factory.CreateDatabaseInstance(dbType);
     this.import = new Import(dbType);
 }
 protected static void UnmapViewAndCloseFileMapping(Tuple <IntPtr, IntPtr> file)
 {
     Import.UnmapViewOfFile(file.Item2);
     Import.CloseHandle(file.Item1);
 }
Ejemplo n.º 20
0
        /// <summary>
        ///  Imports the file inside the import as a dot-less file.
        /// </summary>
        /// <param name="import"></param>
        /// <returns> The action for the import node to process</returns>
        public virtual ImportAction Import(Import import)
        {
            // if the import is protocol'd (e.g. http://www.opencss.com/css?blah) then leave the import alone
            if (IsProtocolUrl(import.Path) && !IsEmbeddedResource(import.Path))
            {
                if (import.Path.EndsWith(".less"))
                {
                    throw new FileNotFoundException(string.Format(".less cannot import non local less files [{0}].", import.Path), import.Path);
                }

                if (CheckIgnoreImport(import))
                {
                    return(ImportAction.ImportNothing);
                }

                return(ImportAction.LeaveImport);
            }

            var file = import.Path;

            if (!IsNonRelativeUrl(file))
            {
                file = GetAdjustedFilePath(import.Path, _paths);
            }

            if (CheckIgnoreImport(import, file))
            {
                return(ImportAction.ImportNothing);
            }

            bool importAsless = ImportAllFilesAsLess || IsOptionSet(import.ImportOptions, ImportOptions.Less);

            if (!importAsless && import.Path.EndsWith(".css") && !import.Path.EndsWith(".less.css"))
            {
                if (InlineCssFiles || IsOptionSet(import.ImportOptions, ImportOptions.Inline))
                {
                    if (IsEmbeddedResource(import.Path) && ImportEmbeddedCssContents(file, import))
                    {
                        return(ImportAction.ImportCss);
                    }
                    if (ImportCssFileContents(file, import))
                    {
                        return(ImportAction.ImportCss);
                    }
                }

                return(ImportAction.LeaveImport);
            }

            if (Parser == null)
            {
                throw new InvalidOperationException("Parser cannot be null.");
            }

            if (!ImportLessFile(file, import))
            {
                if (IsOptionSet(import.ImportOptions, ImportOptions.Optional))
                {
                    return(ImportAction.ImportNothing);
                }

                if (IsOptionSet(import.ImportOptions, ImportOptions.Css))
                {
                    return(ImportAction.LeaveImport);
                }

                if (import.Path.EndsWith(".less", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new FileNotFoundException(string.Format("You are importing a file ending in .less that cannot be found [{0}].", file), file);
                }
                return(ImportAction.LeaveImport);
            }

            return(ImportAction.ImportLess);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///  Imports a less file and puts the root into the import node
        /// </summary>
        protected bool ImportLessFile(string lessPath, Import import)
        {
            string contents, file = null;

            if (IsEmbeddedResource(lessPath))
            {
                contents = ResourceLoader.GetResource(lessPath, FileReader, out file);
                if (contents == null)
                {
                    return(false);
                }
            }
            else
            {
                string fullName = lessPath;
                if (Path.IsPathRooted(lessPath))
                {
                    fullName = lessPath;
                }
                else if (!string.IsNullOrEmpty(CurrentDirectory))
                {
                    fullName = CurrentDirectory.Replace(@"\", "/").TrimEnd('/') + '/' + lessPath;
                }

                bool fileExists = FileReader.DoesFileExist(fullName);
                if (!fileExists && !fullName.EndsWith(".less"))
                {
                    fullName  += ".less";
                    fileExists = FileReader.DoesFileExist(fullName);
                }

                if (!fileExists)
                {
                    return(false);
                }

                contents = FileReader.GetFileContents(fullName);

                file = fullName;
            }

            _paths.Add(Path.GetDirectoryName(import.Path));

            try
            {
                if (!string.IsNullOrEmpty(file))
                {
                    Imports.Add(file);
                }
                import.InnerRoot = Parser().Parse(contents, lessPath);
            }
            catch
            {
                Imports.Remove(file);
                throw;
            }
            finally
            {
                _paths.RemoveAt(_paths.Count - 1);
            }

            return(true);
        }
Ejemplo n.º 22
0
        public static void Parse()
        {
            var badString = "(RNToys)";
            var URL       = @"http://www.rntoys.com";
            var singlePropertiesProduct = new Dictionary <string, Search <string> >
            {
                ["Наименование"] = (node, args) => node
                                   .SelectSingleNode(@"//h1")
                                   .InnerText.Replace(badString, String.Empty),
                [@"""Код артикула"""] = (node, args) => "RS-" + node
                                        .SelectSingleNode(@".//*[@id='ctl00_MainContent_panTopRight']/div[1]/span")
                                        .InnerText,
                ["Цена"] = (node, args) => Regex.Replace(node
                                                         .SelectSingleNode(@".//*[@id='ctl00_MainContent_panTopRight']/div[2]/span")
                                                         .InnerText.Replace("р.", String.Empty), @"\s+", string.Empty),
                ["Вес"] = (node, args) => node
                          .SelectSingleNode(@".//*[@id='ctl00_MainContent_panWeight']/span")
                          .InnerText,
                ["Размеры"] = (node, args) => node
                              .SelectSingleNode(@".//*[@id='ctl00_MainContent_panDimensions']/span")
                              .InnerText,
                ["Валюта"] = (node, o) => "RUB",
                [@"""Доступен для заказа"""] = (node, o) => "1",
                [@"Статус"] = (node, o) => "1",
                [@"Страна-производитель"] = (node, args) => node
                                            .SelectSingleNode(@".//*[@id='ctl00_MainContent_countryElement_iconCountry']")
                                            .Attributes["alt"].Value,
                ["Описание"] = (node, args) => node
                               .SelectSingleNode(@".//*[@id='ctl00_MainContent_panFeature']/span")
                               .InnerText
            };

            singlePropertiesProduct["Заголовок"] = (node, args) => singlePropertiesProduct["Наименование"](node, args);
            singlePropertiesProduct[@"""Ссылка на витрину"""] = (node, args) =>
                                                                Humanization.GetHumanLink(singlePropertiesProduct["Наименование"](node, args)
                                                                                          + "-" + singlePropertiesProduct[@"""Код артикула"""](node, args));

            var parser = new LiquiMolyClass(
                isCategory: node => node
                ._SelectNodes(@"//a[contains(@class, 'rpSelected')]")
                .Count != 0,
                findProducts: (node, args) => node
                ._SelectNodes(@"//div[@class='mm-pl-tiles-Item']/div/div[2]/a")
                .Select(x => new ArgumentObject(URL + x.Attributes["href"].Value))
                .ToArray(),
                singlePropertiesCategory: new Dictionary <string, Search <string> >
            {
                ["Наименование"] = (node, args) => new string('!', (int)args.Args[0]) + node
                                   .SelectSingleNode(@"//h1")
                                   .InnerText,
                ["Описание"] = (node, args) => node
                               .SelectSingleNode(@"//h1/..")
                               .InnerHtml
            },
                singlePropertiesProduct:  singlePropertiesProduct,
                pluralPropertiesProduct: new Dictionary <string, Search <string[]> >
            {
                ["Изображения"] = (node, args) => node
                                  ._SelectNodes(@".//*[@id='ctl00_MainContent_panImageContainer']/div/div/img")
                                  .Select(x => URL + x.Attributes["src"].Value)
                                  .Select(HttpUtility.UrlPathEncode)
                                  .ToArray()
            }
                );

            var argument = new ArgumentObject(
                url: URL,
                args: new object[] { 2 });

            var collection =
                parser.GetProductOrCategory(parser.GetLinks(argument,
                                                            @".//*[@id='ctl00_productCategoriesMenu_menu']/ul/li/a",
                                                            URL));

            //parser.GetProductOrCategory(argument);
            collection = new[]
            {
                new ProductCategoryObject(
                    new Dictionary <string, string> {
                    ["Наименование"] = "Temporary2"
                }, isCategory: true),
                new ProductCategoryObject(
                    new Dictionary <string, string> {
                    ["Наименование"] = "!Rntoys"
                }, isCategory: true)
            }.Extend(collection);
            Import.Write(path: @"..\..\..\CSV\rntoys.csv",
                         collection: collection.ToArray(),
                         headers: Constants.WebAsystKeys,
                         format: Constants.WebAsystFormatter);
        }
Ejemplo n.º 23
0
            internal static stmt Convert(Statement stmt) {
                stmt ast;

                if (stmt is FunctionDefinition)
                    ast = new FunctionDef((FunctionDefinition)stmt);
                else if (stmt is ReturnStatement)
                    ast = new Return((ReturnStatement)stmt);
                else if (stmt is AssignmentStatement)
                    ast = new Assign((AssignmentStatement)stmt);
                else if (stmt is AugmentedAssignStatement)
                    ast = new AugAssign((AugmentedAssignStatement)stmt);
                else if (stmt is DelStatement)
                    ast = new Delete((DelStatement)stmt);
                else if (stmt is PrintStatement)
                    ast = new Print((PrintStatement)stmt);
                else if (stmt is ExpressionStatement)
                    ast = new Expr((ExpressionStatement)stmt);
                else if (stmt is ForStatement)
                    ast = new For((ForStatement)stmt);
                else if (stmt is WhileStatement)
                    ast = new While((WhileStatement)stmt);
                else if (stmt is IfStatement)
                    ast = new If((IfStatement)stmt);
                else if (stmt is WithStatement)
                    ast = new With((WithStatement)stmt);
                else if (stmt is RaiseStatement)
                    ast = new Raise((RaiseStatement)stmt);
                else if (stmt is TryStatement)
                    ast = Convert((TryStatement)stmt);
                else if (stmt is AssertStatement)
                    ast = new Assert((AssertStatement)stmt);
                else if (stmt is ImportStatement)
                    ast = new Import((ImportStatement)stmt);
                else if (stmt is FromImportStatement)
                    ast = new ImportFrom((FromImportStatement)stmt);
                else if (stmt is ExecStatement)
                    ast = new Exec((ExecStatement)stmt);
                else if (stmt is GlobalStatement)
                    ast = new Global((GlobalStatement)stmt);
                else if (stmt is ClassDefinition)
                    ast = new ClassDef((ClassDefinition)stmt);
                else if (stmt is BreakStatement)
                    ast = new Break();
                else if (stmt is ContinueStatement)
                    ast = new Continue();
                else if (stmt is EmptyStatement)
                    ast = new Pass();
                else
                    throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());

                ast.GetSourceLocation(stmt);
                return ast;
            }
Ejemplo n.º 24
0
 public bool Contains(double x, double y)
 {
     return(Geometry.FillContainsPoint(Import.Point(x, y)));
 }
Ejemplo n.º 25
0
 public void visitImport(Import i)
 {
     throw new NotImplementedException();
 }
 public virtual void Visit(Import import)
 {
 }
Ejemplo n.º 27
0
 public void LoadSettingsFile_throws_on_incorrect_key()
 {
     Exceptions.AssertThrowsBadCredentials(
         () => Import.LoadSettingsFile(SettingsFilename, "Incorrect key".ToBytes()),
         "The password is incorrect");
 }
Ejemplo n.º 28
0
 public void ImportLocalKey_throws_on_incorrect_password()
 {
     Exceptions.AssertThrowsBadCredentials(
         () => Import.ImportLocalKey($"{FixtureDir}/localKey-kwc3.aes", "Incorrect password"),
         "The password is incorrect");
 }
Ejemplo n.º 29
0
        public void ImportLocalKey_loads_and_decrypts_key(string filename)
        {
            var key = Import.ImportLocalKey($"{FixtureDir}/{filename}", Password);

            Assert.Equal(LocalKey, key);
        }
Ejemplo n.º 30
0
 public void ImportDeviceIdFromSettings_as_xdocument_throws_on_wrong_xml()
 {
     Exceptions.AssertThrowsInternalError(() => Import.ImportDeviceIdFromSettings(XDocument.Parse("<root />")),
                                          "The settings file doesn't contain a device ID");
 }
Ejemplo n.º 31
0
        public ActionResult Import([Bind(Include = "ImportId,Month,Year")] Import import,
                                   HttpPostedFileBase bip,
                                   HttpPostedFileBase biq,
                                   HttpPostedFileBase biqd,
                                   HttpPostedFileBase aiq,
                                   HttpPostedFileBase ta,
                                   HttpPostedFileBase npt)
        {
            string logon_user = Session["logon_user"].ToString();

            ViewBag.Months = db.months;
            ViewBag.Years  = db.years;
            #region "BIP"
            if (bip == null || bip.ContentLength == 0)
            {
                ViewBag.ErrorBIP = "No file selected";
            }
            else
            {
                if (bip.FileName.EndsWith("xls") || bip.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(bip.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    bip.SaveAs(path);
                    ImportFiles i       = new ImportFiles();
                    int         result1 = i.ImportBIProd(path, import, DateTime.Now, logon_user);
                    if (result1 == 1)
                    {
                        ViewBag.MessageBIP = "Success";
                    }
                    else
                    {
                        ViewBag.ErrorBIP = "Failed";
                    }
                }
                else
                {
                    ViewBag.ErrorBIP = "File type is incorrect";
                }
            }
            #endregion "BIP"
            #region "BIQ"
            if (biq == null || biq.ContentLength == 0)
            {
                ViewBag.ErrorBIQ = "No file selected";
            }
            else
            {
                if (biq.FileName.EndsWith("xls") || biq.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(biq.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    biq.SaveAs(path);
                    ImportFiles i       = new ImportFiles();
                    int         result2 = i.ImportBIQual(path, import, DateTime.Now, logon_user);
                    if (result2 == 1)
                    {
                        ViewBag.MessageBIQ = "Success";
                    }
                    else
                    {
                        ViewBag.ErrorBIQ = "Failed";
                    }
                }
                else
                {
                    ViewBag.ErrorBIQ = "File type is incorrect";
                }
            }
            #endregion "BIQ"
            #region "BIQD"
            if (biqd == null || biqd.ContentLength == 0)
            {
                ViewBag.ErrorBIQD = "No file selected";
            }
            else
            {
                if (biqd.FileName.EndsWith("xls") || biqd.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(biqd.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    biqd.SaveAs(path);
                    ImportFiles i       = new ImportFiles();
                    int         result2 = i.ImportBIQualD(path, import, DateTime.Now, logon_user);
                    if (result2 == 1)
                    {
                        ViewBag.MessageBIQD = "Success";
                    }
                    else
                    {
                        ViewBag.ErrorBIQD = "Failed";
                    }
                }
                else
                {
                    ViewBag.ErrorBIQD = "File type is incorrect";
                }
            }
            #endregion "BIQD"
            #region "AIQ"
            if (aiq == null || aiq.ContentLength == 0)
            {
                ViewBag.ErrorAIQ = "No file selected";
            }
            else
            {
                if (aiq.FileName.EndsWith("xls") || aiq.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(aiq.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    aiq.SaveAs(path);
                    #region "EXCEL"
                    Excel.Application    application = new Excel.Application();
                    Excel.Workbook       workbook    = application.Workbooks.Open(path);
                    Excel.Worksheet      worksheet   = workbook.ActiveSheet;
                    Excel.Range          range       = worksheet.UsedRange;
                    List <OSC_ImportAIQ> list        = new List <OSC_ImportAIQ>();
                    for (int row = 2; row <= range.Rows.Count; row++)
                    {
                        OSC_ImportAIQ obj = new OSC_ImportAIQ();
                        obj.Agent = ((Excel.Range)range.Cells[row, 1]).Text;
                        obj.IntervalStaffedDuration = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 2]).Text);
                        obj.TotalPercServiceTime    = Convert.ToDouble(((Excel.Range)range.Cells[row, 3]).Text);
                        obj.TotalACDCalls           = Convert.ToInt32(((Excel.Range)range.Cells[row, 4]).Text);
                        obj.ExtInCalls         = Convert.ToInt32(((Excel.Range)range.Cells[row, 5]).Text);
                        obj.ExtInAvgActiveDur  = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 6]).Text);
                        obj.ExtOutCalls        = Convert.ToInt32(((Excel.Range)range.Cells[row, 7]).Text);
                        obj.AvgExtOutActiveDur = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 8]).Text);
                        obj.ACDWrapUpTime      = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 9]).Text);
                        obj.ACDTalkTime        = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 10]).Text);
                        obj.ACDRingTime        = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 11]).Text);
                        obj.Aux             = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 12]).Text);
                        obj.AvgHoldDur      = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 13]).Text);
                        obj.IntervalIdleDur = af.GetSecondsFormat(((Excel.Range)range.Cells[row, 14]).Text);
                        obj.Transfers       = Convert.ToInt32(((Excel.Range)range.Cells[row, 15]).Text);
                        obj.HeldContacts    = Convert.ToInt32(((Excel.Range)range.Cells[row, 16]).Text);
                        obj.Redirects       = Convert.ToInt32(((Excel.Range)range.Cells[row, 17]).Text);
                        obj.Month           = import.Month;
                        obj.Year            = import.Year;
                        obj.DateUploaded    = DateTime.Now;
                        obj.UploadedBy      = User.Identity.Name;
                        list.Add(obj);
                    }
                    foreach (OSC_ImportAIQ obj in list)
                    {
                        obj.RepId  = db.Representatives.Where(r => (r.AIQUserId == obj.Agent) && ((bool)r.IsCurrent)).FirstOrDefault().RepId;
                        obj.TeamId = db.Representatives.Where(r => (r.AIQUserId == obj.Agent) && ((bool)r.IsCurrent)).FirstOrDefault().TeamId;
                        db.AIQ.Add(obj);
                    }
                    try
                    {
                        db.SaveChanges();
                        ViewBag.MessageBIP = "Success";
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewBag.ErrorBIP = "Error: " + ex.Message.ToString();
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    #endregion "EXCEL"
                }
                else
                {
                    ViewBag.ErrorAIQ = "File type is incorrect";
                }
            }
            #endregion "AIQ"
            #region "TA"
            if (ta == null || ta.ContentLength == 0)
            {
                ViewBag.ErrorTA = "No file selected";
            }
            else
            {
                if (ta.FileName.EndsWith("xls") || ta.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(ta.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    ta.SaveAs(path);
                    #region "EXCEL"
                    Excel.Application   application = new Excel.Application();
                    Excel.Workbook      workbook    = application.Workbooks.Open(path);
                    Excel.Worksheet     worksheet   = workbook.ActiveSheet;
                    Excel.Range         range       = worksheet.UsedRange;
                    List <OSC_ImportTA> list        = new List <OSC_ImportTA>();
                    for (int row = 2; row <= range.Rows.Count; row++)
                    {
                        OSC_ImportTA obj = new OSC_ImportTA();
                        obj.AssignedId       = ((Excel.Range)range.Cells[row, 1]).Text;
                        obj.Group            = ((Excel.Range)range.Cells[row, 2]).Text;
                        obj.FirstName        = ((Excel.Range)range.Cells[row, 3]).Text;
                        obj.MiddleInt        = ((Excel.Range)range.Cells[row, 4]).Text;
                        obj.LastName         = ((Excel.Range)range.Cells[row, 5]).Text;
                        obj.CreateDateTime   = ((Excel.Range)range.Cells[row, 6]).Text;
                        obj.BusinessArea     = ((Excel.Range)range.Cells[row, 7]).Text;
                        obj.WorkType         = ((Excel.Range)range.Cells[row, 8]).Text;
                        obj.Status           = ((Excel.Range)range.Cells[row, 9]).Text;
                        obj.Queue            = ((Excel.Range)range.Cells[row, 10]).Text;
                        obj.Suspended        = ((Excel.Range)range.Cells[row, 11]).Text;
                        obj.SuspendDate      = ((Excel.Range)range.Cells[row, 12]).Text;
                        obj.UnsuspendDate    = ((Excel.Range)range.Cells[row, 13]).Text;
                        obj.LastStatusUpdate = ((Excel.Range)range.Cells[row, 14]).Text;
                        obj.Account          = ((Excel.Range)range.Cells[row, 15]).Text;
                        obj.GAC                = ((Excel.Range)range.Cells[row, 16]).Text;
                        obj.Assoc              = ((Excel.Range)range.Cells[row, 17]).Text;
                        obj.Certificate        = ((Excel.Range)range.Cells[row, 18]).Text;
                        obj.CheckAmount        = ((Excel.Range)range.Cells[row, 19]).Text;
                        obj.First_Name         = ((Excel.Range)range.Cells[row, 20]).Text;
                        obj.Last_Name          = ((Excel.Range)range.Cells[row, 21]).Text;
                        obj.CustomerNo         = ((Excel.Range)range.Cells[row, 22]).Text;
                        obj.ProductType        = ((Excel.Range)range.Cells[row, 23]).Text;
                        obj.AdminSystem        = ((Excel.Range)range.Cells[row, 24]).Text;
                        obj.CheckAmountTotal   = ((Excel.Range)range.Cells[row, 25]).Text;
                        obj.UCIVendorMatchDate = ((Excel.Range)range.Cells[row, 26]).Text;
                        obj.ReasonCodeForAdv   = ((Excel.Range)range.Cells[row, 27]).Text;
                        obj.ReasonDescription  = ((Excel.Range)range.Cells[row, 28]).Text;
                        obj.TinSourceType      = ((Excel.Range)range.Cells[row, 29]).Text;
                        obj.SSBusinessUnit     = ((Excel.Range)range.Cells[row, 30]).Text;
                        obj.Month              = import.Month;
                        obj.Year               = import.Year;
                        obj.DateUploaded       = DateTime.Now;
                        obj.UploadedBy         = User.Identity.Name;
                        list.Add(obj);
                    }
                    foreach (OSC_ImportTA obj in list)
                    {
                        if (Convert.ToDateTime(obj.CreateDateTime).Month == obj.Month)
                        {
                            obj.RepId  = db.Representatives.Where(r => (r.PRDUserId == obj.AssignedId) && ((bool)r.IsCurrent)).FirstOrDefault().RepId;
                            obj.TeamId = af.GetTeamIdByGroupId(obj.Group, "BI").TeamId;
                            db.TA.Add(obj);
                        }
                    }
                    try
                    {
                        db.SaveChanges();
                        ViewBag.MessageBIP = "Success";
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewBag.ErrorBIP = "Error: " + ex.Message.ToString();
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    #endregion "EXCEL"
                }
                else
                {
                    ViewBag.ErrorTA = "File type is incorrect";
                }
            }
            #endregion "TA"
            #region "NPT"
            if (npt == null || npt.ContentLength == 0)
            {
                ViewBag.ErrorNPT = "No file selected";
            }
            else
            {
                if (npt.FileName.EndsWith("xls") || npt.FileName.EndsWith("xlsx"))
                {
                    string fname = Path.GetFileName(npt.FileName);
                    string path  = Server.MapPath("~/ImportFile/" + fname);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    npt.SaveAs(path);
                    #region "EXCEL"
                    Excel.Application    application = new Excel.Application();
                    Excel.Workbook       workbook    = application.Workbooks.Open(path);
                    Excel.Worksheet      worksheet   = workbook.ActiveSheet;
                    Excel.Range          range       = worksheet.UsedRange;
                    List <OSC_ImportNPT> list        = new List <OSC_ImportNPT>();
                    for (int row = 2; row <= range.Rows.Count; row++)
                    {
                        OSC_ImportNPT obj = new OSC_ImportNPT();
                        obj.Activity       = ((Excel.Range)range.Cells[row, 1]).Text;
                        obj.DateOfActivity = Convert.ToDateTime(((Excel.Range)range.Cells[row, 2]).Text);
                        obj.TimeSpent      = Convert.ToDouble(((Excel.Range)range.Cells[row, 3]).Text) * 60;
                        obj.TypeOfActivity = ((Excel.Range)range.Cells[row, 4]).Text;
                        obj.CreatedBy      = ((Excel.Range)range.Cells[row, 5]).Text;
                        obj.ItemType       = ((Excel.Range)range.Cells[row, 6]).Text;
                        obj.Path           = ((Excel.Range)range.Cells[row, 7]).Text;
                        obj.Month          = import.Month;
                        obj.Year           = import.Year;
                        obj.DateUploaded   = DateTime.Now;
                        obj.UploadedBy     = User.Identity.Name;
                        obj.Source         = "Import";
                        list.Add(obj);
                    }
                    foreach (OSC_ImportNPT obj in list)
                    {
                        if (Convert.ToDateTime(obj.DateOfActivity).Month == obj.Month)
                        {
                            obj.RepId = db.Representatives.Where(r => (r.LastName + ", " + r.FirstName == obj.CreatedBy) &&
                                                                 ((bool)r.IsCurrent)).FirstOrDefault().RepId;
                            obj.TeamId = db.Representatives.Where(r => (r.LastName + ", " + r.FirstName == obj.CreatedBy) &&
                                                                  ((bool)r.IsCurrent)).FirstOrDefault().TeamId;
                            db.NPT.Add(obj);
                        }
                    }
                    try
                    {
                        db.SaveChanges();
                        ViewBag.MessageBIP = "Success";
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewBag.ErrorBIP = "Error: " + ex.Message.ToString();
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                    }
                    #endregion "EXCEL"
                }
                else
                {
                    ViewBag.ErrorNPT = "File type is incorrect";
                }
            }
            #endregion "NPT"
            return(View("Index"));
        }
 protected override void VisitImport(Import import)
 {
     VisitingImport?.Invoke(this, import);
     base.VisitImport(import);
     VisitedImport?.Invoke(this, import);
 }
Ejemplo n.º 33
0
 public void ImportDeviceIdFromSettings_as_xdocument_returns_device_id()
 {
     Assert.Equal(DeviceId, Import.ImportDeviceIdFromSettings(XDocument.Parse(Xml)));
 }
 private void UpdateCorePluginFrameworkImports(Import import)
 {
     import.Project   = ReplacePluginFrameworkBuildVersion(import.Project);
     import.Condition = ReplacePluginFrameworkBuildVersion(import.Condition);
 }
Ejemplo n.º 35
0
        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="details"></param>
        /// <param name="import"></param>
        /// <param name="IgnoreError"></param>
        /// <param name="OnlyTotal"></param>
        private void Calc(out List <ImportDetail> details, out Import import, bool IgnoreError = true, bool OnlyTotal = false)
        {
            bool IsError = false;

            details = new List <ImportDetail>();
            import  = new Import();

            if (!OnlyTotal)
            {
                for (int i = krpdgList.Rows.Count - 1; i >= 0; i--)
                {
                    ImportDetail importDetails = new ImportDetail();

                    //只有有改动才可以继续
                    if (krpdgList.Rows[i].Cells["krpcmEdit"].Value.Equals("*"))
                    {
                        try
                        {
                            string  productName = krpdgList.Rows[i].Cells["krpcmProductName"].Value.ToString();
                            Product product     = null;
                            if (Resources.GetRes().MainLangIndex == 0)
                            {
                                product = Resources.GetRes().Products.Where(x => x.ProductName0 == productName && (x.HideType == 0 || x.HideType == 3)).FirstOrDefault();
                            }
                            else if (Resources.GetRes().MainLangIndex == 1)
                            {
                                product = Resources.GetRes().Products.Where(x => x.ProductName1 == productName && (x.HideType == 0 || x.HideType == 3)).FirstOrDefault();
                            }
                            else if (Resources.GetRes().MainLangIndex == 2)
                            {
                                product = Resources.GetRes().Products.Where(x => x.ProductName2 == productName && (x.HideType == 0 || x.HideType == 3)).FirstOrDefault();
                            }

                            importDetails.ProductId = product.ProductId;
                            importDetails.Count     = Math.Round(double.Parse(krpdgList.Rows[i].Cells["krpcmCount"].Value.ToString()), 3);

                            krpdgList.Rows[i].Cells["krpcmCostPrice"].Value  = importDetails.Price = Math.Round(double.Parse(krpdgList.Rows[i].Cells["krpcmCostPrice"].Value.ToString()), 2);
                            krpdgList.Rows[i].Cells["krpcmTotalPrice"].Value = importDetails.TotalPrice = Math.Round(importDetails.Price * importDetails.Count, 2);
                            importDetails.OriginalTotalPrice = Math.Round(product.CostPrice * importDetails.Count, 2);

                            krpdgList.Rows[i].Cells["krpcmPrice"].Value = importDetails.SalePrice = Math.Round(double.Parse(krpdgList.Rows[i].Cells["krpcmPrice"].Value.ToString()), 2);
                            importDetails.OriginalSalePrice             = product.Price;


                            details.Add(importDetails);
                        }
                        catch
#if DEBUG
                        (Exception ex)
#endif
                        {
                            krpdgList.Rows[i].Cells["krpcmCostPrice"].Value  = "?";
                            krpdgList.Rows[i].Cells["krpcmTotalPrice"].Value = "?";
                            krpdgList.Rows[i].Cells["krpcmPrice"].Value      = "?";

                            // 产品名空时这种错误很常见, 所以暂时去掉
#if DEBUG
                            ExceptionPro.ExpLog(ex, null, true);
#endif
                            IsError = true;

                            if (!IgnoreError)
                            {
                                krpdgList.Rows[i].Selected = true;
                                throw new OybabException(string.Format(Resources.GetRes().GetString("LineDataError"), i + 1));
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                if (IsError)
                {
                    return;
                }
            }



            if (IsError)
            {
                return;
            }

            if (!OnlyTotal)
            {
                krplTotalPriceValue.Text  = (import.TotalPrice = Math.Round(details.Sum(x => x.TotalPrice), 2)).ToString();
                import.OriginalTotalPrice = Math.Round(details.Sum(x => x.OriginalTotalPrice), 2);
            }
            else
            {
                return;
            }


            // 显示客显(实际客户需要支付的赊账)
            Common.GetCommon().OpenPriceMonitor(Math.Round(import.TotalPaidPrice - import.TotalPrice, 2).ToString());


            import.Remark = GetValueOrNull(krptbRemark.Text);


            DateTime importDateTime = DateTime.Now;

            try
            {
                importDateTime    = krptbImportTime.Value;
                import.ImportTime = long.Parse(importDateTime.ToString("yyyyMMddHHmmss"));
            }
            catch (Exception ex)
            {
                ExceptionPro.ExpLog(ex);
                IsError = true;
                if (!IgnoreError)
                {
                    krptbImportTime.Focus();
                    throw new OybabException(string.Format(Resources.GetRes().GetString("PropertyError"), Resources.GetRes().GetString("Time")));
                }
            }

            if (IsError)
            {
                return;
            }


            ShowOrHideSave();
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Sets basic values which are required to generate Html log file
        /// </summary>
        /// <param name="totalTimperiod"></param>
        /// <param name="totalSource"></param>
        /// <param name="totalData"></param>
        /// <param name="indicatorLogInfoTable"></param>
        /// <param name="unitLogInfoTable"></param>
        /// <param name="subgroupLogInfoTable"></param>
        /// <param name="areaLogInfoTable"></param>
        /// <param name="duplicateRecordsInfoTable"></param>
        /// <param name="skippedIUSInfoTable"></param>
        internal void SetBasicValues(Import.DAImport.Common.DIImportFileType importType, int totalTimperiod, int totalSource, int totalData,
    DataTable indicatorLogInfoTable, DataTable unitLogInfoTable, DataTable subgroupLogInfoTable,
    DataTable areaLogInfoTable, DataTable duplicateRecordsInfoTable, DataTable skippedIUSInfoTable, DataTable skippedFiles)
        {
            this.TotalTimeperiod = totalTimperiod;
            this.TotalSource = totalSource;
            this.TotalData = totalData;

            this.IndicatorLogInfoTable = indicatorLogInfoTable;
            this.UnitLogInfoTable = unitLogInfoTable;
            this.SubgroupLogInfoTable = subgroupLogInfoTable;
            this.AreaLogInfoTable = areaLogInfoTable;
            this.DuplicateRecordsInfoTable = duplicateRecordsInfoTable;
            this.SkippedIUSInfoTable = skippedIUSInfoTable;

            this.SkippedFiles = skippedFiles;
            this._ImportType = importType;
            this.SetHTMLLogVariables(importType);
        }
Ejemplo n.º 37
0
 public IDisposable BeginScope(Import parentScope)
 {
     return(new ImportScope(this, Path.GetDirectoryName(parentScope.Path)));
 }
Ejemplo n.º 38
0
        /// <summary>
        ///  Imports the file inside the import as a dot-less file.
        /// </summary>
        /// <param name="import"></param>
        /// <returns> The action for the import node to process</returns>
        public virtual ImportAction Import(Import import)
        {
            // if the import is protocol'd (e.g. http://www.opencss.com/css?blah) then leave the import alone
            if (IsProtocolUrl(import.Path) && !IsEmbeddedResource(import.Path))
            {
                if (import.Path.EndsWith(".less"))
                {
                    throw new FileNotFoundException(".less cannot import non local less files.", import.Path);
                }

                if (CheckIgnoreImport(import))
                {
                    return ImportAction.ImportNothing;
                }

                return ImportAction.LeaveImport;
            }

            var file = import.Path;

            if (!IsNonRelativeUrl(file))
            {
                file = GetAdjustedFilePath(import.Path, _paths);
            }

            if (CheckIgnoreImport(import, file))
            {
                return ImportAction.ImportNothing;
            }

            if (!ImportAllFilesAsLess && import.Path.EndsWith(".css"))
            {
                if (InlineCssFiles)
                {
                    if (IsEmbeddedResource(import.Path) && ImportEmbeddedCssContents(file, import))
                        return ImportAction.ImportCss;
                    if (ImportCssFileContents(file, import))
                        return ImportAction.ImportCss;
                }

                return ImportAction.LeaveImport;
            }

            if (Parser == null)
                throw new InvalidOperationException("Parser cannot be null.");

            if (!ImportLessFile(file, import))
            {
                if (import.Path.EndsWith(".less", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new FileNotFoundException("You are importing a file ending in .less that cannot be found.", import.Path);
                }
                return ImportAction.LeaveImport;
            }

            return ImportAction.ImportLess;
        }
Ejemplo n.º 39
0
 /// <summary>
 ///  returns true if the import should be ignored because it is a duplicate and import-once was used
 /// </summary>
 /// <param name="import"></param>
 /// <returns></returns>
 protected bool CheckIgnoreImport(Import import)
 {
     return(CheckIgnoreImport(import, import.Path));
 }
Ejemplo n.º 40
0
        /// <summary>
        ///  returns true if the import should be ignored because it is a duplicate and import-once was used
        /// </summary>
        /// <param name="import"></param>
        /// <returns></returns>
        protected bool CheckIgnoreImport(Import import, string path)
        {
            if (_rawImports.Contains(path, StringComparer.InvariantCultureIgnoreCase))
            {
                return import.IsOnce;
            }
            _rawImports.Add(path);

            return false;
        }
Ejemplo n.º 41
0
        protected void TermSelectDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            int year = DateRange.GetCurrentAcademicYear();

            TermId = Import.GetTermByName(TermSelectDDL.SelectedValue, year);
        }
Ejemplo n.º 42
0
        /// <summary>
        ///  Imports a less file and puts the root into the import node
        /// </summary>
        protected bool ImportLessFile(string file, Import import)
        {
            string contents;
            if (IsEmbeddedResource(file))
            {
                contents = ResourceLoader.GetResource(file, FileReader);
                if (contents == null) return false;
            }
            else
            {
                if (!FileReader.DoesFileExist(file) && !file.EndsWith(".less"))
                {
                    file = file + ".less";
                }

                if (!FileReader.DoesFileExist(file))
                {
                    return false;
                }

                contents = FileReader.GetFileContents(file);
            }

            _paths.Add(Path.GetDirectoryName(import.Path));

            try
            {
                Imports.Add(file);
                import.InnerRoot = Parser().Parse(contents, file);
            }
            catch
            {
                Imports.Remove(file);
                throw;
            }
            finally
            {
                _paths.RemoveAt(_paths.Count - 1);
            }

            return true;
        }
Ejemplo n.º 43
0
 public override void Visit(Node node)
 {
     var modifier = node.Children.SingleOrDefault(t => t.NodeType.Equals(NodeType.ImportModifier));
     var clas = node.Children.SingleOrDefault(t => t.NodeType.Equals(NodeType.StringLiteral));
     Import = new Import(modifier?.NodeValue, clas?.NodeValue);
 }
Ejemplo n.º 44
0
 public void ImportDeviceIdFromSettings_as_xml_string_returns_device_id()
 {
     Assert.Equal(DeviceId, Import.ImportDeviceIdFromSettings(Xml));
 }
        public override void AttachToDependencyGraph(DependencyAnalyzerBase <NodeFactory> graph)
        {
            Header = new HeaderNode(Target);

            var compilerIdentifierNode = new CompilerIdentifierNode(Target);

            Header.Add(Internal.Runtime.ReadyToRunSectionType.CompilerIdentifier, compilerIdentifierNode, compilerIdentifierNode);

            RuntimeFunctionsTable = new RuntimeFunctionsTableNode(this);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.RuntimeFunctions, RuntimeFunctionsTable, RuntimeFunctionsTable);

            RuntimeFunctionsGCInfo = new RuntimeFunctionsGCInfoNode();
            graph.AddRoot(RuntimeFunctionsGCInfo, "GC info is always generated");

            ExceptionInfoLookupTableNode exceptionInfoLookupTableNode = new ExceptionInfoLookupTableNode(this);

            Header.Add(Internal.Runtime.ReadyToRunSectionType.ExceptionInfo, exceptionInfoLookupTableNode, exceptionInfoLookupTableNode);
            graph.AddRoot(exceptionInfoLookupTableNode, "ExceptionInfoLookupTable is always generated");

            MethodEntryPointTable = new MethodEntryPointTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.MethodDefEntryPoints, MethodEntryPointTable, MethodEntryPointTable);

            InstanceEntryPointTable = new InstanceEntryPointTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.InstanceMethodEntryPoints, InstanceEntryPointTable, InstanceEntryPointTable);

            TypesTable = new TypesTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.AvailableTypes, TypesTable, TypesTable);

            ImportSectionsTable = new ImportSectionsTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.ImportSections, ImportSectionsTable, ImportSectionsTable.StartSymbol);

            DebugInfoTable = new DebugInfoTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.DebugInfo, DebugInfoTable, DebugInfoTable);

            EagerImports = new ImportSectionNode(
                "EagerImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_EAGER,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(EagerImports);

            // All ready-to-run images have a module import helper which gets patched by the runtime on image load
            ModuleImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                          ILCompiler.DependencyAnalysis.ReadyToRun.ReadyToRunHelper.READYTORUN_HELPER_Module));
            graph.AddRoot(ModuleImport, "Module import is required by the R2R format spec");

            if (Target.Architecture != TargetArchitecture.X86)
            {
                Import personalityRoutineImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                                                 ILCompiler.DependencyAnalysis.ReadyToRun.ReadyToRunHelper.READYTORUN_HELPER_PersonalityRoutine));
                PersonalityRoutine = new ImportThunk(
                    ILCompiler.DependencyAnalysis.ReadyToRun.ReadyToRunHelper.READYTORUN_HELPER_PersonalityRoutine, this, personalityRoutineImport);
                graph.AddRoot(PersonalityRoutine, "Personality routine is faster to root early rather than referencing it from each unwind info");

                Import filterFuncletPersonalityRoutineImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                                                              ILCompiler.DependencyAnalysis.ReadyToRun.ReadyToRunHelper.READYTORUN_HELPER_PersonalityRoutineFilterFunclet));
                FilterFuncletPersonalityRoutine = new ImportThunk(
                    ILCompiler.DependencyAnalysis.ReadyToRun.ReadyToRunHelper.READYTORUN_HELPER_PersonalityRoutineFilterFunclet, this, filterFuncletPersonalityRoutineImport);
                graph.AddRoot(FilterFuncletPersonalityRoutine, "Filter funclet personality routine is faster to root early rather than referencing it from each unwind info");
            }

            MethodImports = new ImportSectionNode(
                "MethodImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: true);
            ImportSectionsTable.AddEmbeddedObject(MethodImports);

            DispatchImports = new ImportSectionNode(
                "DispatchImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: true);
            ImportSectionsTable.AddEmbeddedObject(DispatchImports);

            HelperImports = new ImportSectionNode(
                "HelperImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(HelperImports);

            PrecodeImports = new ImportSectionNode(
                "PrecodeImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: true,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(PrecodeImports);

            StringImports = new ImportSectionNode(
                "StringImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STRING_HANDLE,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_UNKNOWN,
                (byte)Target.PointerSize,
                emitPrecode: true,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(StringImports);

            graph.AddRoot(ImportSectionsTable, "Import sections table is always generated");
            graph.AddRoot(ModuleImport, "Module import is always generated");
            graph.AddRoot(EagerImports, "Eager imports are always generated");
            graph.AddRoot(MethodImports, "Method imports are always generated");
            graph.AddRoot(DispatchImports, "Dispatch imports are always generated");
            graph.AddRoot(HelperImports, "Helper imports are always generated");
            graph.AddRoot(PrecodeImports, "Precode imports are always generated");
            graph.AddRoot(StringImports, "String imports are always generated");
            graph.AddRoot(Header, "ReadyToRunHeader is always generated");

            MetadataManager.AttachToDependencyGraph(graph);
        }
Ejemplo n.º 46
0
        public IExpression ParseExpression(PutbackRange <IToken> tokens, Import import)
        {
            var next = Expect(tokens, PrimaryExpressions.Keys);

            return(PrimaryExpressions[next.Type](this, import, next));
        }
Ejemplo n.º 47
0
 private static Import Process(Import import) {
     Thread.Sleep(import.Id * 2500 + 500);
     return import;
 }
Ejemplo n.º 48
0
        public void ImportDeviceIdFromSettingsFile_returns_device_id(string filename)
        {
            var id = Import.ImportDeviceIdFromSettingsFile($"{FixtureDir}/{filename}", LocalKey);

            Assert.Equal(DeviceId, id);
        }
Ejemplo n.º 49
0
        /// <summary>
        ///  Imports a less file and puts the root into the import node
        /// </summary>
        protected bool ImportLessFile(string lessPath, Import import)
        {
            string contents, file = null;
            if (IsEmbeddedResource(lessPath))
            {
                contents = ResourceLoader.GetResource(lessPath, FileReader, out file);
                if (contents == null) return false;
            }
            else
            {
                bool fileExists = FileReader.DoesFileExist(lessPath);
                if (!fileExists && !lessPath.EndsWith(".less"))
                {
                    lessPath += ".less";
                    fileExists = FileReader.DoesFileExist(lessPath);
                }

                if (!fileExists) return false;

                contents = FileReader.GetFileContents(lessPath);

                file = lessPath;
            }

            _paths.Add(Path.GetDirectoryName(import.Path));

            try
            {
                if (!string.IsNullOrEmpty(file))
                {
                    Imports.Add(file);
                }
                import.InnerRoot = Parser().Parse(contents, lessPath);
            }
            catch
            {
                Imports.Remove(file);
                throw;
            }
            finally
            {
                _paths.RemoveAt(_paths.Count - 1);
            }

            return true;
        }
Ejemplo n.º 50
0
 protected virtual void VisitImport(Import import)
 {
 }
 public void ParseFileTest()
 {
     var stuff = Import.Read(@"..\..\..\TestData\Governance\3S results.csv", "A", "K", "Please provide");
 }
Ejemplo n.º 52
0
 public void ImportDeviceIdFromSettings_as_xml_string_throws_on_invalid_xml()
 {
     Exceptions.AssertThrowsInternalError(() => Import.ImportDeviceIdFromSettings("> not really xml <"),
                                          "Failed to parse XML settings file");
 }
Ejemplo n.º 53
0
        protected void SetHTMLLogVariables(Import.DAImport.Common.DIImportFileType importType)
        {
            if (importType == DIImportFileType.SDMXXml)
            {
                this.UnmatchedIndicatorColumnName = "Indicator_GID";

                this.UnmatchedUnitColumnName = "Unit_GID";

                this.UnmatchedSubgroupValColumnName = "Subgroup_Val_GID";

                this.UnmatchedAreaColumnName = "Area_ID";

                this.DuplicateIndicatorColumnName = "Indicator_GID";
                this.DuplicateUnitColumnName = "Unit_GID";
                this.DuplicateSubgroupValColumnName = "Subgroup_Val_GID";

                this.SkippedIndicatorColumnName = "Indicator_GID";
                this.SkippedUnitColumnName = "Unit_GID";
                this.SkippedSubgroupValColumnName = "Subgroup_Val_GID";

            }
            else        // In case of ImportType = Spreadsheet, Database, template
            {
                // values are already Set by default..
                // no change
            }
        }
Ejemplo n.º 54
0
        private void ImportSampleProxy(SpecLabEntities _entities,
                                       DatabaseCommand <SampleSpecInfo, bool> paramCommand)
        {
            if (paramCommand.CallingInfo.TubeSampleSpecs.Count == 0)
            {
                throw new BusinessException(ErrorCode.ImportNoTube);
            }

            var sampleDbItem = (from sample in _entities.SampleSpecs
                                where sample.SampleSpecId.Equals(
                                    paramCommand.CallingInfo.SampleSpecId, StringComparison.OrdinalIgnoreCase)
                                select sample).FirstOrDefault();

            if (sampleDbItem != null)
            {
                throw new BusinessException(ErrorCode.SampleSpecIdExists);
            }

            var listTubeId           = paramCommand.CallingInfo.TubeSampleSpecs.Select(t => t.TubeId);
            var countTubeIdDuplicate = (from tube in _entities.TubeSamples
                                        where listTubeId.Contains(tube.TubeId)
                                        select tube.TubeId).Count();

            if (countTubeIdDuplicate > 0)
            {
                throw new BusinessException(ErrorCode.TubeIdExists);
            }

            for (int i = 0; i < paramCommand.CallingInfo.TubeSampleSpecs.Count - 1; i++)
            {
                if (paramCommand.CallingInfo.TubeSampleSpecs[i].Volume <= 0)
                {
                    throw new BusinessException(ErrorCode.ImportTubeEmptyVolume);
                }

                for (int j = i + 1; j < paramCommand.CallingInfo.TubeSampleSpecs.Count; j++)
                {
                    if (paramCommand.CallingInfo.TubeSampleSpecs[i].StorageId.Equals(
                            paramCommand.CallingInfo.TubeSampleSpecs[j].StorageId) &&
                        paramCommand.CallingInfo.TubeSampleSpecs[i].LocationNum ==
                        paramCommand.CallingInfo.TubeSampleSpecs[j].LocationNum)
                    {
                        throw new BusinessException(ErrorCode.DuplicateLocationId);
                    }
                }
            }

            for (int i = 0; i < paramCommand.CallingInfo.TubeSampleSpecs.Count; i++)
            {
                var tubeSampleSpecs = paramCommand.CallingInfo.TubeSampleSpecs[i];
                ValidateStorageId(_entities, tubeSampleSpecs.StorageId, tubeSampleSpecs.LocationNum);

                var innerQuery = (from t in _entities.TubeSamples
                                  where t.StorageId == tubeSampleSpecs.StorageId &&
                                  t.LocationNum == tubeSampleSpecs.LocationNum &&
                                  t.Status != (int)TubeSampleStatus.Remove
                                  select t.TubeId);

                if (innerQuery.Any())
                {
                    throw new BusinessException(ErrorCode.StorageLocationUsed, tubeSampleSpecs.StorageId, tubeSampleSpecs.LocationNum);
                }
            }

            var sexValue   = ((char)paramCommand.CallingInfo.Sex).ToString();
            var sampleSpec = new SampleSpec()
            {
                SampleSpecId = paramCommand.CallingInfo.SampleSpecId,
                Age          = paramCommand.CallingInfo.YearOfBirth,
                PatientName  = paramCommand.CallingInfo.PatientName,
                Sex          = sexValue,
                Source       = paramCommand.CallingInfo.LocationId,
                SampleNumber = paramCommand.CallingInfo.TubeSampleSpecs.Count,
                UserInput    = paramCommand.CallingInfo.UserInput,
                CreateDate   = DateTime.Now,
                UpdateDate   = DateTime.Now,
                DateInput    = paramCommand.CallingInfo.DateInput,
            };

            var importDbItem = new Import()
            {
                CreateDate   = DateTime.Now,
                UpdateDate   = DateTime.Now,
                ImportDate   = paramCommand.CallingInfo.DateInput,
                ImportUserId = paramCommand.CallingInfo.UserInput,
                SampleNumber = paramCommand.CallingInfo.TubeSampleSpecs.Count,
                ImportId     = paramCommand.CallingInfo.SampleSpecId
            };

            for (int i = 0; i < paramCommand.CallingInfo.TubeSampleSpecs.Count; i++)
            {
                var tubeSample = paramCommand.CallingInfo.TubeSampleSpecs[i];
                var tubeDbItem = new TubeSample()
                {
                    SampleSpecId = paramCommand.CallingInfo.SampleSpecId,
                    Status       = (int)TubeSampleStatus.Good,
                    TubeType     = (int)TubeSampleType.InStorage,
                    Volume       = tubeSample.Volume,
                    StorageId    = tubeSample.StorageId,
                    LocationNum  = tubeSample.LocationNum,
                    CreateDate   = DateTime.Now,
                    UpdateDate   = DateTime.Now,
                    TubeId       = tubeSample.TubeId,
                    TubeOrder    = i,
                    SampleType   = (int)tubeSample.SampleType
                };
                tubeDbItem.SampleHistories.Add(new SampleHistory()
                {
                    HistoryDate = DateTime.Now,
                    Action      = (int)HistoryAction.Import,
                    UserId      = paramCommand.CallingInfo.UserInput,
                    Status      = (int)TubeSampleStatus.Good,
                    TubeType    = (int)TubeSampleType.InStorage,
                    Volume      = tubeSample.Volume,
                    StorageId   = tubeSample.StorageId,
                    LocationNum = tubeSample.LocationNum,
                    TubeId      = tubeSample.TubeId,
                    Description = ""
                });

                sampleSpec.TubeSamples.Add(tubeDbItem);

                importDbItem.ImportDetails.Add(new ImportDetail()
                {
                    CreateDate  = DateTime.Now,
                    UpdateDate  = DateTime.Now,
                    Status      = (int)TubeSampleStatus.Good,
                    TubeType    = (int)TubeSampleType.InStorage,
                    StorageId   = tubeSample.StorageId,
                    LocationNum = tubeSample.LocationNum,
                    TubeId      = tubeSample.TubeId,
                    Volume      = tubeSample.Volume,
                });
            }

            _entities.SampleSpecs.Add(sampleSpec);
            _entities.Imports.Add(importDbItem);
            _entities.SaveChanges();
        }
Ejemplo n.º 55
0
 /// <summary>
 ///  returns true if the import should be ignored because it is a duplicate and import-once was used
 /// </summary>
 /// <param name="import"></param>
 /// <returns></returns>
 protected bool CheckIgnoreImport(Import import)
 {
     return CheckIgnoreImport(import, import.Path);
 }
Ejemplo n.º 56
0
    private void threadMethod()
    {
        try
        {
            bool cancel = false;
            using (ProgressBlock progress = new ProgressBlock(_plugin, "Bijwerken van status en nieuwe geocaches", "Download gegevens van globalcaching.eu", 1, 0, true))
            {
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    string doc = wc.DownloadString(string.Format("http://www.globalcaching.eu/Service/GeocacheCodes.aspx?country=Netherlands&token={0}", System.Web.HttpUtility.UrlEncode(_core.GeocachingComAccount.APIToken)));
                    if (doc != null)
                    {
                        List <string> gcList = new List <string>();

                        string[] lines = doc.Replace("\r", "").Split(new char[] { '\n' });
                        progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Bijwerken van de status...", lines.Length, 0);
                        Geocache gc;
                        char[]   sep = new char[] { ',' };
                        string[] parts;
                        foreach (string s in lines)
                        {
                            parts = s.Split(sep);
                            if (parts.Length > 2)
                            {
                                gc = DataAccess.GetGeocache(_core.Geocaches, parts[0]);
                                if (gc != null)
                                {
                                    gc.Archived  = parts[1] != "0";
                                    gc.Available = parts[2] != "0";
                                }
                                else if (parts[1] == "0") //add only none archived
                                {
                                    gcList.Add(parts[0]);
                                }
                            }
                        }

                        if (gcList.Count == 0)
                        {
                            System.Windows.Forms.MessageBox.Show("Er zijn geen nieuwe geocaches gevonden", "Bericht", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        }
                        else
                        {
                            if (System.Windows.Forms.MessageBox.Show(string.Format("Er zijn {0} nieuwe geocaches gevonden\r\nDeze downloaden?", gcList.Count), "Bericht", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                            {
                                progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", gcList.Count, 0);

                                using (GeocachingLiveV6 client = new GeocachingLiveV6(_core, string.IsNullOrEmpty(_core.GeocachingComAccount.APIToken)))
                                {
                                    int      index = 0;
                                    int      total = gcList.Count;
                                    int      gcupdatecount;
                                    TimeSpan interval = new TimeSpan(0, 0, 0, 2, 100);
                                    DateTime prevCall = DateTime.MinValue;
                                    bool     dodelay;
                                    gcupdatecount = 30;
                                    dodelay       = (gcList.Count > 30);
                                    while (gcList.Count > 0)
                                    {
                                        if (dodelay)
                                        {
                                            TimeSpan ts = DateTime.Now - prevCall;
                                            if (ts < interval)
                                            {
                                                Thread.Sleep(interval - ts);
                                            }
                                        }
                                        GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest req = new GlobalcachingApplication.Utils.API.LiveV6.SearchForGeocachesRequest();
                                        req.IsLite               = false;
                                        req.AccessToken          = client.Token;
                                        req.CacheCode            = new GlobalcachingApplication.Utils.API.LiveV6.CacheCodeFilter();
                                        req.CacheCode.CacheCodes = (from a in gcList select a).Take(gcupdatecount).ToArray();
                                        req.MaxPerPage           = gcupdatecount;
                                        req.GeocacheLogCount     = 5;
                                        index += req.CacheCode.CacheCodes.Length;
                                        gcList.RemoveRange(0, req.CacheCode.CacheCodes.Length);
                                        prevCall = DateTime.Now;
                                        var resp = client.Client.SearchForGeocaches(req);
                                        if (resp.Status.StatusCode == 0 && resp.Geocaches != null)
                                        {
                                            Import.AddGeocaches(_core, resp.Geocaches);
                                        }
                                        else
                                        {
                                            _errormessage = resp.Status.StatusMessage;
                                            break;
                                        }
                                        if (!progress.UpdateProgress("Bijwerken van status en nieuwe geocaches", "Importeren van geocaches...", total, index))
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            _errormessage = e.Message;
        }
        _actionReady.Set();
    }
Ejemplo n.º 57
0
        /// <summary>
        ///  Imports a css file and puts the contents into the import node
        /// </summary>
        protected bool ImportCssFileContents(string file, Import import)
        {
            if (!FileReader.DoesFileExist(file))
            {
                return false;
            }

            import.InnerContent = FileReader.GetFileContents(file);

            return true;
        }
Ejemplo n.º 58
0
        public void AttachToDependencyGraph(DependencyAnalyzerBase <NodeFactory> graph)
        {
            var compilerIdentifierNode = new CompilerIdentifierNode(Target);

            Header.Add(Internal.Runtime.ReadyToRunSectionType.CompilerIdentifier, compilerIdentifierNode, compilerIdentifierNode);

            RuntimeFunctionsTable = new RuntimeFunctionsTableNode(this);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.RuntimeFunctions, RuntimeFunctionsTable, RuntimeFunctionsTable);

            RuntimeFunctionsGCInfo = new RuntimeFunctionsGCInfoNode();
            graph.AddRoot(RuntimeFunctionsGCInfo, "GC info is always generated");

            ProfileDataSection = new ProfileDataSectionNode();
            Header.Add(Internal.Runtime.ReadyToRunSectionType.ProfileDataInfo, ProfileDataSection, ProfileDataSection.StartSymbol);

            ExceptionInfoLookupTableNode exceptionInfoLookupTableNode = new ExceptionInfoLookupTableNode(this);

            Header.Add(Internal.Runtime.ReadyToRunSectionType.ExceptionInfo, exceptionInfoLookupTableNode, exceptionInfoLookupTableNode);
            graph.AddRoot(exceptionInfoLookupTableNode, "ExceptionInfoLookupTable is always generated");

            ManifestMetadataTable = new ManifestMetadataTableNode(this);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.ManifestMetadata, ManifestMetadataTable, ManifestMetadataTable);
            Resolver.SetModuleIndexLookup(ManifestMetadataTable.ModuleToIndex);

            AssemblyTableNode assemblyTable = null;

            if (CompilationModuleGroup.CompilationModuleSet.Skip(1).Any())
            {
                assemblyTable = new AssemblyTableNode(Target);
                Header.Add(Internal.Runtime.ReadyToRunSectionType.ComponentAssemblies, assemblyTable, assemblyTable);
            }

            // Generate per assembly header tables
            int assemblyIndex = -1;

            foreach (EcmaModule inputModule in CompilationModuleGroup.CompilationModuleSet)
            {
                assemblyIndex++;
                HeaderNode tableHeader = Header;
                if (assemblyTable != null)
                {
                    AssemblyHeaderNode perAssemblyHeader = new AssemblyHeaderNode(Target, ReadyToRunFlags.READYTORUN_FLAG_Component, assemblyIndex);
                    assemblyTable.Add(perAssemblyHeader);
                    tableHeader = perAssemblyHeader;
                }

                MethodEntryPointTableNode methodEntryPointTable = new MethodEntryPointTableNode(inputModule, Target);
                tableHeader.Add(Internal.Runtime.ReadyToRunSectionType.MethodDefEntryPoints, methodEntryPointTable, methodEntryPointTable);

                TypesTableNode typesTable = new TypesTableNode(Target, inputModule);
                tableHeader.Add(Internal.Runtime.ReadyToRunSectionType.AvailableTypes, typesTable, typesTable);

                InliningInfoNode inliningInfoTable = new InliningInfoNode(Target, inputModule);
                tableHeader.Add(Internal.Runtime.ReadyToRunSectionType.InliningInfo2, inliningInfoTable, inliningInfoTable);

                // Core library attributes are checked FAR more often than other dlls
                // attributes, so produce a highly efficient table for determining if they are
                // present. Other assemblies *MAY* benefit from this feature, but it doesn't show
                // as useful at this time.
                if (inputModule == TypeSystemContext.SystemModule)
                {
                    AttributePresenceFilterNode attributePresenceTable = new AttributePresenceFilterNode(inputModule);
                    Header.Add(Internal.Runtime.ReadyToRunSectionType.AttributePresence, attributePresenceTable, attributePresenceTable);
                }
            }

            InstanceEntryPointTable = new InstanceEntryPointTableNode(this);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.InstanceMethodEntryPoints, InstanceEntryPointTable, InstanceEntryPointTable);

            ImportSectionsTable = new ImportSectionsTableNode(this);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.ImportSections, ImportSectionsTable, ImportSectionsTable.StartSymbol);

            DebugInfoTable = new DebugInfoTableNode(Target);
            Header.Add(Internal.Runtime.ReadyToRunSectionType.DebugInfo, DebugInfoTable, DebugInfoTable);

            EagerImports = new ImportSectionNode(
                "EagerImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_EAGER,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(EagerImports);

            // All ready-to-run images have a module import helper which gets patched by the runtime on image load
            ModuleImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                          ReadyToRunHelper.Module));
            graph.AddRoot(ModuleImport, "Module import is required by the R2R format spec");

            if (Target.Architecture != TargetArchitecture.X86)
            {
                Import personalityRoutineImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                                                 ReadyToRunHelper.PersonalityRoutine));
                PersonalityRoutine = new ImportThunk(
                    ReadyToRunHelper.PersonalityRoutine, this, personalityRoutineImport, useVirtualCall: false);
                graph.AddRoot(PersonalityRoutine, "Personality routine is faster to root early rather than referencing it from each unwind info");

                Import filterFuncletPersonalityRoutineImport = new Import(EagerImports, new ReadyToRunHelperSignature(
                                                                              ReadyToRunHelper.PersonalityRoutineFilterFunclet));
                FilterFuncletPersonalityRoutine = new ImportThunk(
                    ReadyToRunHelper.PersonalityRoutineFilterFunclet, this, filterFuncletPersonalityRoutineImport, useVirtualCall: false);
                graph.AddRoot(FilterFuncletPersonalityRoutine, "Filter funclet personality routine is faster to root early rather than referencing it from each unwind info");
            }

            MethodImports = new ImportSectionNode(
                "MethodImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: true);
            ImportSectionsTable.AddEmbeddedObject(MethodImports);

            DispatchImports = new ImportSectionNode(
                "DispatchImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: true);
            ImportSectionsTable.AddEmbeddedObject(DispatchImports);

            HelperImports = new ImportSectionNode(
                "HelperImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: false,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(HelperImports);

            PrecodeImports = new ImportSectionNode(
                "PrecodeImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_UNKNOWN,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_PCODE,
                (byte)Target.PointerSize,
                emitPrecode: true,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(PrecodeImports);

            StringImports = new ImportSectionNode(
                "StringImports",
                CorCompileImportType.CORCOMPILE_IMPORT_TYPE_STRING_HANDLE,
                CorCompileImportFlags.CORCOMPILE_IMPORT_FLAGS_UNKNOWN,
                (byte)Target.PointerSize,
                emitPrecode: true,
                emitGCRefMap: false);
            ImportSectionsTable.AddEmbeddedObject(StringImports);

            graph.AddRoot(ImportSectionsTable, "Import sections table is always generated");
            graph.AddRoot(ModuleImport, "Module import is always generated");
            graph.AddRoot(EagerImports, "Eager imports are always generated");
            graph.AddRoot(MethodImports, "Method imports are always generated");
            graph.AddRoot(DispatchImports, "Dispatch imports are always generated");
            graph.AddRoot(HelperImports, "Helper imports are always generated");
            graph.AddRoot(PrecodeImports, "Precode helper imports are always generated");
            graph.AddRoot(StringImports, "String imports are always generated");
            graph.AddRoot(Header, "ReadyToRunHeader is always generated");
            if (!CompilationModuleGroup.IsCompositeBuildMode)
            {
                graph.AddRoot(CopiedCorHeaderNode, "MSIL COR header is always generated for single-file R2R files");
            }
            graph.AddRoot(DebugDirectoryNode, "Debug Directory will always contain at least one entry");

            if (Win32ResourcesNode != null)
            {
                graph.AddRoot(Win32ResourcesNode, "Win32 Resources are placed if not empty");
            }

            MetadataManager.AttachToDependencyGraph(graph);
        }
Ejemplo n.º 59
0
 /// <summary>
 ///  Imports a css file from an embedded resource and puts the contents into the import node
 /// </summary>
 /// <param name="file"></param>
 /// <param name="import"></param>
 /// <returns></returns>
 private bool ImportEmbeddedCssContents(string file, Import import)
 {
     string content = ResourceLoader.GetResource(file, FileReader);
     if (content == null) return false;
     import.InnerContent = content;
     return true;
 }
Ejemplo n.º 60
0
        private void OnImportFileClicked(object sender, EventArgs e)
        {
            var selectedNodeAsContainer = _connectionTree.SelectedNode as ContainerInfo ?? _connectionTree.SelectedNode.Parent;

            Import.ImportFromFile(selectedNodeAsContainer);
        }