Пример #1
0
        //EVENT (BUTTON) XML SAVE (to file)
        private void btnXmlSave_Click(object sender, RoutedEventArgs e)
        {
            //settings object
            //WpfApp1.Properties.Settings settings = new Settings();

            //get XML (string) and PATH (from settings)
            //string xml = XmlController.Serialize(response);
            var    xml  = XmlController.Serialize(response);
            string path = settings.XmlPath;

            //write to file
            try
            {
                XmlController.WriteXMLToFile(xml, path);

                //messagebox
                System.Windows.MessageBox.Show("Your XML file has been saved.", "Save to File");
            }
            catch (UnauthorizedAccessException ex1)
            {
                System.Windows.Forms.MessageBox.Show("You have used an incorrect PATH in settings." + "\n" + ex1.Message, "Error");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("An unknown error has occured.", "Error");
            }
        }
Пример #2
0
        public Main()
        {
            InitializeComponent();

            string[] args = Environment.GetCommandLineArgs();

            if (!XmlController <SettingList> .TryDeserialize(SettingList.SettingFileName, out _settingList))
            {
                _settingList = new SettingList
                {
                    InstrumentList = new List <Instrument>()
                };
            }

            if (2 <= args.Length)
            {
                Parallel.For(0, args.Length - 1, i =>
                {
                    string exportPath      = Common.GetNewFilePath(args[i + 1], Common.ExportType.SerialNumber);
                    MidiController midiCon = new MidiController(_settingList);
                    if (midiCon.Convert(args[i + 1], exportPath))
                    {
                        _ = MessageBox.Show(this,
                                            $"{exportPath}にファイルを出力しました。",
                                            "成功",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                    }
                });
            }
        }
Пример #3
0
 public void Dispose()
 {
     rawData?.Clear();
     rawData = null;
     nameToRawDataIndex?.Clear();
     nameToRawDataIndex = null;
     controller?.Dispose();
     controller = null;
 }
Пример #4
0
        static void Main()
        {
            var xmlController = new XmlController<Queries>();

            // Deserialize
            var queriesCollection = xmlController.Deserialize(InputPath);

            // Serialize again
            xmlController.Serialize(queriesCollection, OutputPath);
        }
Пример #5
0
        //QUERY ONE PRODUCT
        public VinProduct.Response1 QueryOneProduct(string sku)     //public PS_Response1 QueryOneProduct(string sku)
        {
            bool   result;
            double count;

            //variables
            sku = txtQuerySku.Text;                                //what if it is BLANK or INCORRECT?
            pc  = new ProductController(WS_USERNAME, WS_PASSWORD); //create controller (to run query)

            //response = new PS_Response1();              //create (Response) object
            //product = new PS_Product1();                //create (Product) object for results
            response = new VinProduct.Response1();              //create (Response) object
            product  = new VinProduct.Product1();               //create (Product) object for results

            //need to run query
            //***************************************
            response = pc.PS_SearchProductBySKU2(sku);
            //***************************************

            //was result successful?
            result = (bool)response.IsSuccessful;
            count  = (double)response.RecordCount;

            if (result && count > 0)      //if true
            {
                if (count == 1)           //only ONE product (make sure)
                {
                    //create a product
                    //product = response.Products[0];
                    //show results
                    //txtVin65Xml.Text = XmlController.Serialize(product);      //xml for product
                    txtVin65Xml.Text = XmlController.Serialize(response);       //xml for entire response
                }
            }
            else if (count == 0)
            {
                txtVin65Xml.Text = "There were no results found.";              //RecordCount is zero(0)
            }

            return(response);

            //product = pc.PS_SearchProductBySKU(sku);
            //product.

            //product = pc.PS_SearchProductBySKU("739242");

            //need to confirm in was successful



            //need to show results
            //txtVin65Xml.Text = XmlController.Serialize(pc.PS_SearchProductBySKU(sku));
            //XmlController.Serialize(pc2.PS_SearchAllProducts2()));
        }
Пример #6
0
        static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookstoreDbContext, Configuration>());

            var db = new BookstoreDbContext();

            db.Authors.Count();

            var xmlController = new XmlController<CatalogXml>();
            var books = xmlController.Deserialize(XmlInputPath).Books;

            foreach (var book in books)
            {
                var authors = new List<Author>();
                if (book.Authors != null)
                {
                    foreach (var auth in book.Authors)
                    {
                        authors.Add(new Author() { Name = auth });
                    }
                }

                var reviews = new List<Review>();

                if (book.Reviews != null)
                {
                    foreach (var review in book.Reviews)
                    {
                        reviews.Add(new Review()
                        {
                            Author = new Author() { Name = review.Author == null ? null : review.Author },
                            CreationDate = review.Date != null ? DateTime.Parse(review.Date) : DateTime.MinValue
                        });
                    }
                }

                var bookToAdd = db.Books.Add(new Book()
                {
                    Title = book.Title,
                    Isbn = book.Isbn,
                    Price = book.Price,
                    WebSite = book.Website
                });

                bookToAdd.Reviews = reviews;
                bookToAdd.Authors = authors;

                db.Books.Add(bookToAdd);
            }

            db.SaveChanges();
        }
        public IHttpActionResult FuncCount(string repoUrl, uint diff = 10, uint times = 10)
        {
            var path       = GitController.InitRepository(repoUrl);
            var funcCounts = new List <int>();

            for (var i = 0; i < times; i++)
            {
                var srcmlPath = SrcmlController.ParseSources(path);
                funcCounts.Add(XmlController.CountFuncs(srcmlPath));
                GitController.TimeTravelCommits(path, diff);
            }
            return(Ok(new XmlOutput <int>(funcCounts.ToArray(), JobType.FuncCount)));
        }
        public IHttpActionResult AverageRowCountPerFunction(string repoUrl, uint diff = 10, uint times = 10)
        {
            var path         = GitController.InitRepository(repoUrl);
            var avgRowCounts = new List <double>();

            for (var i = 0; i < times; i++)
            {
                var srcmlPath = SrcmlController.ParseSources(path);
                avgRowCounts.Add(XmlController.GetAverageRowsPerFunction(srcmlPath));
                GitController.TimeTravelCommits(path, diff);
            }
            return(Ok(new XmlOutput <double>(avgRowCounts.ToArray(), JobType.AvgRowsPerFunction)));
        }
Пример #9
0
        public override object Deserialize(XmlNode node)
        {
            string text = node.Value;

            var found = TypeResolver.Resolve(text);

            if (found == null)
            {
                XmlController.Log($"[WARN] Failed to resolve type '{text}' for node {node.GetXPath()}");
            }

            return(found);
        }
        public IHttpActionResult Imports(string repoUrl, uint diff = 10, uint times = 10)
        {
            var path         = GitController.InitRepository(repoUrl);
            var importCounts = new List <Dictionary <string, int> >();

            for (var i = 0; i < times; i++)
            {
                var srcmlPath = SrcmlController.ParseSources(path);
                importCounts.Add(XmlController.CountImports(srcmlPath));
                GitController.TimeTravelCommits(path, diff);
            }
            var orderedCounts = Sort(importCounts);

            return(Ok(new XmlOutput <List <KeyValuePair <string, int> > >(orderedCounts.ToArray(), JobType.Imports)));
        }
