public void SetConfigurationData(string SqlIP, string SqlPort, string SqlUsername, string SqlPassword, int KioskId, string KioskRegion, string AdminPassword, string xmlFileName)
            {
                bool isError = false;
                try
                {
                    Decrypt(xmlFileName);
                }
                catch (Exception)
                {
                    isError = true;
                }

                try
                {

                    var doc = new XDocument(
                        new XElement("Settings",
                            new XElement("SqlIP", SqlIP),
                            new XElement("SqlUsername", SqlUsername),
                            new XElement("SqlPassword", SqlPassword),
                            new XElement("SqlPort", SqlPort),
                            new XElement("AdminPassword", AdminPassword),
                            new XElement("KioskId", KioskId),
                            new XElement("KioskRegion", KioskRegion)));

                    File.WriteAllText(xmlFileName, doc.ToString());
                }
                catch (Exception) { }

                finally
                {
                    if (!isError) Encrypt(xmlFileName);
                }
            }
Esempio n. 2
0
        public static XDocument GetDocumentWithContacts()
        {
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XProcessingInstruction("AppName", "Processing Instruction Data"),
                new XComment("Personal Contacts"),
                new XElement("contacts",
                    new XAttribute("category", "friends"),
                    new XAttribute("gender", "male"),
                     new XElement("contact",
                        new XAttribute("netWorth", "100"),
                        new XElement("name", "John Hopkins"),
                        new XElement("phone",
                            new XAttribute("type", "home"),
                            "214-459-8907"),
                        new XElement("phone",
                            new XAttribute("type", "work"),
                            "817-283-9670")),
                    new XElement("contact",
                        new XAttribute("netWorth", "10"),
                        new XElement("name", "Patrick Hines"),
                        new XElement("phone",
                            new XAttribute("type", "home"),
                            "206-555-0144"),
                        new XElement("phone",
                            new XAttribute("type", "work"),
                            "425-555-0145"))));

            return doc;
        }
		//TODO: respect namespaces
		public void Populate (XDocument doc)
		{
			foreach (XNode node in doc.AllDescendentNodes) {
				XElement el = node as XElement;
				if (el == null)
					continue;
				string parentName = "";
				XElement parentEl = el.Parent as XElement;
				if (parentEl != null)
					parentName = parentEl.Name.Name;
				
				HashSet<string> map;
				if (!elementCompletions.TryGetValue (parentName, out map)) {
					map = new HashSet<string> ();
					elementCompletions.Add (parentName, map);
				}
				map.Add (el.Name.Name);
				
				if (!attributeCompletions.TryGetValue (el.Name.Name, out map)) {
					map = new HashSet<string> ();
					attributeCompletions.Add (el.Name.Name, map);
				}
				foreach (XAttribute att in el.Attributes)
					map.Add (att.Name.Name);
			}
		}
Esempio n. 4
0
		// Constructor used for testing the XDOM
		public AspNetParsedDocument (string fileName, WebSubtype type, PageInfo info, XDocument xDoc) : 
			base (fileName)
		{
			Flags |= ParsedDocumentFlags.NonSerializable;
			Info = info;
			Type = type;
			XDocument = xDoc;
		}
		IEnumerable<Error> Validate (XDocument doc)
		{
			foreach (XNode node in doc.Nodes) {
				if (node is XElement && !Object.ReferenceEquals (node, doc.RootElement)) {
					yield return new Error (ErrorType.Warning, "More than one root element", node.Region);
				}
			}
		}
Esempio n. 6
0
		public MemberListBuilder (DocumentReferenceManager refMan, XDocument xDoc)
		{
			docRefMan = refMan;
			xDocument = xDoc;
			
			Errors = new List<Error> ();
			Members = new Dictionary<string,CodeBehindMember> ();
		}
Esempio n. 7
0
        public void Comment(string value1, string value2, bool checkHashCode)
        {
            XComment c1 = new XComment(value1);
            XComment c2 = new XComment(value2);
            VerifyComparison(checkHashCode, c1, c2);

            XDocument doc = new XDocument(c1);
            XElement e2 = new XElement("p2p", c2);

            VerifyComparison(checkHashCode, c1, c2);
        }
Esempio n. 8
0
        public void ProcessingInstruction(string target1, string data1, string target2, string data2, bool checkHashCode)
        {
            var p1 = new XProcessingInstruction(target1, data1);
            var p2 = new XProcessingInstruction(target2, data2);

            VerifyComparison(checkHashCode, p1, p2);

            XDocument doc = new XDocument(p1);
            XElement e2 = new XElement("p2p", p2);

            VerifyComparison(checkHashCode, p1, p2);
        }
Esempio n. 9
0
		public void Populate (XDocument xDoc, List<Error> errors)
		{
			foreach (XNode node in xDoc.AllDescendentNodes) {
				if (node is AspNetDirective) {
					HandleDirective (node as AspNetDirective, errors);
				} else if (node is XDocType) {
					HandleDocType (node as XDocType);
				} else if (node is XElement) {
					// quit the parsing when reached the html nodes
					return;
				}
			}
		}
Esempio n. 10
0
 public XMLScoreParser()
 {
     try
     {
         this.xdoc = XDocument.Load(FILENAME);
         Scores = this.ParseScores();
     }
     catch (FileNotFoundException ex)
     {
         this.xdoc = new XDocument(new XElement("Scores"));
         Scores = new List<Score>();
         this.xdoc.Save(FILENAME);
     }
 }
Esempio n. 11
0
            public void StoreScores(List<Score> Scores)
            {
                this.Scores = Scores;
                this.Scores.Sort((x, y) => y.CompareTo(x));
                XElement[] Xscores = new XElement[Scores.Count];
                int i =0;
                foreach (Score sc in Scores)
                {
                    Xscores[i++] = new XElement("Score", new XElement("Name", sc.Player.Pseudo), new XElement("Value", sc.Value), new XElement("Mode", sc.Mode.GetType().FullName));
                }
                this.xdoc = new XDocument(new XElement("Scores", Xscores));

                this.xdoc.Save(FILENAME);
            }
        /// <summary>
        /// Сохранить.
        /// </summary>
        /// <exception cref="InvalidOperationException"></exception>
        public void Save()
        {
            if (!this.rootImports.Keys.Any())
            {
                throw new InvalidOperationException("Cannot save. rootImports is empty.");
            }

            foreach (var filePath in this.rootImports.Keys)
            {
                var rootElement = new XElement("settings");

                var rootImportsWithEqualPath = this.rootImports.Where(v => v.Value.FilePath.Equals(filePath) &&
                                                                      !v.Key.Equals(filePath, StringComparison.OrdinalIgnoreCase));
                foreach (var kvp in rootImportsWithEqualPath)
                {
                    this.SaveComments(kvp.Value.Comments, rootElement);
                    rootElement.Add(new XElement("import", new XAttribute("from", kvp.Key)));
                }

                var metaVariablesWithEqualPath = this.metaVariables.Where(v => v.Value.FilePath.Equals(filePath));
                foreach (var kvp in metaVariablesWithEqualPath)
                {
                    this.SaveComments(kvp.Value.Comments, rootElement);
                    rootElement.Add(new XElement("meta", new XAttribute("name", kvp.Key), new XAttribute("value", kvp.Value.Value)));
                }
                var variablesWithEqualPath = this.variables.Where(v => v.Value.FilePath.Equals(filePath) && !this.HasBlock(v.Key));
                foreach (var kvp in variablesWithEqualPath)
                {
                    this.SaveComments(kvp.Value.Comments, rootElement);
                    rootElement.Add(
                        new XElement("var", new XAttribute("name", kvp.Key), new XAttribute("value", kvp.Value.Value)));
                }

                var blocksWithEqualPath = this.blocks.Where(v => v.Value.FilePath.Equals(filePath));
                foreach (var kvp in blocksWithEqualPath)
                {
                    var blockContentWithRoot = string.IsNullOrEmpty(kvp.Value.Content)
            ? kvp.Value.IsEnabled != null ? $@"<block name=""{kvp.Key}"" enabled=""{kvp.Value.IsEnabled}""></block>"
              : $@"<block name=""{kvp.Key}""></block>"
            : kvp.Value.Content;
                    var blockContent = XDocument.Parse(blockContentWithRoot);

                    this.SaveComments(kvp.Value.Comments, rootElement);
                    rootElement.Add(blockContent.Root);
                }

                var commentsWithEqualPath = this.comments.Where(v => v.FilePath.Equals(filePath));
                foreach (var comment in commentsWithEqualPath)
                {
                    if (!string.IsNullOrEmpty(comment.Value))
                    {
                        rootElement.Add(new XComment(comment.Value));
                    }
                }

                if (!rootElement.HasElements)
                {
                    continue;
                }

                var config = new XDocument();
                config.Add(rootElement);
                config.Save(filePath);
            }
        }