Пример #11
0
    public void EndGame(EndReason endReason = EndReason.Escape)
    {
        IsGameStarted = false;
        UIController.Instance.EndGame();
        Maze.Instance.DestroyMaze();

        TempResult.lifetime       = (int)TimeSpan.FromTicks(DateTime.Now.Ticks - TempResult.startDate.Ticks).TotalSeconds;
        TempResult.endReason      = endReason.ToString();
        TempResult.coinsCollected = CoinsCollected;
        XmlController.UpdateResults(TempResult);

        CoinsCollected  = 0;
        CurCoinsAmmount = 0;
        zombiesAmmount  = 0;
        isMummySpawned  = false;
    }
 //
 //======================================================================================================
 //
 public static void installNode(CoreController core, XmlNode rootNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
 {
     return_ErrorMessage = "";
     return_UpgradeOK    = true;
     try {
         string Basename = GenericController.toLCase(rootNode.Name);
         if (Basename == "layout")
         {
             bool   IsFound    = false;
             string layoutName = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "name", "No Name");
             if (string.IsNullOrEmpty(layoutName))
             {
                 layoutName = "No Name";
             }
             string layoutGuid = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "guid", layoutName);
             if (string.IsNullOrEmpty(layoutGuid))
             {
                 layoutGuid = layoutName;
             }
             var layout = DbBaseModel.create <LayoutModel>(core.cpParent, layoutGuid);
             if (layout == null)
             {
                 layout = DbBaseModel.createByUniqueName <LayoutModel>(core.cpParent, layoutName);
             }
             if (layout == null)
             {
                 layout = DbBaseModel.addDefault <LayoutModel>(core.cpParent);
             }
             layout.ccguid                  = layoutGuid;
             layout.name                    = layoutName;
             layout.layout.content          = rootNode.InnerText;
             layout.installedByCollectionId = collectionId;
             layout.save(core.cpParent);
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
Пример #13
0
    private void UpdatePreviousResults()
    {
        foreach (Transform child in previousResultsContent.transform)
        {
            Destroy(child.gameObject);
        }

        var resContainer = XmlController.GetResults();

        resContainer.Results.Reverse();

        foreach (var res in resContainer.Results)
        {
            var resText = Instantiate(previousResultsText);
            resText.text = "Alias: " + res.alias +
                           "\nCollected " + res.coinsCollected + " coins" +
                           "\nLifetime: " + res.lifetime + " seconds" +
                           "\nStart date: " + res.startDate.ToString("dd/MM/yyyy HH:mm:ss") +
                           "\nEnd reason: " + res.endReason;
            resText.transform.SetParent(previousResultsContent.transform);
            resText.transform.localScale = Vector3.one;
        }
    }
        public void sendHeartBeat(object source, ElapsedEventArgs e)
        {
            Uri           rabbitMQUri   = new Uri(Constant.RabbitMQConnectionUrl);
            Services      services      = new Services();
            XmlController xmlController = new XmlController();

            var factory = new ConnectionFactory
            {
                Uri = rabbitMQUri
            };

            using var connection = factory.CreateConnection();
            using var channel    = connection.CreateModel();

            string xmlString = services.getHeartBeat();

            //Console.WriteLine(xmlString);
            if (xmlController.XSDValidatie(xmlString, "heartbeat"))
            {
                var xml = Encoding.UTF8.GetBytes(xmlString);
                channel.BasicPublish("", Constant.RabbitMQHeartBeatName, null, xml);
            }
        }
        /// <summary>
        /// В данном методе происходит создание объектной модели, создание на ее основе документации и ее сохранение.
        /// </summary>
        public void CreateAndSave()
        {
            var template = new MarkdownTemplate(_generateMode);
            var xml      = new XmlController(_generateMode);

            template.CreateTemplate();
            var elements = xml
                           .GetElements(CreateRelationsFromTypesHash().ToList());

            CreateFileNumbers(elements);
            var namespaces = new NamepacesIndexPageModel {
                NamespacesList = new List <MarkdownTemplateModel>()
            };

            foreach (var model in elements /*.OrderBy(model => model.RelativeKey)*/.ToList())
            {
                if (!model.IsTargetType)
                {
                    continue;
                }
                if (model.RelativeKey != template.CurrentRelativeKey)
                {
                    Write(template.CurrentRelativeKey);
                    template.CurrentRelativeKey = model.RelativeKey;
                    template.CreateTemplate();
                    Write(template.CurrentRelativeKey);
                }
                model.MdKey = _generateMode.MdKey;
                Save(template.CreateMdText(model), $"{_generateMode.OutPath}{model.FilePath}");
                Write(model.FullName + $" {model.RelativeKey}");
                if (model.TypeForm == "Пространство имен")
                {
                    namespaces.NamespacesList.Add(model);
                }
            }
            Save(template.CreateMdIndexPage(namespaces), $"{_generateMode.OutPath}Index.md");
        }
Пример #16
0
        //QUERY ALL PRODUCTS
        private VinProduct.Response1 QueryAllProducts()         //private PS_Response1 QueryAllProducts()
        {
            bool   result;
            double count;

            //variables
            pc = new ProductController(WS_USERNAME, WS_PASSWORD);               //create controller (to run query)
            //response = new PS_Response1();              //create (Response) object
            //product = new PS_Product1();                //create (Product) object for results
            response = new VinProduct.Response1();              //create (Response) object
            product  = new VinProduct.Product1();               //create (Product) object for results

            //need to run query
            //***************************************
            response = pc.PS_SearchAllProducts2();
            //***************************************

            //was result successful?
            result = (bool)response.IsSuccessful;
            count  = (double)response.RecordCount;

            if (result && count > 0)      //if true
            {
                //create a list of products
                //products = response.Products;
                //show results
                //txtVin65Xml.Text = XmlController.Serialize(products);     //xml for products
                txtVin65Xml.Text = XmlController.Serialize(response);           //xml for entire response
            }
            else if (count == 0)
            {
                txtVin65Xml.Text = "There were no results found.";              //RecordCount is zero(0)
            }

            return(response);
        }
 public Form1()
 {
     InitializeComponent();
     xc = new XmlController();
     xc.readXml(); //reads the xml when starts
 }
Пример #18
0
        /// <summary>
        /// Modifies the main list to combine it with the elements of the secondary list.
        /// The method used to combine is set using the mode parameter.
        /// The secondary list is not modified.
        /// </summary>
        public static void Combine(IList main, IList secondary, ListMergeMode mode)
        {
            if (main == null || secondary == null || secondary.Count == 0)
            {
                return;
            }

            if ((main.IsFixedSize || main.IsReadOnly) && mode != ListMergeMode.Replace)
            {
                XmlController.Log("[ERROR] Main list is fixed size or read only.");
                return;
            }

            switch (mode)
            {
            case ListMergeMode.Replace:

                // Clear list and add all values from other list.
                main.Clear();
                foreach (var value in secondary)
                {
                    main.Add(value);
                }

                break;

            case ListMergeMode.Append:

                // Simply add all values from secondary to primary.
                foreach (var value in secondary)
                {
                    main.Add(value);
                }

                break;

            case ListMergeMode.Merge:

                // Add all values from other list, if they are not already in the list.
                foreach (var value in secondary)
                {
                    if (!main.Contains(value))
                    {
                        temp.Add(value);
                    }
                }
                foreach (var value in temp)
                {
                    main.Add(value);
                }

                break;

            case ListMergeMode.MergeReplace:
                // Add all values from the other list, if they are not already in the list.
                // If they already are in the list, replace it with the new value.
                // Useful for custom classes that override .equals()
                foreach (var value in secondary)
                {     // TODO left off here, needs to work like Merge where items are inserted.
                    int index = main.IndexOf(value);
                    if (index != -1)
                    {
                        temp.Add(value);
                    }
                }

                foreach (var value in secondary)
                {
                    int index = main.IndexOf(value);
                    if (index == -1)
                    {
                        main.Add(value);
                    }
                    else
                    {
                        main.RemoveAt(index);
                        main.Insert(index, value);
                    }
                }

                break;

            case ListMergeMode.Subtract:

                // Removes values from main if they are in secondary.
                foreach (var value in secondary)
                {
                    if (main.Contains(value))
                    {
                        main.Remove(value);
                    }
                }

                break;

            default:
                XmlController.Log($"[ERROR] {mode} is not implemented.");
                break;
            }

            temp.Clear();
            temp2.Clear();
        }
        //
        //====================================================================================================
        /// <summary>
        /// Builds collection folders for a collectionZip file
        /// unzip a folder and if the collection is not in the collections installed or the collectionsToInstall, save the collection to the appropriate collection folder and add it to the collectionsToInstall
        /// </summary>
        /// <param name="core"></param>
        /// <param name="sourceTempFolderPathFilename"></param>
        /// <param name="CollectionLastChangeDate"></param>
        /// <param name="collectionGuid"></param>
        /// <param name="return_ErrorMessage"></param>
        /// <param name="collectionsDownloaded">collection guids that have been saved to the collection folder and need to be saved to the database druing this install.</param>
        /// <param name="collectionsInstalledList">collection guids that have been saved to the database during this install.</param>
        /// <param name="collectionsBuildingFolder">folder building is recursive. These are the collection guids whose folders are currently being built.</param>
        /// <returns></returns>
        public static bool buildCollectionFolderFromCollectionZip(CoreController core, Stack <string> contextLog, string sourceTempFolderPathFilename, DateTime CollectionLastChangeDate, ref string return_ErrorMessage, ref List <string> collectionsDownloaded, ref List <string> collectionsInstalledList, ref List <string> collectionsBuildingFolder)
        {
            try {
                //
                contextLog.Push(MethodInfo.GetCurrentMethod().Name + ", [" + sourceTempFolderPathFilename + "]");
                traceContextLog(core, contextLog);
                //
                string collectionPath     = "";
                string collectionFilename = "";
                core.tempFiles.splitDosPathFilename(sourceTempFolderPathFilename, ref collectionPath, ref collectionFilename);
                string CollectionVersionFolderName = "";
                if (!core.tempFiles.pathExists(collectionPath))
                {
                    //
                    // return false, The working folder is not there
                    return_ErrorMessage = "<p>There was a problem with the installation. The installation folder is not valid.</p>";
                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, CheckFileFolder was false for the temp folder [" + collectionPath + "]");
                    return(false);
                }
                //
                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, processing files in temp folder [" + collectionPath + "]");
                //
                // --move collection file to a temp directory
                // -- use try-finally to delete temp folder
                string tmpInstallPath = "tmpInstallCollection" + GenericController.getGUIDNaked() + "\\";
                try {
                    core.tempFiles.copyFile(sourceTempFolderPathFilename, tmpInstallPath + collectionFilename);
                    if (collectionFilename.ToLowerInvariant().Substring(collectionFilename.Length - 4) == ".zip")
                    {
                        core.tempFiles.unzipFile(tmpInstallPath + collectionFilename);
                        core.tempFiles.deleteFile(tmpInstallPath + collectionFilename);
                    }
                    //
                    // -- find xml file in temp folder and process it
                    bool CollectionXmlFileFound = false;
                    foreach (FileDetail file in core.tempFiles.getFileList(tmpInstallPath))
                    {
                        if (file.Name.Substring(file.Name.Length - 4).ToLower(CultureInfo.InvariantCulture) == ".xml")
                        {
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", build collection folder for Collection file [" + file.Name + "]");
                            //
                            XmlDocument CollectionFile = new XmlDocument();
                            try {
                                CollectionFile.LoadXml(core.tempFiles.readFileText(tmpInstallPath + file.Name));
                            } catch (Exception ex) {
                                //
                                // -- There was a parse error in this xml file. Set the return message and the flag
                                // -- If another xml files shows up, and process OK it will cover this error
                                return_ErrorMessage = "There was a problem installing the Collection File [" + tmpInstallPath + file.Name + "]. The error reported was [" + ex.Message + "].";
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, error reading collection [" + sourceTempFolderPathFilename + "]");
                                continue;
                            }
                            string CollectionFileBaseName = GenericController.toLCase(CollectionFile.DocumentElement.Name);
                            if ((CollectionFileBaseName != "contensivecdef") && (CollectionFileBaseName != CollectionFileRootNode) && (CollectionFileBaseName != GenericController.toLCase(CollectionFileRootNodeOld)))
                            {
                                //
                                // -- Not a problem, this is just not a collection file
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, xml base name wrong [" + CollectionFileBaseName + "]");
                                continue;
                            }
                            bool IsFound = false;
                            //
                            // Collection File
                            //
                            string Collectionname = XmlController.getXMLAttribute(core, ref IsFound, CollectionFile.DocumentElement, "name", "");
                            string collectionGuid = XmlController.getXMLAttribute(core, ref IsFound, CollectionFile.DocumentElement, "guid", Collectionname);
                            if ((!collectionsInstalledList.Contains(collectionGuid.ToLower(CultureInfo.InvariantCulture))) && (!collectionsDownloaded.Contains(collectionGuid.ToLower(CultureInfo.InvariantCulture))))
                            {
                                if (string.IsNullOrEmpty(Collectionname))
                                {
                                    //
                                    // ----- Error condition -- it must have a collection name
                                    //
                                    return_ErrorMessage = "<p>There was a problem with this Collection. The collection file does not have a collection name.</p>";
                                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, collection has no name");
                                    continue;
                                }
                                //
                                //------------------------------------------------------------------
                                // Build Collection folder structure in /Add-ons folder
                                //------------------------------------------------------------------
                                //
                                collectionsDownloaded.Add(collectionGuid.ToLower(CultureInfo.InvariantCulture));
                                CollectionXmlFileFound = true;
                                if (string.IsNullOrEmpty(collectionGuid))
                                {
                                    //
                                    // must have a guid
                                    collectionGuid = Collectionname;
                                }
                                //
                                //
                                CollectionVersionFolderName = verifyCollectionVersionFolderName(core, collectionGuid, Collectionname);
                                string CollectionVersionFolder = AddonController.getPrivateFilesAddonPath() + CollectionVersionFolderName;
                                //
                                core.tempFiles.copyPath(tmpInstallPath, CollectionVersionFolder, core.privateFiles);
                                //
                                // -- iterate through all nodes of this collection xml file and install all dependencies
                                foreach (XmlNode metaDataSection in CollectionFile.DocumentElement.ChildNodes)
                                {
                                    string ChildCollectionGUID = null;
                                    string ChildCollectionName = null;
                                    bool   Found = false;
                                    switch (GenericController.toLCase(metaDataSection.Name))
                                    {
                                    case "resource":
                                        break;

                                    case "getcollection":
                                    case "importcollection":
                                        //
                                        // -- Download Collection file into install folder
                                        ChildCollectionName = XmlController.getXMLAttribute(core, ref Found, metaDataSection, "name", "");
                                        ChildCollectionGUID = XmlController.getXMLAttribute(core, ref Found, metaDataSection, "guid", metaDataSection.InnerText);
                                        if (string.IsNullOrEmpty(ChildCollectionGUID))
                                        {
                                            ChildCollectionGUID = metaDataSection.InnerText;
                                        }
                                        ChildCollectionGUID = GenericController.normalizeGuid(ChildCollectionGUID);
                                        string statusMsg = "Installing collection [" + ChildCollectionName + ", " + ChildCollectionGUID + "] referenced from collection [" + Collectionname + "]";
                                        LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, getCollection or importcollection, childCollectionName [" + ChildCollectionName + "], childCollectionGuid [" + ChildCollectionGUID + "]");
                                        if (GenericController.strInstr(1, CollectionVersionFolder, ChildCollectionGUID, 1) == 0)
                                        {
                                            if (string.IsNullOrEmpty(ChildCollectionGUID))
                                            {
                                                //
                                                // -- Needs a GUID to install
                                                return_ErrorMessage = statusMsg + ". The installation can not continue because an imported collection could not be downloaded because it does not include a valid GUID.";
                                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, return message [" + return_ErrorMessage + "]");
                                            }
                                            else
                                            {
                                                if ((!collectionsBuildingFolder.Contains(ChildCollectionGUID)) && (!collectionsDownloaded.Contains(ChildCollectionGUID)) && (!collectionsInstalledList.Contains(ChildCollectionGUID)))
                                                {
                                                    //
                                                    // -- add to the list of building folders to block recursive loop
                                                    collectionsBuildingFolder.Add(ChildCollectionGUID);
                                                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, [" + ChildCollectionGUID + "], not found so needs to be installed");
                                                    //
                                                    // If it is not already installed, download and install it also
                                                    //
                                                    string   workingTempPath = GenericController.getGUIDNaked() + "\\";
                                                    DateTime libraryCollectionLastModifiedDate = default(DateTime);
                                                    try {
                                                        //
                                                        // try-finally to delete the working folder
                                                        if (!CollectionLibraryController.downloadCollectionFromLibrary(core, workingTempPath, ChildCollectionGUID, ref libraryCollectionLastModifiedDate, ref return_ErrorMessage))
                                                        {
                                                            //
                                                            // -- did not download correctly
                                                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, [" + statusMsg + "], downloadCollectionFiles returned error state, message [" + return_ErrorMessage + "]");
                                                            if (string.IsNullOrEmpty(return_ErrorMessage))
                                                            {
                                                                return_ErrorMessage = statusMsg + ". The installation can not continue because there was an unknown error while downloading the necessary collection file, [" + ChildCollectionGUID + "].";
                                                            }
                                                            else
                                                            {
                                                                return_ErrorMessage = statusMsg + ". The installation can not continue because there was an error while downloading the necessary collection file, guid [" + ChildCollectionGUID + "]. The error was [" + return_ErrorMessage + "]";
                                                            }
                                                        }
                                                        else
                                                        {
                                                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, libraryCollectionLastChangeDate [" + libraryCollectionLastModifiedDate.ToString() + "].");
                                                            bool installDependentCollection = true;
                                                            var  localCollectionConfig      = CollectionFolderModel.getCollectionFolderConfig(core, ChildCollectionGUID);
                                                            if (localCollectionConfig == null)
                                                            {
                                                                //
                                                                // -- collection not installed, ok to install
                                                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, collection");
                                                            }
                                                            else
                                                            {
                                                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, localCollectionConfig.lastChangeDate [" + localCollectionConfig.lastChangeDate.ToString() + "].");
                                                                if (localCollectionConfig.lastChangeDate < libraryCollectionLastModifiedDate)
                                                                {
                                                                    //
                                                                    // -- downloaded collection is newer than installed collection, reinstall
                                                                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, **** local version is older than library, needs to reinstall.");
                                                                }
                                                                else
                                                                {
                                                                    //
                                                                    // -- download is older than installed, skip the rest of the xml file processing
                                                                    installDependentCollection = false;
                                                                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, **** local version is newer or the same as library, can skip install.");
                                                                    break;
                                                                }
                                                            }
                                                            if (installDependentCollection)
                                                            {
                                                                //
                                                                // -- install the downloaded file
                                                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, collection missing or needs to be updated.");
                                                                if (!buildCollectionFoldersFromCollectionZips(core, contextLog, workingTempPath, libraryCollectionLastModifiedDate, ref collectionsDownloaded, ref return_ErrorMessage, ref collectionsInstalledList, ref collectionsBuildingFolder))
                                                                {
                                                                    LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, [" + statusMsg + "], BuildLocalCollectionFolder returned error state, message [" + return_ErrorMessage + "]");
                                                                    if (string.IsNullOrEmpty(return_ErrorMessage))
                                                                    {
                                                                        return_ErrorMessage = statusMsg + ". The installation can not continue because there was an unknown error installing the included collection file, guid [" + ChildCollectionGUID + "].";
                                                                    }
                                                                    else
                                                                    {
                                                                        return_ErrorMessage = statusMsg + ". The installation can not continue because there was an unknown error installing the included collection file, guid [" + ChildCollectionGUID + "]. The error was [" + return_ErrorMessage + "]";
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception) {
                                                        //
                                                        // -- exception in try-finally for folder handling, just rethrow to the catch for hte method
                                                        throw;
                                                    } finally {
                                                        //
                                                        // -- remove child installation working folder
                                                        core.tempFiles.deleteFolder(workingTempPath);
                                                        //
                                                        // -- no longer building this folder
                                                        collectionsBuildingFolder.Remove(ChildCollectionGUID);
                                                    }
                                                }
                                            }
                                        }
                                        break;
                                    }
                                    if (!string.IsNullOrEmpty(return_ErrorMessage))
                                    {
                                        //
                                        // -- if error during xml processing, skip the rest of the xml nodes and go to the next file.
                                        break;
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(return_ErrorMessage))
                            {
                                //
                                // -- stop processing xml nodes if error
                                break;
                            }
                            //
                            // If the collection parsed correctly, update the Collections.xml file and exit loop
                            updateCollectionFolderConfig(core, Collectionname, collectionGuid, CollectionLastChangeDate, CollectionVersionFolderName);
                            break;
                        }
                        if (!string.IsNullOrEmpty(return_ErrorMessage))
                        {
                            //
                            // -- stop files if error
                            break;
                        }
                    }
                    //
                    // -- all files finished
                    if (string.IsNullOrEmpty(return_ErrorMessage) && !CollectionXmlFileFound)
                    {
                        //
                        // no errors, but xml file not found. Make an error
                        return_ErrorMessage = "<p>There was a problem with the installation. The collection zip was not downloaded successfully.</p>";
                    }
                } catch (Exception) {
                    throw;
                } finally {
                    //
                    // delete the tmp working folder
                    core.tempFiles.deleteFolder(tmpInstallPath);
                }
                //
                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", BuildLocalCollectionFolder, Exiting with ErrorMessage [" + return_ErrorMessage + "]");
                //
                return(string.IsNullOrEmpty(return_ErrorMessage));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            } finally {
                contextLog.Pop();
            }
        }
Пример #20
0
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode AddonNode, string AddonGuidFieldName, int CollectionID, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            // todo - return bool
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = GenericController.toLCase(AddonNode.Name);
                if ((Basename == "page") || (Basename == "process") || (Basename == "addon") || (Basename == "add-on"))
                {
                    bool   IsFound   = false;
                    string addonName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "name", "No Name");
                    if (string.IsNullOrEmpty(addonName))
                    {
                        addonName = "No Name";
                    }
                    string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "guid", addonName);
                    if (string.IsNullOrEmpty(addonGuid))
                    {
                        addonGuid = addonName;
                    }
                    string navTypeName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "type", "");
                    int    navTypeId   = getListIndex(navTypeName, navTypeIDList);
                    if (navTypeId == 0)
                    {
                        navTypeId = NavTypeIDAddon;
                    }
                    using (var cs = new CsModel(core)) {
                        string Criteria = "(" + AddonGuidFieldName + "=" + DbController.encodeSQLText(addonGuid) + ")";
                        cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                        if (cs.ok())
                        {
                            //
                            // Update the Addon
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, GUID match with existing Add-on, Updating Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            //
                            // not found by GUID - search name against name to update legacy Add-ons
                            //
                            cs.close();
                            Criteria = "(name=" + DbController.encodeSQLText(addonName) + ")and(" + AddonGuidFieldName + " is null)";
                            cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on name matched an existing Add-on that has no GUID, Updating legacy Aggregate Function to Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // not found by GUID or by name, Insert a new addon
                            //
                            cs.close();
                            cs.insert(AddonModel.tableMetadata.contentName);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Creating new Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // Could not create new Add-on
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on could not be created, skipping Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            int addonId = cs.getInteger("ID");
                            MetadataController.deleteContentRecords(core, "Add-on Include Rules", "addonid=" + addonId);
                            MetadataController.deleteContentRecords(core, "Add-on Content Trigger Rules", "addonid=" + addonId);
                            //
                            cs.set("collectionid", CollectionID);
                            cs.set(AddonGuidFieldName, addonGuid);
                            cs.set("name", addonName);
                            cs.set("navTypeId", navTypeId);
                            var ArgumentList = new StringBuilder();
                            var StyleSheet   = new StringBuilder();
                            if (AddonNode.ChildNodes.Count > 0)
                            {
                                foreach (XmlNode Addonfield in AddonNode.ChildNodes)
                                {
                                    if (!(Addonfield is XmlComment))
                                    {
                                        XmlNode PageInterface = Addonfield;
                                        string  fieldName     = null;
                                        string  FieldValue    = "";
                                        switch (GenericController.toLCase(Addonfield.Name))
                                        {
                                        case "activexdll": {
                                            //
                                            // This is handled in BuildLocalCollectionFolder
                                            //
                                            break;
                                        }

                                        case "editors": {
                                            //
                                            // list of editors
                                            //
                                            foreach (XmlNode TriggerNode in Addonfield.ChildNodes)
                                            {
                                                //
                                                int    fieldTypeId = 0;
                                                string fieldType   = null;
                                                switch (GenericController.toLCase(TriggerNode.Name))
                                                {
                                                case "type": {
                                                    fieldType   = TriggerNode.InnerText;
                                                    fieldTypeId = MetadataController.getRecordIdByUniqueName(core, "Content Field Types", fieldType);
                                                    if (fieldTypeId > 0)
                                                    {
                                                        using (var CS2 = new CsModel(core)) {
                                                            Criteria = "(addonid=" + addonId + ")and(contentfieldTypeID=" + fieldTypeId + ")";
                                                            CS2.open("Add-on Content Field Type Rules", Criteria);
                                                            if (!CS2.ok())
                                                            {
                                                                CS2.insert("Add-on Content Field Type Rules");
                                                            }
                                                            if (CS2.ok())
                                                            {
                                                                CS2.set("addonid", addonId);
                                                                CS2.set("contentfieldTypeID", fieldTypeId);
                                                            }
                                                        }
                                                    }
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            break;
                                        }

                                        case "processtriggers": {
                                            //
                                            // list of events that trigger a process run for this addon
                                            //
                                            foreach (XmlNode TriggerNode in Addonfield.ChildNodes)
                                            {
                                                switch (GenericController.toLCase(TriggerNode.Name))
                                                {
                                                case "contentchange": {
                                                    int    TriggerContentId  = 0;
                                                    string ContentNameorGuid = TriggerNode.InnerText;
                                                    if (string.IsNullOrEmpty(ContentNameorGuid))
                                                    {
                                                        ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "guid", "");
                                                        if (string.IsNullOrEmpty(ContentNameorGuid))
                                                        {
                                                            ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "name", "");
                                                        }
                                                    }
                                                    using (var CS2 = new CsModel(core)) {
                                                        Criteria = "(ccguid=" + DbController.encodeSQLText(ContentNameorGuid) + ")";
                                                        CS2.open("Content", Criteria);
                                                        if (!CS2.ok())
                                                        {
                                                            Criteria = "(ccguid is null)and(name=" + DbController.encodeSQLText(ContentNameorGuid) + ")";
                                                            CS2.open("content", Criteria);
                                                        }
                                                        if (CS2.ok())
                                                        {
                                                            TriggerContentId = CS2.getInteger("ID");
                                                        }
                                                    }
                                                    if (TriggerContentId != 0)
                                                    {
                                                        using (var CS2 = new CsModel(core)) {
                                                            Criteria = "(addonid=" + addonId + ")and(contentid=" + TriggerContentId + ")";
                                                            CS2.open("Add-on Content Trigger Rules", Criteria);
                                                            if (!CS2.ok())
                                                            {
                                                                CS2.insert("Add-on Content Trigger Rules");
                                                                if (CS2.ok())
                                                                {
                                                                    CS2.set("addonid", addonId);
                                                                    CS2.set("contentid", TriggerContentId);
                                                                }
                                                            }
                                                            CS2.close();
                                                        }
                                                    }
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            break;
                                        }

                                        case "scripting": {
                                            //
                                            // include add-ons - NOTE - import collections must be run before interfaces
                                            // when importing a collectin that will be used for an include
                                            int    scriptinglanguageid = (int)AddonController.ScriptLanguages.VBScript;
                                            string ScriptingLanguage   = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "language", "").ToLowerInvariant();
                                            if (ScriptingLanguage.Equals("javascript") || ScriptingLanguage.Equals("jscript"))
                                            {
                                                scriptinglanguageid = (int)AddonController.ScriptLanguages.Javascript;
                                            }
                                            cs.set("scriptinglanguageid", scriptinglanguageid);
                                            string ScriptingEntryPoint = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "entrypoint", "");
                                            cs.set("ScriptingEntryPoint", ScriptingEntryPoint);
                                            int ScriptingTimeout = GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "timeout", "5000"));
                                            cs.set("ScriptingTimeout", ScriptingTimeout);
                                            string ScriptingCode = "";
                                            foreach (XmlNode ScriptingNode in Addonfield.ChildNodes)
                                            {
                                                switch (GenericController.toLCase(ScriptingNode.Name))
                                                {
                                                case "code": {
                                                    ScriptingCode += ScriptingNode.InnerText;
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            cs.set("ScriptingCode", ScriptingCode);
                                            break;
                                        }

                                        case "activexprogramid": {
                                            //
                                            // save program id
                                            //
                                            FieldValue = Addonfield.InnerText;
                                            cs.set("ObjectProgramID", FieldValue);
                                            break;
                                        }

                                        case "navigator": {
                                            //
                                            // create a navigator entry with a parent set to this
                                            //
                                            cs.save();
                                            string menuNameSpace = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "NameSpace", "");
                                            if (!string.IsNullOrEmpty(menuNameSpace))
                                            {
                                                string NavIconTypeString = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "type", "");
                                                if (string.IsNullOrEmpty(NavIconTypeString))
                                                {
                                                    NavIconTypeString = "Addon";
                                                }
                                                BuildController.verifyNavigatorEntry(core, new MetadataMiniCollectionModel.MiniCollectionMenuModel {
                                                        menuNameSpace = menuNameSpace,
                                                        name          = addonName,
                                                        adminOnly     = false,
                                                        developerOnly = false,
                                                        newWindow     = false,
                                                        active        = true,
                                                        addonName     = addonName,
                                                        navIconType   = NavIconTypeString,
                                                        navIconTitle  = addonName
                                                    }, CollectionID);
                                            }
                                            break;
                                        }

                                        case "argument":
                                        case "argumentlist": {
                                            //
                                            // multiple argumentlist elements are concatinated with crlf
                                            ArgumentList.Append(Addonfield.InnerText.Trim(' ') + Environment.NewLine);
                                            break;
                                        }

                                        case "style": {
                                            //
                                            // import exclusive style
                                            //
                                            string NodeName = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "name", "");
                                            string NewValue = encodeText(Addonfield.InnerText).Trim(' ');
                                            if (NewValue.left(1) != "{")
                                            {
                                                NewValue = "{" + NewValue;
                                            }
                                            if (NewValue.Substring(NewValue.Length - 1) != "}")
                                            {
                                                NewValue += "}";
                                            }
                                            StyleSheet.Append(NodeName + " " + NewValue + Environment.NewLine);
                                            break;
                                        }

                                        case "stylesheet":
                                        case "styles": {
                                            //
                                            // import exclusive stylesheet if more then whitespace
                                            //
                                            string test = Addonfield.InnerText;
                                            test = strReplace(test, " ", "");
                                            test = strReplace(test, "\r", "");
                                            test = strReplace(test, "\n", "");
                                            test = strReplace(test, "\t", "");
                                            if (!string.IsNullOrEmpty(test))
                                            {
                                                StyleSheet.Append(Addonfield.InnerText + Environment.NewLine);
                                            }
                                            break;
                                        }

                                        case "template":
                                        case "content":
                                        case "admin": {
                                            //
                                            // these add-ons will be "non-developer only" in navigation
                                            //
                                            fieldName  = Addonfield.Name;
                                            FieldValue = Addonfield.InnerText;
                                            if (!cs.isFieldSupported(fieldName))
                                            {
                                                //
                                                // Bad field name - need to report it somehow
                                                //
                                            }
                                            else
                                            {
                                                cs.set(fieldName, FieldValue);
                                                if (GenericController.encodeBoolean(Addonfield.InnerText))
                                                {
                                                    //
                                                    // if template, admin or content - let non-developers have navigator entry
                                                    //
                                                }
                                            }
                                            break;
                                        }

                                        case "icon": {
                                            //
                                            // icon
                                            //
                                            FieldValue = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "link", "");
                                            if (!string.IsNullOrEmpty(FieldValue))
                                            {
                                                //
                                                // Icons can be either in the root of the website or in content files
                                                //
                                                FieldValue = GenericController.strReplace(FieldValue, "\\", "/");         // make it a link, not a file
                                                if (GenericController.strInstr(1, FieldValue, "://") != 0)
                                                {
                                                    //
                                                    // the link is an absolute URL, leave it link this
                                                    //
                                                }
                                                else
                                                {
                                                    if (FieldValue.left(1) != "/")
                                                    {
                                                        //
                                                        // make sure it starts with a slash to be consistance
                                                        //
                                                        FieldValue = "/" + FieldValue;
                                                    }
                                                    if (FieldValue.left(17) == "/contensivefiles/")
                                                    {
                                                        //
                                                        // in content files, start link without the slash
                                                        //
                                                        FieldValue = FieldValue.Substring(17);
                                                    }
                                                }
                                                cs.set("IconFilename", FieldValue);
                                                {
                                                    cs.set("IconWidth", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "width", "0")));
                                                    cs.set("IconHeight", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "height", "0")));
                                                    cs.set("IconSprites", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "sprites", "0")));
                                                }
                                            }
                                            break;
                                        }

                                        case "includeaddon":
                                        case "includeadd-on":
                                        case "include addon":
                                        case "include add-on": {
                                            //
                                            // processed in phase2 of this routine, after all the add-ons are installed
                                            //
                                            break;
                                        }

                                        case "form": {
                                            //
                                            // The value of this node is the xml instructions to create a form. Take then
                                            //   entire node, children and all, and save them in the formxml field.
                                            //   this replaces the settings add-on type, and soo to be report add-on types as well.
                                            //   this removes the ccsettingpages and settingcollectionrules, etc.
                                            //
                                            {
                                                cs.set("formxml", Addonfield.InnerXml);
                                            }
                                            break;
                                        }

                                        case "javascript":
                                        case "javascriptinhead": {
                                            //
                                            // these all translate to JSFilename
                                            //
                                            fieldName = "jsfilename";
                                            cs.set(fieldName, Addonfield.InnerText);

                                            break;
                                        }

                                        case "iniframe": {
                                            //
                                            // typo - field is inframe
                                            //
                                            fieldName = "inframe";
                                            cs.set(fieldName, Addonfield.InnerText);
                                            break;
                                        }

                                        case "diagnostic": {
                                            bool fieldValue = encodeBoolean(Addonfield.InnerText);
                                            cs.set("diagnostic", fieldValue);
                                            collectionIncludesDiagnosticAddons = collectionIncludesDiagnosticAddons || fieldValue;
                                            break;
                                        }

                                        case "category": {
                                            if (!string.IsNullOrWhiteSpace(Addonfield.InnerText))
                                            {
                                                AddonCategoryModel category = DbBaseModel.createByUniqueName <AddonCategoryModel>(core.cpParent, Addonfield.InnerText);
                                                if (category == null)
                                                {
                                                    category      = DbBaseModel.addDefault <AddonCategoryModel>(core.cpParent);
                                                    category.name = Addonfield.InnerText;
                                                    category.save(core.cpParent);
                                                }
                                                cs.set("addonCategoryId", category.id);
                                            }
                                            break;
                                        }

                                        case "instancesettingprimarycontentid": {
                                            int lookupContentId = 0;
                                            if (!string.IsNullOrWhiteSpace(Addonfield.InnerText))
                                            {
                                                ContentModel lookupContent = DbBaseModel.createByUniqueName <ContentModel>(core.cpParent, Addonfield.InnerText);
                                                if (lookupContent != null)
                                                {
                                                    lookupContentId = lookupContent.id;
                                                }
                                            }
                                            cs.set("instancesettingprimarycontentid", lookupContentId);
                                            break;
                                        }

                                        default: {
                                            //
                                            // All the other fields should match the Db fields
                                            //
                                            fieldName  = Addonfield.Name;
                                            FieldValue = Addonfield.InnerText;
                                            if (!cs.isFieldSupported(fieldName))
                                            {
                                                //
                                                // Bad field name - need to report it somehow
                                                //
                                                LogController.logError(core, new ApplicationException("bad field found [" + fieldName + "], in addon node [" + addonName + "], of collection [" + MetadataController.getRecordName(core, "add-on collections", CollectionID) + "]"));
                                            }
                                            else
                                            {
                                                cs.set(fieldName, FieldValue);
                                            }
                                            break;
                                        }
                                        }
                                    }
                                }
                            }
                            cs.set("ArgumentList", ArgumentList.ToString());
                            cs.set("StylesFilename", StyleSheet.ToString());
                        }
                        cs.close();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
Пример #21
0
 public DefLoader(DefDatabase database)
 {
     this.database = database ?? throw new ArgumentNullException(nameof(database));
     controller    = new XmlController();
     controller.AddCustomResolver(typeof(Def), DefResolver);
 }
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode templateNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = toLCase(templateNode.Name);
                if (Basename == "template")
                {
                    bool   IsFound      = false;
                    string templateName = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "name", "No Name");
                    if (string.IsNullOrEmpty(templateName))
                    {
                        templateName = "No Name";
                    }
                    string recordGuid = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "guid", templateName);
                    if (string.IsNullOrEmpty(recordGuid))
                    {
                        recordGuid = templateName;
                    }
                    var template = DbBaseModel.create <PageTemplateModel>(core.cpParent, recordGuid);
                    if (template == null)
                    {
                        template = DbBaseModel.createByUniqueName <PageTemplateModel>(core.cpParent, templateName);
                    }
                    if (template == null)
                    {
                        template = DbBaseModel.addDefault <PageTemplateModel>(core.cpParent);
                    }
                    foreach (XmlNode childNode in templateNode.ChildNodes)
                    {
                        switch (childNode.Name.ToLowerInvariant())
                        {
                        case "includeaddon": {
                            string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, childNode, "guid", "");
                            string addonName = XmlController.getXMLAttribute(core, ref IsFound, childNode, "name", "No Name");
                            if (!string.IsNullOrEmpty(addonGuid))
                            {
                                var addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuid);
                                if (addon == null)
                                {
                                    return_ErrorMessage += "Addon dependency [" + addonName + "] for template [" + templateName + "] could not be found by its guid [" + addonGuid + "]";
                                }
                                var ruleList = DbBaseModel.createList <AddonTemplateRuleModel>(core.cpParent, "(addonId=" + addon.id + ")and(addonId=" + template.id + ")");
                                if (ruleList.Count.Equals(0))
                                {
                                    var rule = DbBaseModel.addDefault <AddonTemplateRuleModel>(core.cpParent);
                                    rule.addonId    = addon.id;
                                    rule.templateId = template.id;
                                    rule.save(core.cpParent);
                                }
                            }
                            break;
                        }

                        case "bodyhtml": {
                            template.bodyHTML = childNode.InnerText;
                            break;
                        }
                        }
                    }
                    template.ccguid = recordGuid;
                    template.name   = templateName;
                    //record.bodyHTML = templateNode.InnerText;
                    template.collectionId = collectionId;
                    template.isSecure     = XmlController.getXMLAttributeBoolean(core, ref IsFound, templateNode, "issecure", false);
                    template.save(core.cpParent);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