Esempio n. 13
0
 public void CastToInterface()
 {
     XDocument doc = new XDocument();
     Assert.IsAssignableFrom<IXmlLineInfo>(doc);
     Assert.IsAssignableFrom<IXmlLineInfo>(doc.CreateReader());
 }
        /// <summary>
        /// Gets the Open Search XML for the current site. You can customize the contents of this XML here. See
        /// http://www.hanselman.com/blog/CommentView.aspx?guid=50cc95b1-c043-451f-9bc2-696dc564766d#commentstart
        /// http://www.opensearch.org
        /// </summary>
        /// <returns>The Open Search XML for the current site.</returns>
        public string GetOpenSearchXml()
        {
            // Short name must be less than or equal to 16 characters.
            string shortName = "Search";
            string description = "Search the ASP.NET MVC Boilerplate Site";
            // The link to the search page with the query string set to 'searchTerms' which gets replaced with a user 
            // defined query.
            string searchUrl = this.urlHelper.AbsoluteRouteUrl(
                HomeControllerRoute.GetSearch, 
                new { query = "{searchTerms}" });
            // The link to the page with the search form on it. The home page has the search form on it.
            string searchFormUrl = this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex);
            // The link to the favicon.ico file for the site.
            string favicon16Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon.ico");
            // The link to the favicon.png file for the site.
            string favicon32Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon-32x32.png");
            // The link to the favicon.png file for the site.
            string favicon96Url = this.urlHelper.AbsoluteContent("~/content/icons/favicon-96x96.png");

            XNamespace ns = "http://a9.com/-/spec/opensearch/1.1";
            XDocument document = new XDocument(
                new XElement(
                    ns + "OpenSearchDescription",
                    new XElement(ns + "ShortName", shortName),
                    new XElement(ns + "Description", description),
                    new XElement(ns + "Url",
                        new XAttribute("type", "text/html"),
                        new XAttribute("method", "get"),
                        new XAttribute("template", searchUrl)),
                    // Search results can also be returned as RSS. Here, our start index is zero for the first result.
                    // new XElement(ns + "Url",
                    //     new XAttribute("type", "application/rss+xml"),
                    //     new XAttribute("indexOffset", "0"),
                    //     new XAttribute("rel", "results"),
                    //     new XAttribute("template", "http://example.com/?q={searchTerms}&amp;start={startIndex?}&amp;format=rss")),
                    // Search suggestions can also be returned as JSON.
                    // new XElement(ns + "Url",
                    //     new XAttribute("type", "application/json"),
                    //     new XAttribute("indexOffset", "0"),
                    //     new XAttribute("rel", "suggestions"),
                    //     new XAttribute("template", "http://example.com/suggest?q={searchTerms}")),
                    new XElement(
                        ns + "Image", 
                        favicon16Url,
                        new XAttribute("height", "16"),
                        new XAttribute("width", "16"),
                        new XAttribute("type", "image/x-icon")),
                    new XElement(
                        ns + "Image", 
                        favicon32Url,
                        new XAttribute("height", "32"),
                        new XAttribute("width", "32"),
                        new XAttribute("type", "image/png")),
                    new XElement(
                        ns + "Image", 
                        favicon96Url,
                        new XAttribute("height", "96"),
                        new XAttribute("width", "96"),
                        new XAttribute("type", "image/png")),
                    new XElement(ns + "InputEncoding", "UTF-8"),
                    new XElement(ns + "SearchForm", searchFormUrl)));

            return document.ToString(Encoding.UTF8);
        }
Esempio n. 15
0
 public XMLProvider(string filename)
 {
     XmlDocument = XDocument.Load(filename);
 }
Esempio n. 16
0
        public override async Task ExecuteAsync(IOperationExecutionContext context)
        {
            var fileOps = context.Agent.GetService<IFileOperationsExecuter>();
            var testFilePath = context.ResolvePath(this.TestFile);
            this.LogDebug("Test file: " + testFilePath);

            var exePath = context.ResolvePath(this.ExePath);
            this.LogDebug("Exe path: " + exePath);

            if (!fileOps.FileExists(testFilePath))
            {
                this.LogError($"Test file {testFilePath} does not exist.");
                return;
            }

            if (!fileOps.FileExists(exePath))
            {
                this.LogError($"NUnit runner not found at {exePath}.");
                return;
            }

            string outputPath;
            if (string.IsNullOrEmpty(this.CustomXmlOutputPath))
                outputPath = context.WorkingDirectory;
            else
                outputPath = context.ResolvePath(this.CustomXmlOutputPath);

            this.LogDebug("Output directory: " + outputPath);

            var testResultsXmlFile = fileOps.CombinePath(outputPath, "TestResult.xml");
            this.LogDebug("Output file: " + testResultsXmlFile);

            var args = this.IsNUnit3
                ? $"\"{testFilePath}\" --work:\"{outputPath}\""
                : $"\"{testFilePath}\" /xml:\"{outputPath}\"";

            if (!string.IsNullOrEmpty(this.AdditionalArguments))
            {
                this.LogDebug("Additional arguments: " + this.AdditionalArguments);
                args += " " + this.AdditionalArguments;
            }

            try
            {
                this.LogDebug("Run tests");
                await this.ExecuteCommandLineAsync(
                    context,
                    new RemoteProcessStartInfo
                    {
                        FileName = exePath,
                        Arguments = args,
                        WorkingDirectory = context.WorkingDirectory
                    }
                );


                this.LogDebug($"Read file: {testResultsXmlFile}");
                XDocument xdoc;
                using (var stream = fileOps.OpenFile(testResultsXmlFile, FileMode.Open, FileAccess.Read))
                {
                    xdoc = XDocument.Load(stream);
                    this.LogDebug("File read");
                }

                this.LogDebug($"Parse results");
                string resultsNodeName = this.IsNUnit3 ? "test-run" : "test-results";

                var testResultsElement = xdoc.Element(resultsNodeName);

                var startTime = this.TryParseStartTime(testResultsElement);
                var failures = 0;

                using (var db = new DB.Context())
                {
                    foreach (var testCaseElement in xdoc.Descendants("test-case"))
                    {
                        var testName = (string)testCaseElement.Attribute("name");

                        // skip tests that weren't actually run
                        if (TestCaseWasSkipped(testCaseElement))
                        {
                            this.LogInformation($"NUnit test: {testName} (skipped)");
                            continue;
                        }

                        var result = GetTestCaseResult(testCaseElement);
                        if (result == Domains.TestStatusCodes.Failed)
                            failures++;

                        var testDuration = this.TryParseTestTime((string)testCaseElement.Attribute("time"));

                        this.LogInformation($"NUnit test: {testName}, Result: {Domains.TestStatusCodes.GetName(result)}, Test length: {testDuration}");

                        db.BuildTestResults_RecordTestResult(
                            Execution_Id: context.ExecutionId,
                            Group_Name: AH.NullIf(this.GroupName, string.Empty) ?? "NUnit",
                            Test_Name: testName,
                            TestStatus_Code: result,
                            TestResult_Text: result == Domains.TestStatusCodes.Passed ? result : testCaseElement.ToString(),
                            TestStarted_Date: startTime,
                            TestEnded_Date: startTime + testDuration
                        );

                        startTime += testDuration;
                    }
                }

                if (failures > 0)
                    this.LogError($"{0} test failures were reported.");
            }
            finally
            {
                if (string.IsNullOrEmpty(this.CustomXmlOutputPath))
                {
                    this.LogDebug($"Deleting temp output file ({testResultsXmlFile})...");
                    try
                    {
                        fileOps.DeleteFile(testResultsXmlFile);
                    }
                    catch
                    {
                        this.LogWarning($"Could not delete {testResultsXmlFile}.");
                    }
                }
            }
        }
Esempio n. 17
0
 public void Document4(bool checkHashCode)
 {
     var doc1 = new XDocument(new object[] { (checkHashCode ? new XDocumentType("root", "", "", "") : null), new XElement("root") });
     var doc2 = new XDocument(new object[] { new XDocumentType("root", "", "", ""), new XElement("root") });
     VerifyComparison(checkHashCode, doc1, doc2);
 }
Esempio n. 18
0
        public virtual string[] GetProjectReferenceAssemblies()
        {
            var baseDir = Path.GetDirectoryName(Location);

            XDocument  projDefinition = XDocument.Load(Location);
            XNamespace rootNs         = projDefinition.Root.Name.Namespace;
            var        helper         = new ConfigHelper <H5DotJson_AssemblySettings>();
            var        tokens         = ProjectProperties.GetValues();

            var referencesPathes = projDefinition
                                   .Element(rootNs + "Project")
                                   .Elements(rootNs + "ItemGroup")
                                   .Elements(rootNs + "Reference")
                                   .Where(el => (el.Attribute("Include")?.Value != "System") && (el.Attribute("Condition") == null || el.Attribute("Condition").Value.ToLowerInvariant() != "false"))
                                   .Select(refElem => (refElem.Element(rootNs + "HintPath") == null ? (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) : refElem.Element(rootNs + "HintPath").Value))
                                   .Select(path => helper.ApplyPathTokens(tokens, Path.IsPathRooted(path) ? path : Path.GetFullPath((new Uri(Path.Combine(baseDir, path))).LocalPath)))
                                   .ToList();

            var projectReferences = projDefinition
                                    .Element(rootNs + "Project")
                                    .Elements(rootNs + "ItemGroup")
                                    .Elements(rootNs + "ProjectReference")
                                    .Where(el => el.Attribute("Condition") == null || el.Attribute("Condition").Value.ToLowerInvariant() != "false")
                                    .Select(refElem => (refElem.Element(rootNs + "HintPath") == null ? (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) : refElem.Element(rootNs + "HintPath").Value))
                                    .Select(path => helper.ApplyPathTokens(tokens, Path.IsPathRooted(path) ? path : Path.GetFullPath((new Uri(Path.Combine(baseDir, path))).LocalPath)))
                                    .ToArray();

            if (projectReferences.Length > 0)
            {
                if (ProjectProperties.BuildProjects == null)
                {
                    ProjectProperties.BuildProjects = new List <string>();
                }

                foreach (var projectRef in projectReferences)
                {
                    var isBuilt = ProjectProperties.BuildProjects.Contains(projectRef);

                    if (!isBuilt)
                    {
                        ProjectProperties.BuildProjects.Add(projectRef);
                    }

                    var processor = new TranslatorProcessor(new CompilationOptions
                    {
                        Rebuild           = Rebuild,
                        ProjectLocation   = projectRef,
                        H5Location        = H5Location,
                        ProjectProperties = new ProjectProperties
                        {
                            BuildProjects = ProjectProperties.BuildProjects,
                            Configuration = ProjectProperties.Configuration
                        }
                    }, default);

                    processor.PreProcess();

                    var projectAssembly = processor.Translator.AssemblyLocation;

                    if (File.Exists(projectAssembly))
                    {
                        referencesPathes.Add(projectAssembly);
                    }
                }
            }

            return(referencesPathes.ToArray());
        }
 public static bool ToReturnTotalRecordCount(this XDocument xlDoc)
 {
     return(xlDoc.Elements()   //fetch
            .FirstOrDefault()
            .ToReturnTotalRecordCount());
 }