Пример #23
0
 public PodcastController()
 {
     podcast       = new Podcast();
     xmlController = new XmlController();
 }
Пример #24
0
        public static void Combine(IDictionary main, IDictionary secondary, ListMergeMode mode)
        {
            if (main == null || secondary == null || secondary.Count == 0)
            {
                return;
            }

            if ((main.IsFixedSize || main.IsReadOnly) && mode != ListMergeMode.Replace)
            {
                XmlController.Log("[ERROR] Main dictionary is fixed size or read only.");
                return;
            }

            switch (mode)
            {
            case ListMergeMode.Replace:

                // Clear list and add all values from other list.
                main.Clear();
                foreach (var key in secondary.Keys)
                {
                    main.Add(key, secondary[key]);
                }

                break;

            case ListMergeMode.Append:

                // Simply add all values from secondary to primary.
                foreach (var key in secondary.Keys)
                {
                    if (!main.Contains(key))
                    {
                        main.Add(key, secondary[key]);
                    }
                }

                break;

            case ListMergeMode.MergeReplace:     // Merge replace and normal merge have the same behaviour on dictionaries.
            case ListMergeMode.Merge:

                // Add all values from other list, if they are not already in the list.
                foreach (var key in secondary.Keys)
                {
                    if (!main.Contains(key))
                    {
                        main.Add(key, secondary[key]);
                    }
                    else
                    {
                        main[key] = secondary[key];
                    }
                }

                break;

            case ListMergeMode.Subtract:

                // Remove pairs from main if key is in secondary
                foreach (var key in secondary.Keys)
                {
                    if (main.Contains(key))
                    {
                        main.Remove(key);
                    }
                }
                break;

            default:
                XmlController.Log($"[ERROR] {mode} is not implemented.");
                break;
            }
        }
        static void Main(string[] args)
        {
            /* --- Instatiate the Services --- */
            Services          OfficeService     = new Services();
            UserService       userService       = new UserService();
            EventService      eventService      = new EventService();
            AttendanceService attendanceService = new AttendanceService();
            XmlController     xmlController     = new XmlController();


            /* --- Instatiate timer and trigger sendHeartbeat every second --- */
            HeartBeat heartBeat = new HeartBeat();

            Timer timer = new Timer();

            timer.Elapsed += new ElapsedEventHandler(heartBeat.sendHeartBeat);
            timer.Interval = 1000;
            timer.Start();

            /* --- Instatiate List of CalendarEvents --- */
            List <CalendarEvent> events = new List <CalendarEvent>();

            /* --- Instatiate connection with RabbitMQ --- */
            Uri    rabbitMQUri         = new Uri(Constant.RabbitMQConnectionUrl);
            string queueEventName      = Constant.RabbitMQEventQueueName;
            string queueUserName       = Constant.RabbitMQUserQueueName;
            string queueAttendanceName = Constant.RabbitMQAttendanceQueueName;

            var factory = new ConnectionFactory
            {
                Uri = rabbitMQUri
            };

            using var connection = factory.CreateConnection();
            using var channel    = connection.CreateModel();

            /* --- Instatiate consumer for event, user & attendance queue --- */
            var eventConsumer      = new EventingBasicConsumer(channel);
            var userConsumer       = new EventingBasicConsumer(channel);
            var attendanceConsumer = new EventingBasicConsumer(channel);


            /* --- Execute valid User changes (create, dupdate, delete) from other systems (Canvas, Frontend) )--- */
            // User
            userConsumer.Received += (sender, e) =>
            {
                var message = e.Body.ToArray();
                var xml     = Encoding.UTF8.GetString(message);
                Console.WriteLine(xml);
                if (xmlController.XSDValidatie(xml, "user"))
                {
                    RabbitMQUser result = xmlController.ConvertXMLtoObject <RabbitMQUser>(xml);
                    Console.WriteLine(result.Header.Method);
                    Console.WriteLine(result.Header.Source);
                    Console.WriteLine(result.UUID);
                    Console.WriteLine(result.EntityVersion);
                    Console.WriteLine(result.LastName);
                    Console.WriteLine(result.FirstName);
                    Console.WriteLine(result.EmailAddress);
                    Console.WriteLine(result.Role);
                    if (result.Header.Source != XMLSource.PLANNING)
                    {
                        switch (result.Header.Method)
                        {
                        case XMLMethod.CREATE:
                            userService.UserCreate(result);
                            break;

                        case XMLMethod.UPDATE:
                            userService.UserUpdate(result);
                            break;

                        case XMLMethod.DELETE:
                            userService.UserDelete(result);
                            break;
                        }
                    }
                }
            };

            /* --- Execute valid Event changes (create, dupdate, delete) from other systems (Canvas, Frontend) --- */
            //Event
            eventConsumer.Received += (sender, e) =>
            {
                var message = e.Body.ToArray();
                var xml     = Encoding.UTF8.GetString(message);
                Console.WriteLine(xml);
                if (xmlController.XSDValidatie(xml, "event"))
                {
                    RabbitMQEvent result = xmlController.ConvertXMLtoObject <RabbitMQEvent>(xml);
                    Console.WriteLine(result.Header.Method);
                    Console.WriteLine(result.Header.Source);
                    Console.WriteLine(result.UUID);
                    Console.WriteLine(result.EntityVersion);
                    Console.WriteLine(result.Title);
                    Console.WriteLine(result.OrganiserId);
                    Console.WriteLine(result.Description);
                    Console.WriteLine(result.Start);
                    Console.WriteLine(result.End);
                    if (result.Header.Source != XMLSource.PLANNING)
                    {
                        switch (result.Header.Method)
                        {
                        case XMLMethod.CREATE:
                            eventService.EventCreate(result);
                            break;

                        case XMLMethod.UPDATE:
                            eventService.EventUpdate(result);
                            break;

                        case XMLMethod.DELETE:
                            eventService.EventDelete(result);
                            break;
                        }
                    }
                }
            };

            /* --- Execute valid Attendance changes (create, delete) from other systems (Canvas, Frontend) --- */
            //Attendance
            attendanceConsumer.Received += (sender, e) =>
            {
                var message = e.Body.ToArray();
                var xml     = Encoding.UTF8.GetString(message);
                Console.WriteLine(xml);
                if (xmlController.XSDValidatie(xml, "attendance"))
                {
                    RabbitMQAttendance result = xmlController.ConvertXMLtoObject <RabbitMQAttendance>(xml);
                    Console.WriteLine(result.Header.Method);
                    Console.WriteLine(result.UUID);
                    Console.WriteLine(result.CreatorId);
                    Console.WriteLine(result.AttendeeId);
                    Console.WriteLine(result.EventId);
                    switch (result.Header.Method)
                    {
                    case XMLMethod.CREATE:
                        attendanceService.AttendanceCreate(result);
                        break;

                    case XMLMethod.DELETE:
                        attendanceService.AttendanceDelete(result);
                        break;
                    }
                }
            };


            /* --- Consume the event, user & attendance queues --- */
            channel.BasicConsume(queueUserName, true, userConsumer);
            channel.BasicConsume(queueEventName, true, eventConsumer);
            channel.BasicConsume(queueAttendanceName, true, attendanceConsumer);
            Console.ReadLine();
        }
Пример #26
0
        //
        // ====================================================================================================
        /// <summary>
        /// create the colleciton zip file and return the pathFilename in the Cdn
        /// </summary>
        /// <param name="cp"></param>
        /// <param name="collectionId"></param>
        /// <returns></returns>
        public static string createCollectionZip_returnCdnPathFilename(CPBaseClass cp, AddonCollectionModel collection)
        {
            string cdnExportZip_Filename = "";

            try {
                if ((collection == null))
                {
                    //
                    // -- exit with error
                    cp.UserError.Add("The collection you selected could not be found");
                    return(string.Empty);
                }
                using (CPCSBaseClass CS = cp.CSNew()) {
                    CS.OpenRecord("Add-on Collections", collection.id);
                    if (!CS.OK())
                    {
                        //
                        // -- exit with error
                        cp.UserError.Add("The collection you selected could not be found");
                        return(string.Empty);
                    }
                    string collectionXml  = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
                    string CollectionGuid = CS.GetText("ccGuid");
                    if (CollectionGuid == "")
                    {
                        CollectionGuid = cp.Utils.CreateGuid();
                        CS.SetField("ccGuid", CollectionGuid);
                    }
                    string onInstallAddonGuid = "";
                    if ((CS.FieldOK("onInstallAddonId")))
                    {
                        int onInstallAddonId = CS.GetInteger("onInstallAddonId");
                        if ((onInstallAddonId > 0))
                        {
                            AddonModel addon = AddonModel.create <AddonModel>(cp, onInstallAddonId);
                            if ((addon != null))
                            {
                                onInstallAddonGuid = addon.ccguid;
                            }
                        }
                    }
                    string CollectionName = CS.GetText("name");
                    collectionXml        += System.Environment.NewLine + "<Collection";
                    collectionXml        += " name=\"" + CollectionName + "\"";
                    collectionXml        += " guid=\"" + CollectionGuid + "\"";
                    collectionXml        += " system=\"" + GenericController.getYesNo(CS.GetBoolean("system")) + "\"";
                    collectionXml        += " updatable=\"" + GenericController.getYesNo(CS.GetBoolean("updatable")) + "\"";
                    collectionXml        += " blockNavigatorNode=\"" + GenericController.getYesNo(CS.GetBoolean("blockNavigatorNode")) + "\"";
                    collectionXml        += " onInstallAddonGuid=\"" + onInstallAddonGuid + "\"";
                    collectionXml        += ">";
                    cdnExportZip_Filename = encodeFilename(cp, CollectionName + ".zip");
                    List <string> tempPathFileList = new List <string>();
                    string        tempExportPath   = "CollectionExport" + Guid.NewGuid().ToString() + @"\";
                    //
                    // --resource executable files
                    string        wwwFileList          = CS.GetText("wwwFileList");
                    string        ContentFileList      = CS.GetText("ContentFileList");
                    List <string> execFileList         = ExportResourceListController.getResourceFileList(cp, CS.GetText("execFileList"), CollectionGuid);
                    string        execResourceNodeList = ExportResourceListController.getResourceNodeList(cp, execFileList, CollectionGuid, tempPathFileList, tempExportPath);
                    //
                    // helpLink
                    //
                    if (CS.FieldOK("HelpLink"))
                    {
                        collectionXml += System.Environment.NewLine + "\t" + "<HelpLink>" + System.Net.WebUtility.HtmlEncode(CS.GetText("HelpLink")) + "</HelpLink>";
                    }
                    //
                    // Help
                    //
                    collectionXml += System.Environment.NewLine + "\t" + "<Help>" + System.Net.WebUtility.HtmlEncode(CS.GetText("Help")) + "</Help>";
                    //
                    // Addons
                    //
                    string IncludeSharedStyleGuidList = "";
                    string IncludeModuleGuidList      = "";
                    foreach (var addon in DbBaseModel.createList <AddonModel>(cp, "collectionid=" + collection.id))
                    {
                        //
                        // -- style sheet is in the wwwroot
                        if (!string.IsNullOrEmpty(addon.stylesLinkHref))
                        {
                            string filename = addon.stylesLinkHref.Replace("/", "\\");
                            if (filename.Substring(0, 1).Equals(@"\"))
                            {
                                filename = filename.Substring(1);
                            }
                            if (!cp.WwwFiles.FileExists(filename))
                            {
                                cp.WwwFiles.Save(filename, @"/* css file created as exported for addon [" + addon.name + "], collection [" + collection.name + "] in site [" + cp.Site.Name + "] */");
                            }
                            wwwFileList += System.Environment.NewLine + addon.stylesLinkHref;
                        }
                        //
                        // -- js is in the wwwroot
                        if (!string.IsNullOrEmpty(addon.jsHeadScriptSrc))
                        {
                            string filename = addon.jsHeadScriptSrc.Replace("/", "\\");
                            if (filename.Substring(0, 1).Equals(@"\"))
                            {
                                filename = filename.Substring(1);
                            }
                            if (!cp.WwwFiles.FileExists(filename))
                            {
                                cp.WwwFiles.Save(filename, @"// javascript file created as exported for addon [" + addon.name + "], collection [" + collection.name + "] in site [" + cp.Site.Name + "]");
                            }
                            wwwFileList += System.Environment.NewLine + addon.jsHeadScriptSrc;
                        }
                        collectionXml += ExportAddonController.getAddonNode(cp, addon.id, ref IncludeModuleGuidList, ref IncludeSharedStyleGuidList);
                    }
                    //
                    // Layouts
                    foreach (var layout in DbBaseModel.createList <LayoutModel>(cp, "(installedByCollectionId=" + collection.id + ")"))
                    {
                        collectionXml += ExportLayoutController.get(cp, layout);
                    }
                    //
                    // Templates
                    foreach (var template in DbBaseModel.createList <PageTemplateModel>(cp, "(collectionId=" + collection.id + ")"))
                    {
                        collectionXml += ExportTemplateController.get(cp, template);
                    }
                    //
                    // Data Records
                    string DataRecordList = CS.GetText("DataRecordList");
                    collectionXml += ExportDataRecordController.getNodeList(cp, DataRecordList, tempPathFileList, tempExportPath);
                    //
                    // CDef
                    foreach (Contensive.Models.Db.ContentModel content in createListFromCollection(cp, collection.id))
                    {
                        if ((string.IsNullOrEmpty(content.ccguid)))
                        {
                            content.ccguid = cp.Utils.CreateGuid();
                            content.save(cp);
                        }
                        XmlController xmlTool = new XmlController(cp);
                        string        Node    = xmlTool.GetXMLContentDefinition3(content.name);
                        //
                        // remove the <collection> top node
                        //
                        int Pos = Strings.InStr(1, Node, "<cdef", CompareMethod.Text);
                        if (Pos > 0)
                        {
                            Node = Strings.Mid(Node, Pos);
                            Pos  = Strings.InStr(1, Node, "</cdef>", CompareMethod.Text);
                            if (Pos > 0)
                            {
                                Node           = Strings.Mid(Node, 1, Pos + 6);
                                collectionXml += System.Environment.NewLine + "\t" + Node;
                            }
                        }
                    }
                    //
                    // Scripting Modules
                    if (IncludeModuleGuidList != "")
                    {
                        string[] Modules = Strings.Split(IncludeModuleGuidList, System.Environment.NewLine);
                        for (var Ptr = 0; Ptr <= Information.UBound(Modules); Ptr++)
                        {
                            string ModuleGuid = Modules[Ptr];
                            if (ModuleGuid != "")
                            {
                                using (CPCSBaseClass CS2 = cp.CSNew()) {
                                    CS2.Open("Scripting Modules", "ccguid=" + cp.Db.EncodeSQLText(ModuleGuid));
                                    if (CS2.OK())
                                    {
                                        string Code = CS2.GetText("code").Trim();
                                        Code           = EncodeCData(Code);
                                        collectionXml += System.Environment.NewLine + "\t" + "<ScriptingModule Name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\" guid=\"" + ModuleGuid + "\">" + Code + "</ScriptingModule>";
                                    }
                                    CS2.Close();
                                }
                            }
                        }
                    }
                    //
                    // shared styles
                    string[] recordGuids;
                    string   recordGuid;
                    if ((IncludeSharedStyleGuidList != ""))
                    {
                        recordGuids = Strings.Split(IncludeSharedStyleGuidList, System.Environment.NewLine);
                        for (var Ptr = 0; Ptr <= Information.UBound(recordGuids); Ptr++)
                        {
                            recordGuid = recordGuids[Ptr];
                            if (recordGuid != "")
                            {
                                using (CPCSBaseClass CS2 = cp.CSNew()) {
                                    CS2.Open("Shared Styles", "ccguid=" + cp.Db.EncodeSQLText(recordGuid));
                                    if (CS2.OK())
                                    {
                                        collectionXml += System.Environment.NewLine + "\t" + "<SharedStyle"
                                                         + " Name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\""
                                                         + " guid=\"" + recordGuid + "\""
                                                         + " alwaysInclude=\"" + CS2.GetBoolean("alwaysInclude") + "\""
                                                         + " prefix=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("prefix")) + "\""
                                                         + " suffix=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("suffix")) + "\""
                                                         + " sortOrder=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("sortOrder")) + "\""
                                                         + ">"
                                                         + EncodeCData(CS2.GetText("styleFilename").Trim())
                                                         + "</SharedStyle>";
                                    }
                                    CS2.Close();
                                }
                            }
                        }
                    }
                    //
                    // Import Collections
                    {
                        string Node = "";
                        using (CPCSBaseClass CS3 = cp.CSNew()) {
                            if (CS3.Open("Add-on Collection Parent Rules", "parentid=" + collection.id))
                            {
                                do
                                {
                                    using (CPCSBaseClass CS2 = cp.CSNew()) {
                                        if (CS2.OpenRecord("Add-on Collections", CS3.GetInteger("childid")))
                                        {
                                            string Guid = CS2.GetText("ccGuid");
                                            if (Guid == "")
                                            {
                                                Guid = cp.Utils.CreateGuid();
                                                CS2.SetField("ccGuid", Guid);
                                            }

                                            Node = Node + System.Environment.NewLine + "\t" + "<ImportCollection name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\">" + Guid + "</ImportCollection>";
                                        }

                                        CS2.Close();
                                    }

                                    CS3.GoNext();
                                }while (CS3.OK());
                            }
                            CS3.Close();
                        }
                        collectionXml += Node;
                    }
                    //
                    // wwwFileList
                    if (wwwFileList != "")
                    {
                        string[] Files = Strings.Split(wwwFileList, System.Environment.NewLine);
                        for (int Ptr = 0; Ptr <= Information.UBound(Files); Ptr++)
                        {
                            string pathFilename = Files[Ptr];
                            if (pathFilename != "")
                            {
                                pathFilename = Strings.Replace(pathFilename, @"\", "/");
                                string path     = "";
                                string filename = pathFilename;
                                int    Pos      = Strings.InStrRev(pathFilename, "/");
                                if (Pos > 0)
                                {
                                    filename = Strings.Mid(pathFilename, Pos + 1);
                                    path     = Strings.Mid(pathFilename, 1, Pos - 1);
                                }
                                string fileExtension = System.IO.Path.GetExtension(filename);
                                pathFilename = Strings.Replace(pathFilename, "/", @"\");
                                if (tempPathFileList.Contains(tempExportPath + filename))
                                {
                                    //
                                    // -- the path already has a file with this name
                                    cp.UserError.Add("There was an error exporting this collection because there were multiple files with the same filename [" + filename + "]");
                                }
                                else if (fileExtension.ToUpperInvariant().Equals(".ZIP"))
                                {
                                    //
                                    // -- zip files come from the collection folder
                                    CoreController core           = ((CPClass)cp).core;
                                    string         addonPath      = AddonController.getPrivateFilesAddonPath();
                                    string         collectionPath = CollectionFolderController.getCollectionConfigFolderPath(core, collection.ccguid);
                                    if (!cp.PrivateFiles.FileExists(addonPath + collectionPath + filename))
                                    {
                                        //
                                        // - not there
                                        cp.UserError.Add("There was an error exporting this collection because the zip file [" + pathFilename + "] was not found in the collection path [" + collectionPath + "].");
                                    }
                                    else
                                    {
                                        //
                                        // -- copy file from here
                                        cp.PrivateFiles.Copy(addonPath + collectionPath + filename, tempExportPath + filename, cp.TempFiles);
                                        tempPathFileList.Add(tempExportPath + filename);
                                        collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(filename) + "\" type=\"www\" path=\"" + System.Net.WebUtility.HtmlEncode(path) + "\" />";
                                    }
                                }
                                else if ((!cp.WwwFiles.FileExists(pathFilename)))
                                {
                                    cp.UserError.Add("There was an error exporting this collection because the www file [" + pathFilename + "] was not found.");
                                }
                                else
                                {
                                    cp.WwwFiles.Copy(pathFilename, tempExportPath + filename, cp.TempFiles);
                                    tempPathFileList.Add(tempExportPath + filename);
                                    collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(filename) + "\" type=\"www\" path=\"" + System.Net.WebUtility.HtmlEncode(path) + "\" />";
                                }
                            }
                        }
                    }
                    //
                    // ContentFileList
                    //
                    if (true)
                    {
                        if (ContentFileList != "")
                        {
                            string[] Files = Strings.Split(ContentFileList, System.Environment.NewLine);
                            for (var Ptr = 0; Ptr <= Information.UBound(Files); Ptr++)
                            {
                                string PathFilename = Files[Ptr];
                                if (PathFilename != "")
                                {
                                    PathFilename = Strings.Replace(PathFilename, @"\", "/");
                                    string Path     = "";
                                    string Filename = PathFilename;
                                    int    Pos      = Strings.InStrRev(PathFilename, "/");
                                    if (Pos > 0)
                                    {
                                        Filename = Strings.Mid(PathFilename, Pos + 1);
                                        Path     = Strings.Mid(PathFilename, 1, Pos - 1);
                                    }
                                    if (tempPathFileList.Contains(tempExportPath + Filename))
                                    {
                                        cp.UserError.Add("There was an error exporting this collection because there were multiple files with the same filename [" + Filename + "]");
                                    }
                                    else if ((!cp.CdnFiles.FileExists(PathFilename)))
                                    {
                                        cp.UserError.Add("There was an error exporting this collection because the cdn file [" + PathFilename + "] was not found.");
                                    }
                                    else
                                    {
                                        cp.CdnFiles.Copy(PathFilename, tempExportPath + Filename, cp.TempFiles);
                                        tempPathFileList.Add(tempExportPath + Filename);
                                        collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(Filename) + "\" type=\"content\" path=\"" + System.Net.WebUtility.HtmlEncode(Path) + "\" />";
                                    }
                                }
                            }
                        }
                    }
                    //
                    // ExecFileListNode
                    //
                    collectionXml += execResourceNodeList;
                    //
                    // Other XML
                    //
                    string OtherXML;
                    OtherXML = CS.GetText("otherxml");
                    if (Strings.Trim(OtherXML) != "")
                    {
                        collectionXml += System.Environment.NewLine + OtherXML;
                    }
                    collectionXml += System.Environment.NewLine + "</Collection>";
                    CS.Close();
                    string tempExportXml_Filename = encodeFilename(cp, CollectionName + ".xml");
                    //
                    // Save the installation file and add it to the archive
                    //
                    cp.TempFiles.Save(tempExportPath + tempExportXml_Filename, collectionXml);
                    if (!tempPathFileList.Contains(tempExportPath + tempExportXml_Filename))
                    {
                        tempPathFileList.Add(tempExportPath + tempExportXml_Filename);
                    }
                    string tempExportZip_Filename = encodeFilename(cp, CollectionName + ".zip");
                    //
                    // -- zip up the folder to make the collection zip file in temp filesystem
                    zipTempCdnFile(cp, tempExportPath + tempExportZip_Filename, tempPathFileList);
                    //
                    // -- copy the collection zip file to the cdn filesystem as the download link
                    cp.TempFiles.Copy(tempExportPath + tempExportZip_Filename, cdnExportZip_Filename, cp.CdnFiles);
                    //
                    // -- delete the temp folder
                    cp.TempFiles.DeleteFolder(tempExportPath);
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(cdnExportZip_Filename);
        }
Пример #27
0
 private static void ReportAttributeError(XmlNode node, string attrName, string value, string expectedType)
 {
     XmlController.Log($"Attribute error: Node {node.Name} has attribute {attrName}=\"{value}\", but it should be {expectedType}.");
 }
Пример #28
0
        private bool GenerateCivilizationXml()
        {
            if (!ValidateForm(Categories.Civilization))
            {
                return(false);
            }

            var civType = string.Format(Properties.Resources.txt_civ, Settings.Default.civ_name);

            var gameData = new GameData
            {
                Civilizations = new Civilizations
                {
                    Row = new Civilization
                    {
                        PortraitIndex      = 0,
                        Type               = civType,
                        DerivativeCiv      = string.Format(Properties.Resources.txt_civ, CbSoundtrack.SelectedValue.ToString().ToUpper()),
                        Description        = string.Format(Properties.Resources.key_civ_desc, TbType.Text),
                        Civilopedia        = "TXT_KEY_CIV_MANNCO_PEDIA_HEADER1", // TO-DO
                        CivilopediaTag     = string.Format(Properties.Resources.key_civ_pedia_text, TbType.Text),
                        ShortDescription   = string.Format(Properties.Resources.key_civ_desc_short, TbType.Text),
                        Adjective          = string.Format(Properties.Resources.key_civ_adjective, TbType.Text),
                        DefaultPlayerColor = string.Format(Properties.Resources.txt_civ_color, TbType.Text),
                        ArtDefineTag       = string.Format(Properties.Resources.txt_civ_art_def,
                                                           CbSoundtrack.SelectedValue.ToString().ToUpper()),
                        ArtStyleType = string.Format(Properties.Resources.txt_civ_art_style,
                                                     CbArtStyle.SelectedValue.ToString().ToUpper()),
                        ArtStyleSuffix = GetArtSuffix((ArtStyles)Enum.Parse(typeof(ArtStyles),
                                                                            CbArtStyle.SelectedValue.ToString())),
                        ArtStylePrefix = CbArtStyle.SelectedValue.ToString().ToUpper(),
                        IconAtlas      = string.Format(Properties.Resources.txt_civ_atlas_icon, TbType.Text),
                        AlphaIconAtlas = string.Format(Properties.Resources.txt_civ_atlas_alpha, TbType.Text),
                        SoundtrackTag  = CbSoundtrack.SelectedValue.ToString(),
                        MapImage       = string.Format(Properties.Resources.txt_civ_map, TbType.Text),
                        DawnOfManQuote = string.Format(Properties.Resources.key_civ_dom_text, TbType.Text),
                        DawnOfManImage = string.Format(Properties.Resources.txt_civ_dom_image, TbLeaderType.Text)
                    }
                },
                CityNames = new CityNames
                {
                    Row = new List <CityName>()
                },
                SpyNames = new SpyNames
                {
                    Row = new List <SpyName>()
                },
                Leaders = new Models.Civilization.Leaders
                {
                    Row = new Leader
                    {
                        LeaderheadType   = string.Format(Properties.Resources.txt_leader, TbLeaderType.Text),
                        CivilizationType = civType
                    }
                },
                FreeBuildingClasses = new FreeBuildingClasses
                {
                    Row = new FreeBuildingClass
                    {
                        BuildingClassType = string.Format(Properties.Resources.txt_building_class, CbFreeBuilding.SelectedValue.ToString().ToUpper()),
                        CivilizationType  = civType
                    }
                },
                FreeTechs = new FreeTechs
                {
                    Row = new FreeTech
                    {
                        TechType         = string.Format(Properties.Resources.txt_tech, CbFreeTech.SelectedValue.ToString().ToUpper()),
                        CivilizationType = civType
                    }
                },
                FreeUnits = new FreeUnits(),
                Religions = new Models.Civilization.Religions
                {
                    Row = new Religion
                    {
                        ReligionType = string.Format(Properties.Resources.txt_religion,
                                                     CbReligion.SelectedValue.ToString().ToUpper()),
                        CivilizationType = civType
                    }
                }
            };

            foreach (var x in LbCityNames.Items)
            {
                var city = new CityName
                {
                    Name = string.Format(Properties.Resources.key_city_name, Settings.Default.civ_name,
                                         x.ToString().Replace(' ', '_').ToUpper()),
                    CivilizationType = civType
                };

                gameData.CityNames.Row.Add(city);
            }

            foreach (var x in LbSpyNames.Items)
            {
                var spy = new SpyName
                {
                    Name = string.Format(Properties.Resources.key_spy_name, Settings.Default.civ_name,
                                         x.ToString().Replace(' ', '_').ToUpper()),
                    CivilizationType = civType
                };

                gameData.SpyNames.Row.Add(spy);
            }

            Enum.TryParse(CbFreeUnit.SelectedValue.ToString(), out Units unit);
            gameData.FreeUnits.Row = new FreeUnit
            {
                UnitClassType = string.Format(Properties.Resources.txt_unit_class,
                                              CbFreeUnit.SelectedValue.ToString().ToUpper()),
                UnitAiType = string.Format(Properties.Resources.txt_unit_ai,
                                           Dictionaries.UnitDictionary[unit].Item2.ToString().ToUpper()),
                Count            = 1,
                CivilizationType = civType
            };

            return(XmlController.GenerateCivilizationXml(gameData));
        }