Esempio n. 20
0
        /// <summary>
        /// Sub site provisioning handler
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="templateConfig"></param>
        /// <param name="page"></param>
        /// <param name="baseConfiguration"></param>
        private void DeploySubSites(ClientContext clientContext, Web web, XElement templateConfig, Page page, XDocument baseConfiguration)
        {
            XElement sitesToCreate = templateConfig.Element("Sites");

            if (sitesToCreate != null)
            {
                // If we do have sub sites defined in the config, let's provision those as well
                foreach (XElement siteToCreate in sitesToCreate.Elements())
                {
                    CreateSubSite(siteToCreate.Attribute("Url").Value, siteToCreate.Attribute("Template").Value, siteToCreate.Attribute("Title").Value, siteToCreate.Attribute("Description").Value, clientContext, page, baseConfiguration, true, web);
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="hostWebUrl"></param>
        /// <param name="txtUrl"></param>
        /// <param name="template"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="cc"></param>
        /// <param name="page"></param>
        /// <param name="baseConfiguration"></param>
        /// <returns></returns>
        public Web CreateSiteCollection(string hostWebUrl, string txtUrl, string template, string title, string description,
                                        Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration)
        {
            //get the template element
            XElement templateConfig = GetTemplateConfig(template, baseConfiguration);
            string   siteTemplate   = SolveUsedTemplate(template, templateConfig);

            //get the base tenant admin urls
            var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8);

            tenantStr = tenantStr.Substring(0, tenantStr.IndexOf("."));

            //get the current user to set as owner
            var currUser = cc.Web.CurrentUser;

            cc.Load(currUser);
            cc.ExecuteQuery();

            //create site collection using the Tenant object
            var    webUrl         = String.Format("https://{0}.sharepoint.com/{1}/{2}", tenantStr, templateConfig.Attribute("ManagedPath").Value, txtUrl);
            var    tenantAdminUri = new Uri(String.Format("https://{0}-admin.sharepoint.com", tenantStr));
            string realm          = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);
            var    token          = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken;

            using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token))
            {
                var tenant     = new Tenant(adminContext);
                var properties = new SiteCreationProperties()
                {
                    Url                  = webUrl,
                    Owner                = currUser.Email,
                    Title                = title,
                    Template             = siteTemplate,
                    StorageMaximumLevel  = Convert.ToInt32(templateConfig.Attribute("StorageMaximumLevel").Value),
                    UserCodeMaximumLevel = Convert.ToDouble(templateConfig.Attribute("UserCodeMaximumLevel").Value)
                };

                //start the SPO operation to create the site
                SpoOperation op = tenant.CreateSite(properties);
                adminContext.Load(tenant);
                adminContext.Load(op, i => i.IsComplete);
                adminContext.ExecuteQuery();

                //check if site creation operation is complete
                while (!op.IsComplete)
                {
                    //wait 30seconds and try again
                    System.Threading.Thread.Sleep(30000);
                    op.RefreshLoad();
                    adminContext.ExecuteQuery();
                }
            }

            //get the new site collection
            var siteUri = new Uri(webUrl);

            token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
            using (var newWebContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), token))
            {
                var newWeb = newWebContext.Web;
                newWebContext.Load(newWeb);
                newWebContext.ExecuteQuery();

                //process the remiander of the template configuration
                DeployFiles(newWebContext, newWeb, templateConfig);
                DeployCustomActions(newWebContext, newWeb, templateConfig);
                DeployLists(newWebContext, newWeb, templateConfig);
                DeployNavigation(newWebContext, newWeb, templateConfig);
                DeployTheme(newWebContext, newWeb, templateConfig, baseConfiguration);
                SetSiteLogo(newWebContext, newWeb, templateConfig);

                // All done, let's return the newly created site
                return(newWeb);
            }
        }
Esempio n. 22
0
        private void DeployTheme(ClientContext cc, Web newWeb, XElement templateConfig, XDocument baseConfiguration)
        {
            Web rootWeb = null;

            string theme = templateConfig.Attribute("Theme").Value;
            // Solve theme URLs from config
            XElement themeStructure  = SolveUsedThemeConfigElementFromXML(theme, baseConfiguration);
            string   colorFile       = GetWebRelativeFolderPath(themeStructure.Attribute("ColorFile").Value);
            string   fontFile        = GetWebRelativeFolderPath(themeStructure.Attribute("FontFile").Value);
            string   backgroundImage = GetWebRelativeFolderPath(themeStructure.Attribute("BackgroundFile").Value);
            // Master page is given as the name of the master, has to be uplaoded seperately if custom one is needed
            string masterPage = themeStructure.Attribute("MasterPage").Value;

            if (EnsureWeb(cc, newWeb, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant() !=
                EnsureSite(cc, cc.Site, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant())
            {
                // get instances to root web, since we are processign currently sub site
                rootWeb = cc.Site.RootWeb;
                cc.Load(rootWeb);
                cc.ExecuteQuery();
            }
            else
            {
                // Let's double check that the web is available
                rootWeb = EnsureWeb(cc, newWeb, "Title");
            }

            // Deploy theme files to root web, if they are not there and set it as active theme for the site
            newWeb.DeployThemeToSubWeb(rootWeb, theme,
                                       colorFile, fontFile, backgroundImage, masterPage);

            // Setting the theme to new web
            newWeb.SetThemeToSubWeb(rootWeb, theme);
        }
Esempio n. 23
0
        /// <summary>
        /// This is simple demo on sub site creation based on selected "template" with configurable options
        /// </summary>
        /// <param name="txtUrl"></param>
        /// <param name="template"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="cc"></param>
        /// <param name="page"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public Web CreateSubSite(string txtUrl, string template, string title, string description,
                                 Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration,
                                 bool isChildSite = false, Web subWeb = null)
        {
            // Resolve the template configuration to be used for chosen template
            XElement templateConfig = GetTemplateConfig(template, baseConfiguration);
            string   siteTemplate   = SolveUsedTemplate(template, templateConfig);

            // Create web creation configuration
            WebCreationInformation information = new WebCreationInformation();

            information.WebTemplate = siteTemplate;
            information.Description = description;
            information.Title       = title;
            information.Url         = txtUrl;
            // Currently all english, could be extended to be configurable based on language pack usage
            information.Language = 1033;

            Microsoft.SharePoint.Client.Web newWeb = null;
            //if it's child site from xml, let's do somethign else
            if (!isChildSite)
            {
                // Load host web and add new web to it.
                Microsoft.SharePoint.Client.Web web = cc.Web;
                cc.Load(web);
                cc.ExecuteQuery();
                newWeb = web.Webs.Add(information);
            }
            else
            {
                newWeb = subWeb.Webs.Add(information);
            }
            cc.ExecuteQuery();
            cc.Load(newWeb);
            cc.ExecuteQuery();

            DeployFiles(cc, newWeb, templateConfig);
            DeployCustomActions(cc, newWeb, templateConfig);
            DeployLists(cc, newWeb, templateConfig);
            DeployNavigation(cc, newWeb, templateConfig);
            DeployTheme(cc, newWeb, templateConfig, baseConfiguration);
            SetSiteLogo(cc, newWeb, templateConfig);

            if (!isChildSite)
            {
                DeploySubSites(cc, newWeb, templateConfig, page, baseConfiguration);
            }

            // All done, let's return the newly created site
            return(newWeb);
        }
Esempio n. 24
0
        /// <summary>
        /// 根据XML信息填充实实体
        /// </summary>
        /// <typeparam name="T">MessageBase为基类的类型,Response和Request都可以</typeparam>
        /// <param name="entity">实体</param>
        /// <param name="doc">XML</param>
        public static void FillEntityWithXml <T>(this T entity, XDocument doc) where T : /*MessageBase*/ class, new()
        {
            entity = entity ?? new T();
            var root = doc.Root;

            var props = entity.GetType().GetProperties();

            foreach (var prop in props)
            {
                var propName = prop.Name;
                if (root.Element(propName) != null)
                {
                    switch (prop.PropertyType.Name)
                    {
                    //case "String":
                    //    goto default;
                    case "DateTime":
                        prop.SetValue(entity, DateTimeHelper.GetDateTimeFromXml(root.Element(propName).Value), null);
                        break;

                    case "Boolean":
                        if (propName == "FuncFlag")
                        {
                            prop.SetValue(entity, root.Element(propName).Value == "1", null);
                        }
                        else
                        {
                            goto default;
                        }
                        break;

                    case "Int32":
                        prop.SetValue(entity, int.Parse(root.Element(propName).Value), null);
                        break;

                    case "Int64":
                        prop.SetValue(entity, long.Parse(root.Element(propName).Value), null);
                        break;

                    case "Double":
                        prop.SetValue(entity, double.Parse(root.Element(propName).Value), null);
                        break;

                    //以下为枚举类型
                    case "RequestMsgType":
                        //已设为只读
                        //prop.SetValue(entity, MsgTypeHelper.GetRequestMsgType(root.Element(propName).Value), null);
                        break;

                    case "ResponseMsgType":                            //Response适用
                        //已设为只读
                        //prop.SetValue(entity, MsgTypeHelper.GetResponseMsgType(root.Element(propName).Value), null);
                        break;

                    case "ThirdPartyInfo":    //ThirdPartyInfo适用
                        //已设为只读
                        //prop.SetValue(entity, MsgTypeHelper.GetResponseMsgType(root.Element(propName).Value), null);
                        break;

                    case "Event":
                        //已设为只读
                        //prop.SetValue(entity, EventHelper.GetEventType(root.Element(propName).Value), null);
                        break;

                    //以下为实体类型
                    case "List`1":                                 //List<T>类型,ResponseMessageNews适用
                        var genericArguments = prop.PropertyType.GetGenericArguments();
                        if (genericArguments[0].Name == "Article") //ResponseMessageNews适用
                        {
                            //文章下属节点item
                            List <Article> articles = new List <Article>();
                            foreach (var item in root.Element(propName).Elements("item"))
                            {
                                var article = new Article();
                                FillEntityWithXml(article, new XDocument(item));
                                articles.Add(article);
                            }
                            prop.SetValue(entity, articles, null);
                        }
                        else if (genericArguments[0].Name == "MpNewsArticle")
                        {
                            List <MpNewsArticle> mpNewsArticles = new List <MpNewsArticle>();
                            foreach (var item in root.Elements(propName))
                            {
                                var mpNewsArticle = new MpNewsArticle();
                                FillEntityWithXml(mpNewsArticle, new XDocument(item));
                                mpNewsArticles.Add(mpNewsArticle);
                            }
                            prop.SetValue(entity, mpNewsArticles, null);
                        }
                        else if (genericArguments[0].Name == "PicItem")
                        {
                            List <PicItem> picItems = new List <PicItem>();
                            foreach (var item in root.Elements(propName).Elements("item"))
                            {
                                var    picItem   = new PicItem();
                                var    picMd5Sum = item.Element("PicMd5Sum").Value;
                                Md5Sum md5Sum    = new Md5Sum()
                                {
                                    PicMd5Sum = picMd5Sum
                                };
                                picItem.item = md5Sum;
                                picItems.Add(picItem);
                            }
                            prop.SetValue(entity, picItems, null);
                        }
                        break;

                    case "Image":                            //ResponseMessageImage适用
                        Image image = new Image();
                        FillEntityWithXml(image, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, image, null);
                        break;

                    case "Voice":                            //ResponseMessageVoice适用
                        Voice voice = new Voice();
                        FillEntityWithXml(voice, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, voice, null);
                        break;

                    case "Video":                            //ResponseMessageVideo适用
                        Video video = new Video();
                        FillEntityWithXml(video, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, video, null);
                        break;

                    case "ScanCodeInfo":    //扫码事件中的ScanCodeInfo适用
                        ScanCodeInfo scanCodeInfo = new ScanCodeInfo();
                        FillEntityWithXml(scanCodeInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, scanCodeInfo, null);
                        break;

                    case "SendLocationInfo":    //弹出地理位置选择器的事件推送中的SendLocationInfo适用
                        SendLocationInfo sendLocationInfo = new SendLocationInfo();
                        FillEntityWithXml(sendLocationInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, sendLocationInfo, null);
                        break;

                    case "SendPicsInfo":    //系统拍照发图中的SendPicsInfo适用
                        SendPicsInfo sendPicsInfo = new SendPicsInfo();
                        FillEntityWithXml(sendPicsInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, sendPicsInfo, null);
                        break;

                    case "BatchJobInfo":    //异步任务完成事件推送BatchJob
                        BatchJobInfo batchJobInfo = new BatchJobInfo();
                        FillEntityWithXml(batchJobInfo, new XDocument(root.Element(propName)));
                        prop.SetValue(entity, batchJobInfo, null);
                        break;

                    default:
                        prop.SetValue(entity, root.Element(propName).Value, null);
                        break;
                    }
                }
            }
        }
Esempio n. 25
0
		void BuildTreeStore (XDocument doc)
		{
			outlineStore = new TreeStore (typeof (object));
			BuildTreeChildren (Gtk.TreeIter.Zero, doc);
		}
 public static bool IsAggregateFetchXml(this XDocument doc)
 {
     return(doc.Root.IsAttributeTrue("aggregate"));
 }
Esempio n. 27
0
 public void DocumentTest()
 {
     XDocument expected = new XDocument();
     _settings.Document = expected;
     Assert.AreEqual(expected, _settings.Document, "ClassLibrary.Settings.Document property test failed");
 }
 public static bool IsDistincFetchXml(this XDocument doc)
 {
     return(doc.Root.IsAttributeTrue("distinct"));
 }
Esempio n. 29
0
        /// <summary>
        /// 将实体转为XML
        /// </summary>
        /// <typeparam name="T">RequestMessage或ResponseMessage</typeparam>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public static XDocument ConvertEntityToXml <T>(this T entity) where T : class, new()
        {
            entity = entity ?? new T();
            var doc = new XDocument();

            doc.Add(new XElement("xml"));
            var root = doc.Root;

            /* 注意!
             * 经过测试,微信对字段排序有严格要求,这里对排序进行强制约束
             */
            var propNameOrder = new List <string>()
            {
                "ToUserName", "FromUserName", "CreateTime", "MsgType"
            };

            //不同返回类型需要对应不同特殊格式的排序
            if (entity is ResponseMessageNews)
            {
                propNameOrder.AddRange(new[] { "ArticleCount", "Articles", "FuncFlag", /*以下是Atricle属性*/ "Title ", "Description ", "PicUrl", "Url" });
            }
            else if (entity is ResponseMessageMpNews)
            {
                propNameOrder.AddRange(new[] { "MpNewsArticleCount", "MpNewsArticles", "FuncFlag", /*以下是MpNewsAtricle属性*/ "Title ", "Description ", "PicUrl", "Url" });
            }
            else if (entity is ResponseMessageImage)
            {
                propNameOrder.AddRange(new[] { "Image", /*以下是Image属性*/ "MediaId " });
            }
            else if (entity is ResponseMessageVoice)
            {
                propNameOrder.AddRange(new[] { "Voice", /*以下是Voice属性*/ "MediaId " });
            }
            else if (entity is ResponseMessageVideo)
            {
                propNameOrder.AddRange(new[] { "Video", /*以下是Video属性*/ "MediaId ", "Title", "Description" });
            }
            else
            {
                //如Text类型
                propNameOrder.AddRange(new[] { "Content", "FuncFlag" });
            }

            propNameOrder.AddRange(new[] { "AgentID" });

            Func <string, int> orderByPropName = propNameOrder.IndexOf;

            var props = entity.GetType().GetProperties().OrderBy(p => orderByPropName(p.Name)).ToList();

            foreach (var prop in props)
            {
                var propName = prop.Name;
                if (propName == "Articles")
                {
                    //文章列表
                    var atriclesElement = new XElement("Articles");
                    var articales       = prop.GetValue(entity, null) as List <Article>;
                    foreach (var articale in articales)
                    {
                        var subNodes = ConvertEntityToXml(articale).Root.Elements();
                        atriclesElement.Add(new XElement("item", subNodes));
                    }
                    root.Add(atriclesElement);
                }
                else if (propName == "MpNewsArticles")
                {
                    var mpNewsAtriclesElement = new XElement("MpNewsArticles");
                    var mpNewsAtricles        = prop.GetValue(entity, null) as List <MpNewsArticle>;
                    foreach (var mpNewsArticale in mpNewsAtricles)
                    {
                        var subNodes = ConvertEntityToXml(mpNewsArticale).Root.Elements();
                        mpNewsAtriclesElement.Add(subNodes);
                    }

                    root.Add(mpNewsAtriclesElement);
                }
                else if (propName == "Image" || propName == "Video" || propName == "Voice")
                {
                    //图片、视频、语音格式
                    var musicElement = new XElement(propName);
                    var media        = prop.GetValue(entity, null);
                    var subNodes     = ConvertEntityToXml(media).Root.Elements();
                    musicElement.Add(subNodes);
                    root.Add(musicElement);
                }
                else if (propName == "KfAccount")
                {
                    root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                }
                else
                {
                    switch (prop.PropertyType.Name)
                    {
                    case "String":
                        root.Add(new XElement(propName,
                                              new XCData(prop.GetValue(entity, null) as string ?? "")));
                        break;

                    case "DateTime":
                        root.Add(new XElement(propName, DateTimeHelper.GetWeixinDateTime((DateTime)prop.GetValue(entity, null))));
                        break;

                    case "Boolean":
                        if (propName == "FuncFlag")
                        {
                            root.Add(new XElement(propName, (bool)prop.GetValue(entity, null) ? "1" : "0"));
                        }
                        else
                        {
                            goto default;
                        }
                        break;

                    case "ResponseMsgType":
                        root.Add(new XElement(propName, new XCData(prop.GetValue(entity, null).ToString().ToLower())));
                        break;

                    case "Article":
                        root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                        break;

                    case "MpNewsArticle":
                        root.Add(new XElement(propName, prop.GetValue(entity, null).ToString().ToLower()));
                        break;

                    default:
                        root.Add(new XElement(propName, prop.GetValue(entity, null)));
                        break;
                    }
                }
            }
            return(doc);
        }
 // main functions
 public void LoadXmlDocument()
 {
     Document = XDocument.Load(Util.XMLPath);
     Symbols  = new Dictionary <string, List <SymbolEntry> >();
 }
Esempio n. 31
0
        public void Provision(ClientContext ctx, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation, TokenParser tokenParser, PnPMonitoredScope scope, string configurationData)
        {
            if (!string.IsNullOrEmpty(configurationData))
            {
                // Get the current web
                var web = ctx.Web;

                // Read configuration data from the template
                var configuration = XDocument.Parse(configurationData);
                var ns            = configuration.Root.GetDefaultNamespace();

                var libraries = configuration.Descendants(ns + "Library");

                foreach (var library in libraries)
                {
                    var libraryTitle = library.Attribute("Title").Value;

                    //Get the library
                    List list = ctx.Web.Lists.GetByTitle(libraryTitle);

                    if (list != null)
                    {
                        var items = library.Descendants(ns + "Default");

                        foreach (var item in items)
                        {
                            // Get configuration infos
                            var fieldName  = item.Attribute("InternalName").Value;
                            var fieldValue = item.Attribute("Value").Value;
                            var folder     = item.Attribute("Folder").Value;

                            // Get the field
                            var field = list.Fields.GetByInternalNameOrTitle(fieldName);
                            ctx.Load(field, f => f.InternalName, f => f.TypeAsString);
                            ctx.ExecuteQueryRetry();

                            if (field != null)
                            {
                                IDefaultColumnValue defaultColumnValue = null;
                                if (field.TypeAsString == "Text")
                                {
                                    var values = string.Join(";", fieldValue);
                                    defaultColumnValue = new DefaultColumnTextValue()
                                    {
                                        FieldInternalName  = field.InternalName,
                                        FolderRelativePath = folder,
                                        Text = values
                                    };
                                }
                                else
                                {
                                    var terms  = new List <Microsoft.SharePoint.Client.Taxonomy.Term>();
                                    var values = fieldValue.Split(';');

                                    foreach (var termString in values)
                                    {
                                        var term = ctx.Site.GetTaxonomyItemByPath(termString);
                                        if (term != null)
                                        {
                                            terms.Add(term as Microsoft.SharePoint.Client.Taxonomy.Term);
                                        }
                                    }
                                    if (terms.Any())
                                    {
                                        defaultColumnValue = new DefaultColumnTermValue()
                                        {
                                            FieldInternalName  = field.InternalName,
                                            FolderRelativePath = folder,
                                        };
                                        terms.ForEach(t => ((DefaultColumnTermValue)defaultColumnValue).Terms.Add(t));
                                    }
                                }

                                if (defaultColumnValue != null)
                                {
                                    list.SetDefaultColumnValues(new List <IDefaultColumnValue>()
                                    {
                                        defaultColumnValue
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 32
0
        public static void Load(XDocument doc)
        {
            App item = Populate(doc);

            Configuration.GetInstance().App = item;
        }
Esempio n. 33
0
        /*public Boolean ReserveRoom(String r,int floor)
        {
           Boolean str= c.ReserveRoom(r,floor);
            return str;
        }
        */

        public int WriteHotelRooms(String room)
        {
            int floorno = 1;
            int roomno = 1;
            int roomlimit = 0;
            if (room.Equals("Standard"))
            {
                floorno = 1;
                roomno = 1;
                roomlimit = 10;
            }
            else if (room.Equals("Moderate"))
            {
                floorno = 1;
                roomno = 11;
                roomlimit = 20;
            }
            else if (room.Equals("Superior"))
            {
                floorno = 1;
                roomno = 21;
                roomlimit = 30;
            }
            else if (room.Equals("Junior Suite"))
            {
                floorno = 1;
                roomno = 31;
                roomlimit = 40;
            }
            else if (room.Equals("Suite"))
            {
                floorno = 1;
                roomno = 41;
                roomlimit = 50;
            }
            else
                return 0;
            String r = room + ".xml";
            Console.WriteLine(r);

            for (; floorno <= 5; floorno++)
            {
                for (; roomno <= roomlimit; roomno++)
                {
//                    Console.WriteLine("yes");

                    if (File.Exists(r) == false)
                    {
                        //                      Console.WriteLine("yesss");

                        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                        xmlWriterSettings.Indent = true;
                        xmlWriterSettings.NewLineOnAttributes = true;
                        using (XmlWriter xmlWriter = XmlWriter.Create(r, xmlWriterSettings))
                        {
//                            Console.WriteLine("ysss");

                            xmlWriter.WriteStartDocument();
                            xmlWriter.WriteStartElement("Hotel");

                            xmlWriter.WriteStartElement("Customer");
                            xmlWriter.WriteElementString("Name", "");
                            //xmlWriter.WriteElementString("Age", "");
                            //xmlWriter.WriteElementString("Gender", "");
                            xmlWriter.WriteElementString("IDCardNo", "");
                            //xmlWriter.WriteElementString("BalanceRs", "");
                            //xmlWriter.WriteElementString("DaysReserve", "");
                            xmlWriter.WriteElementString("FloorNo", floorno.ToString());
                            //xmlWriter.WriteElementString("RoomType", "Standard");
                            xmlWriter.WriteElementString("Roomno", roomno.ToString());
                            // xmlWriter.WriteElementString("CheckInTime", "");
                            // xmlWriter.WriteElementString("CheckOutTime", "");
                            // xmlWriter.WriteElementString("TimeRemaining", "");
                            xmlWriter.WriteElementString("Status", "notreserve");

                            xmlWriter.WriteEndElement();

                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndDocument();
                            xmlWriter.Flush();
                            xmlWriter.Close();
                        }
                    }
                    else
                    {
                        XDocument xDocument = XDocument.Load(r);
                        XElement root = xDocument.Element("Hotel");
                        IEnumerable<XElement> rows = root.Descendants("Customer");
                        XElement firstRow = rows.First();
                        firstRow.AddBeforeSelf(
                            new XElement("Customer",
                                new XElement("Name", ""),
                                //new XElement("Age", ""),
                                //new XElement("Gender", ""),
                                new XElement("IDCardNo", ""),
                                //new XElement("BalanceRs", ""),
                                //new XElement("DaysReserve", ""),
              
                                new XElement("FloorNo", floorno.ToString()),
                                //new XElement("RoomType", "Standard"),
                                new XElement("Roomno", roomno.ToString()),
                                //new XElement("CheckInTime", ""),
                                //new XElement("CheckOutTime", ""),
                                //new XElement("TimeRemaining", ""),
                                new XElement("Status", "notreserve")));


                        xDocument.Save(r);
                    }
                }
                roomlimit = roomlimit + 10;
            }
            return 0;
        }
Esempio n. 34
0
        public override NBi.Core.ResultSet.ResultSet Execute()
        {
            var doc = XDocument.Load(Url);

            return(Execute(doc));
        }
Esempio n. 35
0
    protected void btnsend_Click(object sender, ImageClickEventArgs e)

    {
        string opt = RadioButtonList1.SelectedValue;

        r.Text = "";
        g.Text = "";
        if (opt == "1")
        {
            g.ForeColor = System.Drawing.Color.Green;
            g.Text      = "Thanks for taking the time to give us feedback";

            XDocument xdocx = XDocument.Load(Server.MapPath("~/Feedback_Store.xml"));

            // adding to remarks page


            XElement root = new XElement("User");
            DateTime dt;
            dt = DateTime.Now;
            String datetimeshow = dt.ToLongDateString();
            String name         = Convert.ToString(Session["Signinname"]);
            root.Add(new XElement("Username", name));
            root.Add(new XElement("Dated", datetimeshow));
            root.Add(new XElement("Feedback", TextBox1.Text));
            root.Add(new XElement("Rate", "1"));


            xdocx.Element("Feedbacks").Add(root);

            xdocx.Save(Server.MapPath("~/Feedback_Store.xml"));
        }
        else if (opt == "2")
        {
            g.ForeColor = System.Drawing.Color.Green;
            g.Text      = "Thanks for taking the time to give us feedback";

            XDocument xdocx = XDocument.Load(Server.MapPath("~/Feedback_Store.xml"));

            // adding to remarks page


            XElement root = new XElement("User");
            DateTime dt;
            dt = DateTime.Now;
            String datetimeshow = dt.ToLongDateString();
            String name         = Convert.ToString(Session["Signinname"]);
            root.Add(new XElement("Username", name));
            root.Add(new XElement("Dated", datetimeshow));
            root.Add(new XElement("Feedback", TextBox1.Text));
            root.Add(new XElement("Rate", "2"));


            xdocx.Element("Feedbacks").Add(root);

            xdocx.Save(Server.MapPath("~/Feedback_Store.xml"));
        }
        else if (opt == "3")
        {
            g.ForeColor = System.Drawing.Color.Green;
            g.Text      = "Thanks for taking the time to give us feedback";

            XDocument xdocx = XDocument.Load(Server.MapPath("~/Feedback_Store.xml"));

            // adding to remarks page


            XElement root = new XElement("User");
            DateTime dt;
            dt = DateTime.Now;
            String datetimeshow = dt.ToLongDateString();
            String name         = Convert.ToString(Session["Signinname"]);
            root.Add(new XElement("Username", name));
            root.Add(new XElement("Dated", datetimeshow));
            root.Add(new XElement("Feedback", TextBox1.Text));
            root.Add(new XElement("Rate", "3"));


            xdocx.Element("Feedbacks").Add(root);

            xdocx.Save(Server.MapPath("~/Feedback_Store.xml"));
        }
        else if (opt == "4")
        {
            g.ForeColor = System.Drawing.Color.Green;
            g.Text      = "Thanks for taking the time to give us feedback";

            XDocument xdocx = XDocument.Load(Server.MapPath("~/Feedback_Store.xml"));

            // adding to remarks page


            XElement root = new XElement("User");
            DateTime dt;
            dt = DateTime.Now;
            String datetimeshow = dt.ToLongDateString();
            String name         = Convert.ToString(Session["Signinname"]);
            root.Add(new XElement("Username", name));
            root.Add(new XElement("Dated", datetimeshow));
            root.Add(new XElement("Feedback", TextBox1.Text));
            root.Add(new XElement("Rate", "4"));


            xdocx.Element("Feedbacks").Add(root);

            xdocx.Save(Server.MapPath("~/Feedback_Store.xml"));
        }
        else if (opt == "5")
        {
            g.ForeColor = System.Drawing.Color.Green;
            g.Text      = "Thanks for taking the time to give us feedback";

            XDocument xdocx = XDocument.Load(Server.MapPath("~/Feedback_Store.xml"));

            // adding to remarks page


            XElement root = new XElement("User");
            DateTime dt;
            dt = DateTime.Now;
            String datetimeshow = dt.ToLongDateString();
            String name         = Convert.ToString(Session["Signinname"]);
            root.Add(new XElement("Username", name));
            root.Add(new XElement("Dated", datetimeshow));
            root.Add(new XElement("Feedback", TextBox1.Text));
            root.Add(new XElement("Rate", "5"));


            xdocx.Element("Feedbacks").Add(root);

            xdocx.Save(Server.MapPath("~/Feedback_Store.xml"));
        }

        else if (opt == "")
        {
            r.ForeColor = System.Drawing.Color.Red;
            r.Text      = "Fill the choices First !!";
        }
    }
Esempio n. 36
0
            private void createLists()
            {
                // Product data created in-memory using collection initializer:
                productList =
                    new List <Product> {
                    new Product {
                        ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39
                    },
                    new Product {
                        ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17
                    },
                    new Product {
                        ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13
                    },
                    new Product {
                        ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53
                    },
                    new Product {
                        ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0
                    },
                    new Product {
                        ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120
                    },
                    new Product {
                        ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15
                    },
                    new Product {
                        ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6
                    },
                    new Product {
                        ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29
                    },
                    new Product {
                        ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31
                    },
                    new Product {
                        ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products", UnitPrice = 21.0000M, UnitsInStock = 22
                    },
                    new Product {
                        ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products", UnitPrice = 38.0000M, UnitsInStock = 86
                    },
                    new Product {
                        ProductID = 13, ProductName = "Konbu", Category = "Seafood", UnitPrice = 6.0000M, UnitsInStock = 24
                    },
                    new Product {
                        ProductID = 14, ProductName = "Tofu", Category = "Produce", UnitPrice = 23.2500M, UnitsInStock = 35
                    },
                    new Product {
                        ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments", UnitPrice = 15.5000M, UnitsInStock = 39
                    },
                    new Product {
                        ProductID = 16, ProductName = "Pavlova", Category = "Confections", UnitPrice = 17.4500M, UnitsInStock = 29
                    },
                    new Product {
                        ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry", UnitPrice = 39.0000M, UnitsInStock = 0
                    },
                    new Product {
                        ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood", UnitPrice = 62.5000M, UnitsInStock = 42
                    },
                    new Product {
                        ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections", UnitPrice = 9.2000M, UnitsInStock = 25
                    },
                    new Product {
                        ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections", UnitPrice = 81.0000M, UnitsInStock = 40
                    },
                    new Product {
                        ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections", UnitPrice = 10.0000M, UnitsInStock = 3
                    },
                    new Product {
                        ProductID = 22, ProductName = "Gustaf's Kn�ckebr�d", Category = "Grains/Cereals", UnitPrice = 21.0000M, UnitsInStock = 104
                    },
                    new Product {
                        ProductID = 23, ProductName = "Tunnbr�d", Category = "Grains/Cereals", UnitPrice = 9.0000M, UnitsInStock = 61
                    },
                    new Product {
                        ProductID = 24, ProductName = "Guaran� Fant�stica", Category = "Beverages", UnitPrice = 4.5000M, UnitsInStock = 20
                    },
                    new Product {
                        ProductID = 25, ProductName = "NuNuCa Nu�-Nougat-Creme", Category = "Confections", UnitPrice = 14.0000M, UnitsInStock = 76
                    },
                    new Product {
                        ProductID = 26, ProductName = "Gumb�r Gummib�rchen", Category = "Confections", UnitPrice = 31.2300M, UnitsInStock = 15
                    },
                    new Product {
                        ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections", UnitPrice = 43.9000M, UnitsInStock = 49
                    },
                    new Product {
                        ProductID = 28, ProductName = "R�ssle Sauerkraut", Category = "Produce", UnitPrice = 45.6000M, UnitsInStock = 26
                    },
                    new Product {
                        ProductID = 29, ProductName = "Th�ringer Rostbratwurst", Category = "Meat/Poultry", UnitPrice = 123.7900M, UnitsInStock = 0
                    },
                    new Product {
                        ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood", UnitPrice = 25.8900M, UnitsInStock = 10
                    },
                    new Product {
                        ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products", UnitPrice = 12.5000M, UnitsInStock = 0
                    },
                    new Product {
                        ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products", UnitPrice = 32.0000M, UnitsInStock = 9
                    },
                    new Product {
                        ProductID = 33, ProductName = "Geitost", Category = "Dairy Products", UnitPrice = 2.5000M, UnitsInStock = 112
                    },
                    new Product {
                        ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 111
                    },
                    new Product {
                        ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 20
                    },
                    new Product {
                        ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood", UnitPrice = 19.0000M, UnitsInStock = 112
                    },
                    new Product {
                        ProductID = 37, ProductName = "Gravad lax", Category = "Seafood", UnitPrice = 26.0000M, UnitsInStock = 11
                    },
                    new Product {
                        ProductID = 38, ProductName = "C�te de Blaye", Category = "Beverages", UnitPrice = 263.5000M, UnitsInStock = 17
                    },
                    new Product {
                        ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 69
                    },
                    new Product {
                        ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood", UnitPrice = 18.4000M, UnitsInStock = 123
                    },
                    new Product {
                        ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood", UnitPrice = 9.6500M, UnitsInStock = 85
                    },
                    new Product {
                        ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals", UnitPrice = 14.0000M, UnitsInStock = 26
                    },
                    new Product {
                        ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages", UnitPrice = 46.0000M, UnitsInStock = 17
                    },
                    new Product {
                        ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments", UnitPrice = 19.4500M, UnitsInStock = 27
                    },
                    new Product {
                        ProductID = 45, ProductName = "Rogede sild", Category = "Seafood", UnitPrice = 9.5000M, UnitsInStock = 5
                    },
                    new Product {
                        ProductID = 46, ProductName = "Spegesild", Category = "Seafood", UnitPrice = 12.0000M, UnitsInStock = 95
                    },
                    new Product {
                        ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections", UnitPrice = 9.5000M, UnitsInStock = 36
                    },
                    new Product {
                        ProductID = 48, ProductName = "Chocolade", Category = "Confections", UnitPrice = 12.7500M, UnitsInStock = 15
                    },
                    new Product {
                        ProductID = 49, ProductName = "Maxilaku", Category = "Confections", UnitPrice = 20.0000M, UnitsInStock = 10
                    },
                    new Product {
                        ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections", UnitPrice = 16.2500M, UnitsInStock = 65
                    },
                    new Product {
                        ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce", UnitPrice = 53.0000M, UnitsInStock = 20
                    },
                    new Product {
                        ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals", UnitPrice = 7.0000M, UnitsInStock = 38
                    },
                    new Product {
                        ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry", UnitPrice = 32.8000M, UnitsInStock = 0
                    },
                    new Product {
                        ProductID = 54, ProductName = "Tourti�re", Category = "Meat/Poultry", UnitPrice = 7.4500M, UnitsInStock = 21
                    },
                    new Product {
                        ProductID = 55, ProductName = "P�t� chinois", Category = "Meat/Poultry", UnitPrice = 24.0000M, UnitsInStock = 115
                    },
                    new Product {
                        ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals", UnitPrice = 38.0000M, UnitsInStock = 21
                    },
                    new Product {
                        ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals", UnitPrice = 19.5000M, UnitsInStock = 36
                    },
                    new Product {
                        ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood", UnitPrice = 13.2500M, UnitsInStock = 62
                    },
                    new Product {
                        ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products", UnitPrice = 55.0000M, UnitsInStock = 79
                    },
                    new Product {
                        ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products", UnitPrice = 34.0000M, UnitsInStock = 19
                    },
                    new Product {
                        ProductID = 61, ProductName = "Sirop d'�rable", Category = "Condiments", UnitPrice = 28.5000M, UnitsInStock = 113
                    },
                    new Product {
                        ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections", UnitPrice = 49.3000M, UnitsInStock = 17
                    },
                    new Product {
                        ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments", UnitPrice = 43.9000M, UnitsInStock = 24
                    },
                    new Product {
                        ProductID = 64, ProductName = "Wimmers gute Semmelkn�del", Category = "Grains/Cereals", UnitPrice = 33.2500M, UnitsInStock = 22
                    },
                    new Product {
                        ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments", UnitPrice = 21.0500M, UnitsInStock = 76
                    },
                    new Product {
                        ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments", UnitPrice = 17.0000M, UnitsInStock = 4
                    },
                    new Product {
                        ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 52
                    },
                    new Product {
                        ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections", UnitPrice = 12.5000M, UnitsInStock = 6
                    },
                    new Product {
                        ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products", UnitPrice = 36.0000M, UnitsInStock = 26
                    },
                    new Product {
                        ProductID = 70, ProductName = "Outback Lager", Category = "Beverages", UnitPrice = 15.0000M, UnitsInStock = 15
                    },
                    new Product {
                        ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products", UnitPrice = 21.5000M, UnitsInStock = 26
                    },
                    new Product {
                        ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products", UnitPrice = 34.8000M, UnitsInStock = 14
                    },
                    new Product {
                        ProductID = 73, ProductName = "R�d Kaviar", Category = "Seafood", UnitPrice = 15.0000M, UnitsInStock = 101
                    },
                    new Product {
                        ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce", UnitPrice = 10.0000M, UnitsInStock = 4
                    },
                    new Product {
                        ProductID = 75, ProductName = "Rh�nbr�u Klosterbier", Category = "Beverages", UnitPrice = 7.7500M, UnitsInStock = 125
                    },
                    new Product {
                        ProductID = 76, ProductName = "Lakkalik��ri", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 57
                    },
                    new Product {
                        ProductID = 77, ProductName = "Original Frankfurter gr�ne So�e", Category = "Condiments", UnitPrice = 13.0000M, UnitsInStock = 32
                    }
                };

                // Customer/Order data read into memory from XML file using XLinq:
                customerList = (
                    from e in XDocument.Load(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("RestrictionOperators.customers.xml")).
                    Root.Elements("customer")
                    select new Customer
                {
                    CustomerID = (string)e.Element("id"),
                    CompanyName = (string)e.Element("name"),
                    Address = (string)e.Element("address"),
                    City = (string)e.Element("city"),
                    Region = (string)e.Element("region"),
                    PostalCode = (string)e.Element("postalcode"),
                    Country = (string)e.Element("country"),
                    Phone = (string)e.Element("phone"),
                    Fax = (string)e.Element("fax"),
                    Orders = (
                        from o in e.Elements("orders").Elements("order")
                        select new Order
                    {
                        OrderID = (int)o.Element("id"),
                        OrderDate = (DateTime)o.Element("orderdate"),
                        Total = (decimal)o.Element("total")
                    })
                             .ToArray()
                })
                               .ToList();
            }
Esempio n. 37
0
        /// <summary>
        /// Parses a trx file (as produced by MS Test) and returns a set of <see cref="TestResult"/> objects.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <returns>Set of test results.</returns>
        /// <exception cref="System.IO.FileNotFoundException">The file ' + filename + ' does not exist.</exception>
        public IEnumerable <TestResult> Parse(string filename)
        {
            filename.ThrowIfFileDoesNotExist("filename");

            try
            {
                XNamespace        ns  = @"http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
                XDocument         doc = null;
                XmlReaderSettings xmlReaderSettings = new XmlReaderSettings {
                    CheckCharacters = false
                };
                using (XmlReader xmlReader = XmlReader.Create(filename, xmlReaderSettings))
                {
                    xmlReader.MoveToContent();
                    doc = XDocument.Load(xmlReader);
                }

                var testDefinitions = (from unitTest in doc.Descendants(ns + "UnitTest")
                                       select new
                {
                    executionId = unitTest.Element(ns + "Execution").Attribute("id").Value,
                    codeBase = unitTest.Element(ns + "TestMethod").Attribute("codeBase").Value,
                    className = unitTest.Element(ns + "TestMethod").Attribute("className").Value,
                    testName = unitTest.Element(ns + "TestMethod").Attribute("name").Value
                }
                                       ).ToList();


                var results = (from utr in doc.Descendants(ns + "UnitTestResult")
                               let executionId = utr.Attribute("executionId").Value
                                                 let message = utr.Descendants(ns + "Message").FirstOrDefault()
                                                               let stackTrace = utr.Descendants(ns + "StackTrace").FirstOrDefault()
                                                                                let st = DateTime.Parse(utr.Attribute("startTime").Value).ToUniversalTime()
                                                                                         let et = DateTime.Parse(utr.Attribute("endTime").Value).ToUniversalTime()
                                                                                                  select new TestResult()
                {
                    TestResultFileType = Core.InputFileType.Trx,
                    ResultsPathName = filename,
                    AssemblyPathName = (from td in testDefinitions where td.executionId == executionId select td.codeBase).Single(),
                    FullClassName = (from td in testDefinitions where td.executionId == executionId select td.className).Single(),
                    ComputerName = utr.Attribute("computerName").Value,
                    StartTime = st,
                    EndTime = et,
                    Outcome = utr.Attribute("outcome").Value,
                    TestName = utr.Attribute("testName").Value,
                    ErrorMessage = message == null ? "" : message.Value,
                    StackTrace = stackTrace == null ? "" : stackTrace.Value,
                    DurationInSeconds = (et - st).TotalSeconds
                }
                               ).OrderBy(r => r.ResultsPathName).
                              ThenBy(r => r.AssemblyPathName).
                              ThenBy(r => r.ClassName).
                              ThenBy(r => r.TestName).
                              ThenBy(r => r.StartTime);

                return(results);
            }
            catch (Exception ex)
            {
                throw new ParseException("Error while parsing Trx file '" + filename + "'", ex);
            }
        }
Esempio n. 38
0
 /// <summary>
 /// Runs test for valid cases
 /// </summary>
 /// <param name="nodeType">XElement/XAttribute</param>
 /// <param name="name">name to be tested</param>
 public void RunValidTests(string nodeType, string name)
 {
     XDocument xDocument = new XDocument();
     XElement element = null;
     switch (nodeType)
     {
         case "XElement":
             element = new XElement(name, name);
             xDocument.Add(element);
             IEnumerable<XNode> nodeList = xDocument.Nodes();
             Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
             xDocument.RemoveNodes();
             break;
         case "XAttribute":
             element = new XElement(name, name);
             XAttribute attribute = new XAttribute(name, name);
             element.Add(attribute);
             xDocument.Add(element);
             XAttribute x = element.Attribute(name);
             Assert.Equal(name, x.Name.LocalName);
             xDocument.RemoveNodes();
             break;
         case "XName":
             XName xName = XName.Get(name, name);
             Assert.Equal(name, xName.LocalName);
             Assert.Equal(name, xName.NamespaceName);
             Assert.Equal(name, xName.Namespace.NamespaceName);
             break;
         default:
             break;
     }
 }
Esempio n. 39
0
 public DatabaseContext(string path, string name)
 {
     _database  = new Database(string.Format(@"{0}\{1}", path, name));
     _xDocument = XDocument.Load(_database.GetPath());
 }
Esempio n. 40
0
		void Populate (XDocument doc)
		{
			var project = doc.Nodes.OfType<XElement> ().FirstOrDefault (x => x.Name == xnProject);
			if (project == null)
				return;
			var pel = MSBuildElement.Get ("Project");
			foreach (var el in project.Nodes.OfType<XElement> ())
				Populate (el, pel);
		}
Esempio n. 41
0
 public void XDocumentToStringThrowsForXDocumentContainingOnlyWhitespaceNodes()
 {
     // XDocument.ToString() throw exception for the XDocument containing whitespace node only
     XDocument d = new XDocument();
     d.Add(" ");
     string s = d.ToString();
 }
Esempio n. 42
0
        /// <summary>
        /// Informs the screen manager to serialize its state to disk.
        /// </summary>
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else
            // Open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Create an XML document to hold the list of screen types currently in the stack
                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                // Make a copy of the master screen list, to avoid confusion if
                // the process of deactivating one screen adds or removes others.
                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                // Iterate the screens to store in our XML file and deactivate them
                foreach (GameScreen screen in tempScreensList)
                {
                    // Only add the screen to our XML if it is serializable
                    if (screen.IsSerializable)
                    {
                        // We store the screen's controlling player so we can rehydrate that value
                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    // Deactivate the screen regardless of whether we serialized it
                    screen.Deactivate();
                }

                // Save the document
                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
Esempio n. 43
0
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                foreach (GameScreen screen in tempScreensList)
                {

                    if (screen.IsSerializable)
                    {

                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    screen.Deactivate();
                }

                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
Esempio n. 44
0
 public void DifferentDocumentSameNamespaceSameNameElements()
 {
     XDocument xDoc1 = new XDocument(new XElement("{Namespace}Name"));
     XDocument xDoc2 = new XDocument(new XElement("{Namespace}Name"));
     Assert.Same((xDoc1.FirstNode as XElement).Name.Namespace, (xDoc2.FirstNode as XElement).Name.Namespace);
     Assert.Same((xDoc1.FirstNode as XElement).Name, (xDoc2.FirstNode as XElement).Name);
 }
Esempio n. 45
0
        public void Document1()
        {
            object[] content = new object[]
            {
                new object[] { new string[] { " ", null, " " }, "  " },
                new object[] { new string[] { " ", " \t" }, new XText("  \t") },
                new object[] { new XText[] { new XText(" "), new XText("\t") }, new XText(" \t") },
                new XDocumentType("root", "", "", ""), new XProcessingInstruction("PI1", ""), new XText("\n"),
                new XText("\t"), new XText("       "), new XProcessingInstruction("PI1", ""), new XElement("myroot"),
                new XProcessingInstruction("PI2", "click"),
                new object[]
                {
                    new XElement("X", new XAttribute("id", "a1"), new XText("hula")),
                    new XElement("X", new XText("hula"), new XAttribute("id", "a1"))
                },
                new XComment(""),
                new XComment("comment"),
            };

            foreach (object[] objs in content.NonRecursiveVariations(4))
            {
                XDocument doc1 = null;
                XDocument doc2 = null;
                try
                {
                    object[] o1 = ExpandAndProtectTextNodes(objs, 0).ToArray();
                    object[] o2 = ExpandAndProtectTextNodes(objs, 1).ToArray();
                    if (o1.Select(x => new ExpectedValue(false, x)).IsXDocValid()
                        || o2.Select(x => new ExpectedValue(false, x)).IsXDocValid()) continue;
                    doc1 = new XDocument(o1);
                    doc2 = new XDocument(o2);
                    VerifyComparison(true, doc1, doc2);
                }
                catch (InvalidOperationException)
                {
                    // some combination produced from the array are invalid
                    continue;
                }
                finally
                {
                    if (doc1 != null) doc1.RemoveNodes();
                    if (doc2 != null) doc2.RemoveNodes();
                }
            }
        }
Esempio n. 46
0
 public static void ElementsOnXDocBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XElement> nodes = xDoc.Elements();
     Assert.Equal(1, nodes.Count());
     a.Remove();
     Assert.Equal(0, nodes.Count());
 }
Esempio n. 47
0
        //public Encoding Encoding { get; set; }

        public XmlResult(XDocument xml)
        {
            this.Xml         = xml;
            this.ContentType = "text/xml";
        }
Esempio n. 48
0
 internal XmlConfig(string filepath, XDocument content)
     : base(filepath)
 {
     xDoc = content;
 }
Esempio n. 49
0
        /// <summary>
        /// Creates the new infopath and load form.
        /// </summary>
        /// <param name="FormUri">The form URI.</param>
        /// <param name="InfoPathLoginHandler">The info path login handler.</param>
        /// <param name="readOnly">if set to <c>true</c> [read only].</param>
        private void CreateNewInfopathAndLoadForm(string FormUri, LogonDialogHandler InfoPathLoginHandler, bool readOnly)
        {
            // Kill off any existing infopath processes
            foreach (Process proc in Process.GetProcessesByName("infopath"))
            {
                proc.Kill();
            }

            InitInfopathAndStartDialogWatcher(new Application());
            SecurityAlertHandler securityHandler = new SecurityAlertHandler();
            ReplaceFormAlertHandler replaceFormHandler = new ReplaceFormAlertHandler();
            DialogWatcher.Add(securityHandler);
            DialogWatcher.Add(replaceFormHandler);
            if (InfoPathLoginHandler != null)
            {
                // remove other logon dialog handlers since only one handler
                // can effectively handle the logon dialog.
                DialogWatcher.RemoveAll(new LogonDialogHandler("a", "b"));

                // Add the (new) logonHandler
                DialogWatcher.Add(InfoPathLoginHandler);
            }
            if (readOnly)
            {
                InternalInfopathXDocument = InfopathApplicationTester.XDocuments.Open(FormUri, (int)XdDocumentVersionMode.xdCanOpenInReadOnlyMode);
            }
            else
            {
                InternalInfopathXDocument = InfopathApplicationTester.XDocuments.Open(FormUri, (int)XdDocumentVersionMode.xdFailOnVersionOlder);
            }

            InternalInfopathXMLDOMDocument = InternalInfopathXDocument.DOM as IXMLDOMDocument2;
            InternalHTMLDOMDocument = IEDom.IEDOMFromhWnd(this.hWnd);
        }
Esempio n. 50
0
 public Withdraw(string userID, XDocument atmUsers)
 {
     InitializeComponent();
     this.userID   = userID;
     this.atmUsers = atmUsers;
 }
Esempio n. 51
0
        /// <summary>
        /// Runs test for InValid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        public void RunInValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement element = null;
            try
            {
                switch (nodeType)
                {
                    case "XElement":
                        element = new XElement(name, name);
                        xDocument.Add(element);
                        IEnumerable<XNode> nodeList = xDocument.Nodes();
                        break;
                    case "XAttribute":
                        element = new XElement(name, name);
                        XAttribute attribute = new XAttribute(name, name);
                        element.Add(attribute);
                        xDocument.Add(element);
                        XAttribute x = element.Attribute(name);
                        break;
                    case "XName":
                        XName xName = XName.Get(name, name);
                        break;
                    default:
                        break;
                }
            }
            catch (XmlException)
            {
                return;
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.True(false, "Expected exception not thrown");
        }
Esempio n. 52
0
 public NetworkHandler(String pay_load)
 {
     this.payload = pay_load;
     this.xd      = new XDocument();
 }
Esempio n. 53
0
        private void Game_UpdateFrame(object sender, FrameEventArgs e)
        {
            PreviousMouseState = MouseState;
            PreviousKeyboardState = KeyboardState;

            MouseState = OpenTK.Input.Mouse.GetState();
            KeyboardState = OpenTK.Input.Keyboard.GetState();

            PreviousMousePosition = MousePosition;

            #if GRAPHMAKER
            XDocument doc = new XDocument();
            doc.Add(new XElement("Waypoints"));
            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released) {
            int x = Camera.X + MousePosition.X;
            int y = Camera.Y + MousePosition.Y;

            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released && MousePosition.X > 40) {
               doc.Element("Waypoints").Add(new XElement("Waypoint", new XAttribute("X", x), new XAttribute("Y", y)));
               minID++;
               Minion markerMinion = new Minion(new List<Sprite>() { new Sprite(new List<string>() { "Images/BlueMinion.png" }), new Sprite(new List<string>() { "Images/BlueMinion0.png", "Images/BlueMinion1.png" }) }, minID);
                markerMinion.Pos.X = x;
                markerMinion.Pos.Y = y;
                _player1.AddMinion(markerMinion);
              // doc.Save("TestWaypoint.xml");
            XDocument doc = new XDocument();
            doc.Add(new XElement("Waypoints"));
            if (MouseState.LeftButton == ButtonState.Pressed && PreviousMouseState.LeftButton == ButtonState.Released) {
            }

            if (MouseState.RightButton == ButtonState.Pressed && PreviousMouseState.RightButton == ButtonState.Released && MousePosition.X > 40)
            {
                switch (rightClicks)
                {
                    case 0: clicks[0] = x;
                        clicks[1] = y;
                        break;

                    case 1:
                        clicks[2] = x;
                        clicks[3] = y;
                         minID++;
                         Minion markerMinion = new Minion(new List<Sprite>() { new Sprite(new List<string>() { "Images/square.png" }), new Sprite(new List<string>() { "Images/square.png", "Images/square.png" }) }, minID);
                         WaypointNode waypoint1 = graph.GetClosestWaypoint(clicks[0], clicks[1]);
                         WaypointNode waypoint2 = graph.GetClosestWaypoint(clicks[2], clicks[3]);
                         markerMinion.Pos.X = waypoint1.X + (waypoint2.X - waypoint1.X) / 2;
                         markerMinion.Pos.Y = waypoint1.Y + (waypoint2.Y - waypoint1.Y) / 2;
                _player1.AddMinion(markerMinion);
                graph.ConnectNodes(waypoint1, waypoint2);
                        Console.Write("Added neighbor");
                        break;
                }
                rightClicks++;
                rightClicks = rightClicks % 2;
                graph.WriteGraph("TestWaypointNeighbors.xml");
            }

            _scrollBar.Update(e.Time);
            #else

            _map.Update(e.Time);

            _ui.Update(e.Time);

            #endif
            }

            private void Mouse_Move(object sender, MouseMoveEventArgs e)
            {
            MousePosition = e.Position;
            }
            }
        }
Esempio n. 54
0
        private static DayPeriodRuleSet[] GetDayPeriodRuleSets()
        {
            if (options != null && !options.IncludeDayPeriodRuleSets)
            {
                return(null);
            }

            XDocument document = GetXmlDocument(@"common\supplemental\dayPeriods.xml");

            IEnumerable <XElement> ldmlElements          = document.Elements("supplementalData");
            List <XElement>        dayPeriodRuleSetDatas = (from item in ldmlElements.Elements("dayPeriodRuleSet")
                                                            .Elements("dayPeriodRules")
                                                            select item).ToList();

            if (dayPeriodRuleSetDatas != null && dayPeriodRuleSetDatas.Count > 0)
            {
                List <DayPeriodRuleSet> dayPeriodRuleSets = new List <DayPeriodRuleSet>();
                foreach (XElement data in dayPeriodRuleSetDatas)
                {
                    string locales = data.Attribute("locales").Value.ToString();
                    Progress("Adding day period", locales);

                    DayPeriodRuleSet dayPeriodRuleSet = new DayPeriodRuleSet();
                    dayPeriodRuleSet.CultureNames = locales.Split(' ');

                    List <DayPeriodRule> dayPeriodRules     = new List <DayPeriodRule>();
                    List <XElement>      dayPeriodRuleDatas = data.Elements("dayPeriodRule").ToList();
                    foreach (XElement dayPeriodRuleData in dayPeriodRuleDatas)
                    {
                        DayPeriodRule dayPeriodRule = new DayPeriodRule();
                        dayPeriodRule.Id = dayPeriodRuleData.Attribute("type").Value.ToString();

                        if (dayPeriodRuleData.Attribute("from") != null)
                        {
                            dayPeriodRule.From = dayPeriodRuleData.Attribute("from").Value.ToString();
                        }

                        if (dayPeriodRuleData.Attribute("at") != null)
                        {
                            dayPeriodRule.At = dayPeriodRuleData.Attribute("at").Value.ToString();
                        }

                        if (dayPeriodRuleData.Attribute("after") != null)
                        {
                            dayPeriodRule.After = dayPeriodRuleData.Attribute("after").Value.ToString();
                        }

                        if (dayPeriodRuleData.Attribute("before") != null)
                        {
                            dayPeriodRule.Before = dayPeriodRuleData.Attribute("before").Value.ToString();
                        }

                        if (dayPeriodRuleData.Attribute("to") != null)
                        {
                            dayPeriodRule.To = dayPeriodRuleData.Attribute("to").Value.ToString();
                        }

                        dayPeriodRules.Add(dayPeriodRule);
                    }

                    dayPeriodRuleSet.DayPeriodRules = dayPeriodRules.ToArray();

                    dayPeriodRuleSets.Add(dayPeriodRuleSet);
                    Progress("Added day period", locales, ProgressEventType.Added, dayPeriodRuleSet);
                }

                return(dayPeriodRuleSets.ToArray());
            }

            return(null);
        }
Esempio n. 55
0
 public void SameDocumentDefaultNamespaceSameNameElements()
 {
     XDocument xDoc = new XDocument(new XElement("Name", new XElement("Name")));
     Assert.Same(
         (xDoc.Nodes().First() as XElement).Name.Namespace,
         (xDoc.Nodes().Last() as XElement).Name.Namespace);
     Assert.Same((xDoc.Nodes().First() as XElement).Name, (xDoc.Nodes().Last() as XElement).Name);
 }
Esempio n. 56
0
 public void Parse(XDocument xml, AbstractSolrQueryResults <T> results)
 {
     results.Switch(query: r => Parse(xml, r),
                    moreLikeThis: F.DoNothing);
 }
Esempio n. 57
0
 public static void NodesOnXDocBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText, bText);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XNode> nodes = xDoc.Nodes();
     Assert.Equal(1, nodes.Count());
     a.Remove();
     Assert.Equal(0, nodes.Count());
 }
Esempio n. 58
0
        void Auto(string[] args)
        {
            Logger.ConsoleExceptions = true;

            var serverName = Prompt("Server");
            var defaultPath = $@"\\{serverName}\c$\inetpub\logs\LogFiles";
            string path;
            do
            {
                path = Prompt($"Path ({defaultPath})", v => true).NullIfEmpty() ?? defaultPath;
                if (Directory.Exists(path))
                    break;
                Console.WriteLine($"  [{path}] is not a valid path!");
            } while (true);

            var redirectionDoc = XDocument.Load($@"\\{serverName}\c$\windows\system32\inetsrv\config\redirection.config");
            Console.WriteLine("redirection.config loaded: " + (redirectionDoc != null));
            var redNote = redirectionDoc.Root.Element("configurationRedirection");
            var configPath = string.Equals(redNote?.Attribute("enabled")?.Value, "true", StringComparison.OrdinalIgnoreCase)
                ? redNote.Attribute("path").Value
                : $@"\\{serverName}\c$\windows\system32\inetsrv\config";
            Console.WriteLine("Config path: " + configPath);

            var sites = XDocument.Load(Path.Combine(configPath, "applicationHost.config"))
                .Root
                .Element("system.applicationHost")
                .Element("sites")
                .Elements("site");

            var siteBindings = sites
                .ToDictionary(
                    e => e.Attribute("id").Value, 
                    e => new
                    {
                        Name = e.Attribute("name").Value,
                        DefaultHost = e.Element("bindings")
                            .Elements("binding")
                            .Select(be => be.Attribute("bindingInformation").Value)
                            .Select(bi => bi.Split(':').Last())
                            .GroupBy(bi => bi.ToLower())
                            .OrderByDescending(g => g.Count())
                            .First()
                            .Key,
                    });
            foreach (var binding in siteBindings)
                Console.WriteLine($"Found site: {binding.Key}: {binding.Value.Name}");

            var ftpSites = Directory.GetDirectories(path, "FTPSVC*")
                .Select(ftpPath =>
                {
                    var id = Path.GetFileName(ftpPath).Substring("FTPSVC".Length);
                    if (!siteBindings.ContainsKey(id))
                    {
                        Console.WriteLine($"  [{id}]: Unknown FTP site!");
                        return null;
                    }
                    return new
                    {
                        id = id,
                        path = ftpPath,
                        siteName = siteBindings[id].Name,
                    };
                })
                .Where(s => s != null)
                .ToArray();
            var w3Sites = Directory.GetDirectories(path, "W3SVC*")
                .Select(w3Path =>
                {
                    var id = Path.GetFileName(w3Path).Substring("W3SVC".Length);
                    if (!siteBindings.ContainsKey(id))
                    {
                        Console.WriteLine($"  [{id}]: Unknown W3 site!");
                        return null;
                    }
                    //var defaultHost = Prompt($"Host for {siteBindings[id]} ({id})", v => true);
                    return new
                    {
                        id = id,
                        path = w3Path,
                        siteName = siteBindings[id].Name,
                        defaultHost = siteBindings[id].DefaultHost,
                    };
                })
                .Where(s => s != null)
                .ToArray();

            Console.WriteLine();
            Console.WriteLine("FTP Sites: " + ftpSites.Length);
            Console.WriteLine("W3 Sites: " + w3Sites.Length);
            if (ftpSites.Length == 0 && w3Sites.Length == 0)
            {
                Console.WriteLine("  No sites found!");
                return;
            }

            var proceed = Prompt("Proceed (y|n)", v => v.ToLower() == "y" || v.ToLower() == "n");
            if (!proceed.Equals("y"))
                return;

            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
            Console.WriteLine(connectionString);
            var sw = Stopwatch.StartNew();
            foreach (var site in ftpSites)
            {
                ProcessLogs<FtpLogItem>(serverName, site.siteName, null, connectionString, "flexlabs.IIS_FtpLogs", Directory.GetFiles(site.path, "*.log"));
            }

            foreach (var site in w3Sites)
            {
                ProcessLogs<W3LogItem>(serverName, site.siteName, site.defaultHost, connectionString, "flexlabs.IIS_WebLogs", Directory.GetFiles(site.path, "*.log"));
            }

            sw.Stop();
            Console.WriteLine($"Uploaded in {sw.Elapsed}");
            Console.WriteLine($"Processed {totalCounter.ToString("N0")} logs at {(totalCounter / sw.Elapsed.TotalSeconds).ToString("N2")} logs/sec");
        }
Esempio n. 59
0
 public static void DescendantsWithXNameOnXDocBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     b.Add(b, b); a.Add(b);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XElement> nodes = xDoc.Descendants("B");
     Assert.Equal(4, nodes.Count());
     b.Remove();
     Assert.Equal(0, nodes.Count());
 }
 public XmlWorker()
 {
     _document = new XDocument();
 }