public static SettingsBase ParseDocument(XDocument document)
        {
            SettingsBase settings = new SettingsBase();

            foreach (XElement element in document.Descendants("Parameter"))
            {
                Parameter parameter = new Parameter()
                {
                    Name = element.Attribute("Name").GetValue(),
                    Value = element.Attribute("Value").GetValue()
                };

                settings.Parameters.Add(parameter);
            }

            foreach (XElement element in document.Descendants("DataSource"))
            {
                Source source = new Source();
                source.Name = element.Attribute("Name").GetValue();
                source.Url = element.Attribute("Url").GetValueAsUri();

                TimeSpan? interval = element.Attribute("Interval").GetValueAsTimeSpan();
                source.Interval = interval == null ? TimeSpan.MaxValue : interval.Value;

                settings.DataSources.Add(source);
            }

            return settings;
        }
예제 #2
0
        public XDocument Modify(XDocument document)
        {
            var elementsWithHref = document.Descendants()
                .Where(e => e.Name.LocalName == "a" || e.Name.LocalName == "link");
            var elementsWithSrc = document.Descendants()
                .Where(e => e.Name.LocalName == "img" || e.Name.LocalName == "script");
            var formElementsWithAction = document.Descendants()
                .Where(e => e.Name.LocalName == "form");
            var root = HttpRequest.ApplicationPath.TrimEnd('/');
            
            foreach (var element in elementsWithHref)
            {
                ExpandUrl(element, "href", root);
            }
            foreach (var element in elementsWithSrc)
            {
                ExpandUrl(element, "src", root);
            }
            foreach (var element in formElementsWithAction)
            {
                ExpandUrl(element, "action", root);
            }

            return document;
        }
예제 #3
0
 /// <summary>
 /// Retrieves the Style element. This can either be the Style element contained in <paramref name="element"/> or a styleUrl element contained in <paramref name="element"/>.
 /// </summary>
 /// <param name="element">The element that contains the Style element or the styleUrl.</param>
 /// <param name="doc">The kml document.</param>
 /// <param name="docNamespace">The namespace of the kml document.</param>
 /// <returns></returns>
 public static XElement RetrieveStyleElement(XElement element, XDocument doc, XNamespace docNamespace)
 {
     XElement styleUrl = element.Element(docNamespace + "styleUrl");
     if (styleUrl != null)
     {
         string value = styleUrl.Value.Trim();
         if (value.StartsWith("#"))
         {
             value = value.Substring(1);
             var referredStyle = doc.Descendants().Where(o => o.Name == docNamespace + "Style").Where(o => (string)o.Attribute("id") == value).FirstOrDefault();
             if (referredStyle != null)
             {
                 return referredStyle;
             }
             else
             {
                 referredStyle = doc.Descendants().Where(o => o.Name == docNamespace + "StyleMap").Where(o => (string)o.Attribute("id") == value).FirstOrDefault();
                 if (referredStyle != null)
                 {
                     styleUrl = referredStyle.Elements(docNamespace + "Pair").Where(o => o.Element(docNamespace + "key").Value == "normal").FirstOrDefault();
                     return RetrieveStyleElement(styleUrl, doc, docNamespace);
                 }
             }
         }
     }
     return null;
 }
예제 #4
0
        public static bool GetClassNamesLettersList(XDocument Students, out List<string> ClassList, out List<char> Letters, out List<string[]> Names)
        {
            Letters = new List<char>();
              ClassList = new List<string>();
              Names = new List<string[]>();

              if (Students != null)
            foreach (string Validator in Students.Descendants("ValidStuds"))  //Проверка на валидность файла списка студентов
              if (Validator == "545k#cOFj$qM2LbnEY")
              {
            foreach (string Class in Students.Descendants("name"))
              ClassList.Add(Class);

            foreach (string Letter in Students.Descendants("let"))
              if (Letter != "")
                Letters.Add(Letter[0]);
              else
                Letters.Add(' ');

            foreach (string NameList in Students.Descendants("n"))
              Names.Add(Splitter(NameList));

            return true; //Если не пустой документ, то возвращает труЪ
              }
              return false;
        }
예제 #5
0
 public XmlReviewRepository()
 {
     _dbPath = HttpContext.Current.Server.MapPath ("~/App_LocalResources/Data.xml");
     _database = XDocument.Load (_dbPath);
     var data = _database
         .Descendants ("review")
         .Select (review => new Review () {
             Id = Int32.Parse(review.Element ("id").Value),
             PostId = Int32.Parse(review.Element ("postid").Value),
             Title = review.Element ("title").Value,
             Description = review.Element ("description").Value,
             Date = review.Element ("date").Value,
             CommunityUrl = review.Element ("communityurl").Value,
             CommunutyDiscussionsCount = (Int32.Parse(review.Element ("communutydiscussionscount").Value)),
             Author = review.Element ("author").Value,
             AuthorId = review.Element ("authorid").Value,
             Tags = review.Element ("tags").Value.Split(',')
     })
         .OrderByDescending(review => review.Id)
         .AsQueryable ();
     Reviews = data;
     Tags = _database
         .Descendants ("tags")
         .SelectMany (element => element.Value.Split(','))
         .Distinct ()
         .AsQueryable ();
 }
예제 #6
0
        public List<MedDAL.DAL.bitacora> Buscar(XDocument xmlDoc, int iFiltro, string sCadena) 
        {            
            switch (iFiltro) 
            { 
                case 1:
                    var oQuery = from c in xmlDoc.Descendants("bitacora")
                             where (c.Element("Usuario").Value.ToString().ToUpper().Contains(sCadena.ToUpper()))
                             where (c.Element("Modulo").Value.ToString().ToUpper().Contains(sCadena.ToUpper()))
                             select c;

                    List<MedDAL.DAL.bitacora> lstBitacora = ObtenerBitacoraQuery(oQuery);

                    return lstBitacora;
                case 2:                   
                    oQuery = from c in xmlDoc.Descendants("bitacora")
                             where (c.Element("Usuario").Value.ToString().ToUpper().Contains(sCadena.ToUpper()))                             
                             select c;

                    lstBitacora = ObtenerBitacoraQuery(oQuery);

                    return lstBitacora;                    
                case 3:                    
                    oQuery = from c in xmlDoc.Descendants("bitacora")
                             where (c.Element("Modulo").Value.ToString().ToUpper().Contains(sCadena.ToUpper()))
                             select c;

                    lstBitacora = ObtenerBitacoraQuery(oQuery);
                                            
                    return lstBitacora;
                default:
                    return null;
            }
             
        }
예제 #7
0
        /// <summary>
        /// Instead of logging on feature per control, I do 1 feature per control type along with the number of occurrences
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public static IEnumerable<InfoPathFeature> ParseFeature(XDocument document)
        {
            PublishUrl pubRule = new PublishUrl();
            IEnumerable<XElement> allElements = document.Descendants(xsf3Namespace + baseUrl);
            // collect the control counts
            foreach (XElement element in allElements)
            {
                if (pubRule.RelativeBase != null) throw new ArgumentException("Should only see one xsf3:baseUrl node");
                XAttribute pathAttribute = element.Attribute(relativeUrlBaseAttribute);
                if (pathAttribute != null) // this attribute is technically optional per xsf3 spec
                {
                    pubRule.RelativeBase = pathAttribute.Value;
                }
            }

            allElements = document.Descendants(xsfNamespace + xDocumentClass);
            foreach (XElement element in allElements)
            {
                if (pubRule.Publish != null) throw new ArgumentException("Should only see one xsf:xDocumentClass node");
                XAttribute pubUrl = element.Attribute(publishUrlAttribute);
                if (pubUrl != null)
                {
                    pubRule.Publish = pubUrl.Value;
                }
            }

            yield return pubRule;
            // nothing left
            yield break;
        }
예제 #8
0
        public IEnumerable<Issue> Parse(XDocument report)
        {
            var issuesType = report.Descendants("IssueType");

            foreach (var project in report.Descendants("Project"))
            {
                foreach (var issue in project.Descendants("Issue"))
                {
                    var issueType = GetIssueType(issuesType, issue.Attribute("TypeId").Value);
                    var sourceFilePath = issue.Attribute("File").Value;
                    var offsetAttribute = issue.Attribute("Offset");
                    var lineNumber = GetLine(issue.Attribute("Line"), offsetAttribute != null);

                    yield return new Issue
                    {
                        Project = project.Attribute("Name").Value,
                        Category = issueType.Attribute("Category").Value,
                        Description = issueType.Attribute("Description").Value,
                        FilePath = sourceFilePath,
                        HelpUri = GetUri(issueType.Attribute("WikiUrl")),
                        Line = lineNumber,
                        Message = issue.Attribute("Message").Value,
                        Name = issue.Attribute("TypeId").Value,
                        Severity = GetSeverity(issueType.Attribute("Severity")),
                        Offset = GetOffset(offsetAttribute, sourceFilePath, lineNumber),
                        Source = Name,
                    };
                }
            }
        }
        public static FromClause getFromClause(XDocument xmlDoc)
        {
            List<string> tableSourceList = new List<string>();
            List<string> schemaNameList = new List<string>();
            List<string> tableAliasList = new List<string>();

            IEnumerable<XAttribute> ts = from t in xmlDoc.Descendants("SqlFromClause").Descendants("SqlTableRefExpression").Attributes("ObjectIdentifier") select t;
            foreach (var t in ts)
            {
                tableSourceList.Add(t.Value);
            }

            IEnumerable<XAttribute> tsch = from t in xmlDoc.Descendants("SqlFromClause").Descendants("SqlObjectIdentifier").Attributes("SchemaName") select t;
            foreach (var s in tsch)
            {
                schemaNameList.Add(s.Value);
            }

            IEnumerable<XAttribute> tali = from t in xmlDoc.Descendants("SqlFromClause").Descendants("SqlObjectIdentifier").Attributes("ObjectName") select t;
            foreach (var ta in tali)
            {
                tableAliasList.Add(ta.Value);
            }

            FromClause newFromClause = new FromClause(tableSourceList, schemaNameList, tableAliasList);
            return newFromClause;
        }
예제 #10
0
        void UpdateVs2010Compatibility(XDocument document, string file) {
            var elements = document.Descendants().Where(element 
                => element.Name.LocalName == "VSToolsPath" || element.Name.LocalName == "VisualStudioVersion" );
            var xElements = elements as XElement[] ?? elements.ToArray();
            bool save=xElements.Any();
            xElements.Remove();


            elements=document.Descendants().Where(element 
                => element.Name.LocalName == "Import" &&
                (element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath)")||
                element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath32)")));
            var enumerable = elements as XElement[] ?? elements.ToArray();
            if (!save)
                save = enumerable.Any();

            if (IsWeb(document, GetOutputType(document))&& !document.Descendants().Any(element =>
                element.Name.LocalName == "Import" && element.Attribute("Project").Value.StartsWith("$(VSToolsPath)")&&
                element.Attribute("Condition").Value.StartsWith("'$(VSToolsPath)' != ''"))) {
                var element = new XElement(_xNamespace+"Import");
                element.SetAttributeValue("Project",@"$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets");
                element.SetAttributeValue("Condition", @"'$(VSToolsPath)' != ''");
                Debug.Assert(document.Root != null, "document.Root != null");
                document.Root.Add(element);
                save = true;
            }
            
            enumerable.Remove();

            if (save)
                DocumentHelper.Save(document, file);
        }
예제 #11
0
        public override void GetObjectXML(XDocument sourceDoc)
        {
            XElement eng;

            if (sourceDoc.Descendants("enginePart").Where(f => f.Attribute("name").Value == this.Name).Count() > 0)
            {
                // Update Existing
                eng = sourceDoc.Descendants("enginePart").First(f => f.Attribute("name").Value == this.Name);
                eng.Element("MaxHP").Value = this.HP.Max.ToString();
                if (eng.Element("Mass") != null)
                    eng.Element("Mass").Value = this._mass.ToString();
                else
                    eng.Add(new XElement("Mass", this._mass.ToString()));
                eng.Element("Thrust").Value = this._thrust.ToString();
                addActions(eng.Element("Actions"));
            }
            else
            {
                // Create New
                XElement actions = new XElement("Actions");
                addActions(actions);
                eng =
                    new XElement("enginePart", new XAttribute("name", this.Name),
                        new XElement("MaxHP", this.HP.Max.ToString()),
                        new XElement("Mass",this.Mass.ToString()),
                        new XElement("Thrust", this._thrust.ToString()),
                        actions);
                sourceDoc.Descendants("engineParts").First().Add(eng);
            }
        }
예제 #12
0
        //------------------------------------------------------------------------------------------------
        //DataGridviewにXmlデータを反映する(起動時)
        //------------------------------------------------------------------------------------------------
        public void InitDataSet()
        {
            XElement query;

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);


            //Xmlファイル内を検索
            for (int i = 0; i < XmlDoc.Descendants("Chord").Count(); i++)
            {
                //ServiceNameをチェック
                try
                {
                    query = (from y in XmlDoc.Descendants("Chord")
                             where y.Attribute("ID").Value == Convert.ToString(i + 1)
                             select y).Single();

                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells[0].Value = query.Attribute("ID").Value;
                    dataGridView1.Rows[i].Cells[1].Value = query.Element("Root").Value;
                    dataGridView1.Rows[i].Cells[2].Value = query.Element("Degree").Value;
                    dataGridView1.Rows[i].Cells[3].Value = query.Element("Position1").Value;
                    dataGridView1.Rows[i].Cells[4].Value = query.Element("Position2").Value;
                    dataGridView1.Rows[i].Cells[5].Value = query.Element("Position3").Value;
                    dataGridView1.Rows[i].Cells[6].Value = query.Element("Position4").Value;
                    dataGridView1.Rows[i].Cells[7].Value = query.Element("BarreFlg").Value;
                    dataGridView1.Rows[i].Cells[8].Value = query.Element("Barre").Value;
                    dataGridView1.Rows[i].Cells[9].Value = query.Element("High").Value;
                }
                catch (Exception ex)
                {
                }
            }
        }
예제 #13
0
        public IEnumerable<Issue> Parse(XDocument report)
        {
            var issues = new List<Issue>();
            var issuesType = report.Descendants("IssueType");

            foreach (var project in report.Descendants("Project"))
            {
                foreach (var issue in project.Descendants("Issue"))
                {
                    var issueType = GetIssueType(issuesType, issue.Attribute("TypeId").Value);

                    issues.Add(new Issue
                    {
                        Project = project.Attribute("Name").Value,
                        Category = issueType.Attribute("Category").Value,
                        Description = issueType.Attribute("Description").Value,
                        FilePath = issue.Attribute("File").Value,
                        HelpUri = GetUri(issueType.Attribute("WikiUrl")),
                        Line = GetLine(issue.Attribute("Line")),
                        Message = issue.Attribute("Message").Value,
                        Name = issue.Attribute("TypeId").Value,
                        Severity = GetSeverity(issueType.Attribute("Severity")),
                        Offset = GetOffset(issue.Attribute("Offset")),
                        Source = Name,
                    });
                }
            }
            return issues;
        }
예제 #14
0
        public TVDBSeries(XDocument xml)
        {
            Xml = xml;
            var series = xml.Descendants("Series").Single();

            ID = series.GetInt("id").Value;
            Actors = series.Split("Actors");
            AirsDay = series.GetEnum<DayOfWeek>("Airs_DayOfWeek");
            AirsTime = series.GetDateTime("Airs_Time");
            ContentRating = series.Get("ContentRating");
            FirstAired = series.GetDateTime("FirstAired");
            Genres = series.Split("Genre");
            IMDbID = series.Get("IMDB_ID");
            Language = series.Get("Language");
            Network = series.Get("Network");
            Overview = series.Get("Overview");
            Rating = series.GetDouble("Rating");
            LengthMinutes = series.GetDouble("Runtime");
            TvDotComID = series.Get("SeriesID");
            Name = series.Get("SeriesName");
            Status = series.Get("Status");
            BannerPath = series.Get("banner");
            FanartPath = series.Get("fanart");
            LastUpdated = series.GetUnixDateTime("lastupdated");
            PosterPath = series.Get("poster");
            Zap2ItID = series.Get("zap2it_id");

            Episodes = (
                from ep in xml.Descendants("Episode")
                where ep.HasElements
                select new TVDBEpisode(ep)
            )
            .ToList();
        }
예제 #15
0
        public override void GetObjectXML(XDocument sourceDoc)
        {
            XElement act;

            if (sourceDoc.Descendants("actionPart").Where(f => f.Attribute("name").Value == this.Name).Count() > 0)
            {
                // Update Existing
                act = sourceDoc.Descendants("actionPart").First(f => f.Attribute("name").Value == this.Name);
                act.Element("MaxHP").Value = this.HP.Max.ToString();
                if (act.Element("Mass") != null)
                    act.Element("Mass").Value = this._mass.ToString();
                else
                    act.Add(new XElement("Mass", this._mass.ToString()));
                act.Element("ActionDescription").Value = this._actionDescription.ToString();

                addActions(act.Element("Actions"));
            }
            else
            {
                // Create New
                XElement actions = new XElement("Actions");
                addActions(actions);
                act =
                    new XElement("actionPart", new XAttribute("name", this.Name),
                        new XElement("MaxHP", this.HP.Max.ToString()),
                        new XElement("Mass",this.Mass.ToString()),
                        new XElement("ActionDescription", this._actionDescription.ToString()),
                        actions);
                sourceDoc.Descendants("actionParts").First().Add(act);
            }
        }
예제 #16
0
        public SettingsPage()
        {
            InitializeComponent();

            #if !DEBUG
            _xmlDoc = string.IsNullOrEmpty(_settings.XmlThemes) ? XDocument.Load("Themes.xml") : XDocument.Parse(_settings.XmlThemes);
            #else
            _xmlDoc = XDocument.Load("Themes.xml");
            #endif
            if (_xmlDoc != null)
            {
                if (string.IsNullOrEmpty(_settings.XmlThemes)) _settings.XmlThemes = _xmlDoc.ToString();

                _themeNames = _xmlDoc.Descendants("theme").Attributes("name").Select(a => a.Value).ToList();
                ThemeList.ItemsSource = _themeNames;
                ThemeList.SelectedItem = _startTheme = _settings.ThemeName;

                ThemeList.SelectionChanged += (_, __) =>
                {
                    string name = ThemeList.SelectedItem as string;
                    if (!string.IsNullOrEmpty(name) && _xmlDoc != null && name != _settings.ThemeName)
                    {
                        _settings.ThemeName = name;
                        var node = _xmlDoc.Descendants("theme").Where(d => d.Attribute("name").Value == name).FirstOrDefault();
                        if (node != null) _settings.Theme = node.ToString();
                    }
                };
            }
            bytesUsed.Text = string.Format("Used space: {0}", GetStoreUsedSize().ToSize());
        }
예제 #17
0
        void ExtractArchetypesAndTemplates(ref List <string> listIdArchetypes, ref List <string> listEmbeddedTemplates, string sTemplateXML)
        {
            System.Diagnostics.Contracts.Contract.Requires(!String.IsNullOrEmpty(sTemplateXML));

            if (String.IsNullOrEmpty(sTemplateXML))
            {
                return;
            }

            System.Xml.Linq.XDocument xtemplate = null;
            try
            {
                xtemplate = XDocument.Parse(sTemplateXML);
            }
            catch (Exception e)
            {
                throw e;
            }

            var defs = xtemplate.Descendants().Where(p => p.Name.LocalName == "integrity_checks");

            if (defs != null)
            {
                foreach (XElement def in defs)
                {
                    var archid = def.Attribute("archetype_id");
                    listIdArchetypes.Add(archid.Value);
                }
            }

            var names = xtemplate.Descendants().Where(p => p.Name.LocalName == "name").FirstOrDefault();

            if (names != null)
            {
                Console.WriteLine("Template Name = " + names.Value);
            }

            List <string> sValue = new List <string>();

            xtemplate.Descendants().Where(p => p.Name.LocalName == "Item")
            .ToList()
            .ForEach(e =>
            {
                XAttribute tid = e.Attribute("template_id");
                if (tid != null)
                {
                    Console.WriteLine(tid.Value);
                    string Value = tid.Value;

                    sValue.Add(Value);
                }
                //Console.WriteLine(e);
            });

            foreach (string template in sValue)
            {
                listEmbeddedTemplates.Add(template);
            }
        }
 public static ProcDef getProcDef(XDocument xmlDoc)
 {
     string definition = xmlDoc.Descendants("SqlProcedureDefinition").Attributes("Name").FirstOrDefault().Value;
     string schemaName = xmlDoc.Descendants("SqlProcedureDefinition").Descendants("SqlObjectIdentifier").Attributes("SchemaName").FirstOrDefault().Value;
     string objectName = xmlDoc.Descendants("SqlProcedureDefinition").Descendants("SqlObjectIdentifier").Attributes("ObjectName").FirstOrDefault().Value;
     ProcDef def = new ProcDef(definition, schemaName, objectName);
     return def;
 }
예제 #19
0
파일: Hotel.xaml.cs 프로젝트: DISD/2UG
        private IEnumerable<HotelModel> retrieveXMLData(XDocument xmlFile, String categoryType, String searchByType, String searchByDistrictName, String hotelName)
        {
            String firstXMLNode = categoryType.Substring(0, categoryType.Length - 1).ToLower();
            IEnumerable<HotelModel> data = null;

            if (!searchByType.Equals(""))
            {
                data = from hItem in xmlFile.Descendants(firstXMLNode)
                       where hItem.Element("type").Value.Contains(searchByType.ToLower())
                       select new HotelModel()
                       {
                           name = (string)hItem.Element("name"),
                           address = (string)hItem.Element("address"),
                           Telphone = (string)hItem.Element("telphone"),
                           district = convertFirstElementToUpperCase((string)hItem.Element("district")),
                           type = convertFirstElementToUpperCase((string)hItem.Element("type"))
                       };
            }
            else if (!searchByDistrictName.Equals(""))
            {
                data = from hItem in xmlFile.Descendants(firstXMLNode)
                       where hItem.Element("district").Value.Contains(searchByDistrictName.ToLower())
                       select new HotelModel()
                       {
                           name = (string)hItem.Element("name"),
                           address = (string)hItem.Element("address"),
                           Telphone = (string)hItem.Element("telphone"),
                           district = convertFirstElementToUpperCase((string)hItem.Element("district")),
                           type = convertFirstElementToUpperCase((string)hItem.Element("type"))
                       };
            }
            else if (!hotelName.Equals(""))
            {
                data = from hItem in xmlFile.Descendants(firstXMLNode)
                       where hItem.Element("name").Value.Contains(hotelName.ToUpper())
                       select new HotelModel()
                       {
                           name = (string)hItem.Element("name"),
                           address = (string)hItem.Element("address"),
                           Telphone = (string)hItem.Element("telphone"),
                           district = convertFirstElementToUpperCase((string)hItem.Element("district")),
                           type = convertFirstElementToUpperCase((string)hItem.Element("type"))
                       };
            }
            else
            {
                data = from hItem in xmlFile.Descendants(firstXMLNode)
                       select new HotelModel()
                       {
                           name = (string)hItem.Element("name"),
                           address = (string)hItem.Element("address"),
                           Telphone = (string)hItem.Element("telphone"),
                           district = convertFirstElementToUpperCase((string)hItem.Element("district")),
                           type = convertFirstElementToUpperCase((string)hItem.Element("type"))
                       };
            }
            return data;
        }
예제 #20
0
        public void ProcessRequest(HttpContext context)
        {
            _context = context;
            _req = context.Request;
            _res = context.Response;
            xd = XDocument.Load(_context.Server.MapPath("~/IlIlce.xml"));

            if (_req.QueryString.Count == 0)
            {
                context.Response.ContentType = "text/javascript";

                _res.Write("[");
                var a = false;
                foreach (var item in xd.Descendants("Il"))
                {
                    if (a)
                    {
                        _res.Write(",\n");
                    }
                    else
                    {
                        a = !a;
                    }
                    _res.Write(
                        string.Format(
                            "{{ \"PlakaKodu\":{0}, \"IlAdi\":\"{1}\" }}",
                        item.Attribute("PlakaKodu").Value,
                        item.Attribute("Adi").Value));
                }
                _res.Write("]");
            }
            else
            {
                context.Response.ContentType = "text/javascript";
                var pk = _req.QueryString["pk"];

                _res.Write("[");
                var a = false;
                var il = xd.Descendants("Il").FirstOrDefault(x => x.Attribute("PlakaKodu").Value == pk);
                foreach (var item in il.Descendants("Ilce"))
                {
                    if (a)
                    {
                        _res.Write(",\n");
                    }
                    else
                    {
                        a = !a;
                    }
                    _res.Write(
                        string.Format(
                            "{{ \"IlceAdi\":\"{0}\" }}",
                        item.Attribute("Adi").Value));
                }
                _res.Write("]");
            }
        }
예제 #21
0
        internal static Author ParseAuthorInfoResults(XDocument response)
        {
            var author = (from a in response.Descendants("author")
                         select ParseAuthor(a)).FirstOrDefault();

            author.Books.AddRange(from books in response.Descendants("books")
                                  select ParseBookInfo(books.Element("book")));

            return author;
        }
예제 #22
0
        /// <summary>
        /// Validates project and namespace names against conflicts with Bridge.NET namespaces.
        /// </summary>
        /// <param name="doc">XDocument reference of the .csproj file.</param>
        private void ValidateProject(XDocument doc)
        {
            var valid = true;
            var failList = new HashSet<string>();
            var failNodeList = new List<XElement>();
            var combined_tags = from x in doc.Descendants()
                                where x.Name.LocalName == "RootNamespace" || x.Name.LocalName == "AssemblyName"
                                select x;

            // Replace '\' with '/' in any occurrence of <OutputPath><path></OutputPath>
            foreach (var ope in doc.Descendants().Where(e => e.Name.LocalName == "OutputPath" && e.Value.Contains("\\")))
            {
                ope.SetValue(ope.Value.Replace("\\", "/"));
            }

            // Replace now for <Compile Include="<path>" />
            foreach (var ope in doc.Descendants().Where(e =>
                e.Name.LocalName == "Compile" &&
                e.Attributes().Any(a => a.Name.LocalName == "Include") &&
                e.Attribute("Include").Value.Contains("\\")))
            {
                var incAtt = ope.Attribute("Include");
                incAtt.SetValue(incAtt.Value.Replace("\\", "/"));
            }

            foreach (var tag in combined_tags)
            {
                if (tag.Value == "Bridge")
                {
                    valid = false;
                    if (!failList.Contains(tag.Value))
                    {
                        failList.Add(tag.Value);
                        failNodeList.Add(tag);
                    }
                }
            }

            if (!valid)
            {
                var offendingSettings = "";
                foreach (var tag in failNodeList)
                {
                    offendingSettings += "Line " + ((IXmlLineInfo)tag).LineNumber + ": <" + tag.Name.LocalName + ">" +
                        tag.Value + "</" + tag.Name.LocalName + ">\n";
                }

                throw new Bridge.Translator.Exception("'Bridge' name is reserved and may not " +
                    "be used as project names or root namespaces.\n" +
                    "Please verify your project settings and rename where it applies.\n" +
                    "Project file: " + this.Location + "\n" +
                    "Offending settings:\n" + offendingSettings
                );
            }
        }
예제 #23
0
    private void GetWeather(string city, int numOfDays)
    {
        lblError.Text = "";
        btnChange.Text = "Change to European values";
        string url = string.Format
("http://api.worldweatheronline.com/free/v1/weather.ashx?q={0}&format=xml&num_of_days={1}&key=ca5fa4c5fca7f7d61ee60affa4b151468ca63572", city, numOfDays);

        WebClient client = new WebClient();

        XmlDocument doc = new XmlDocument();
        doc.Load(url);
        xdoc = XDocument.Load(url);

        try
        {
            currentCondition = xdoc.Descendants("current_condition").First();
        }
        catch (Exception)
        {
            
            lblError.Text = "Oops there is no such city or I couldn't find forecast for it!";
            return;
        }
        

        xElements =  currentCondition.Elements().ToArray();
        XElement chosenCity = xdoc.Descendants("query").First();
        lblCity.Text = "Current condition for " + chosenCity.Value;
        lblCity0.Text = "Forecast for tomorrow for " + chosenCity.Value;
        lblCity1.Text = "Forecast in two days for " + chosenCity.Value;
        lblObservationTime.Text = "Observation Time: " + xElements[0].Value;
        lblTemperature.Text = "Maximum Temperature: " + xElements[2].Value + "F";
        lblWindSpeed.Text = "Wind Speed: " + xElements[6].Value + "MPH";
        lblHumidity.Text = "Humidity: " + xElements[11].Value;
        lblVisibility.Text = "Visibility: " + xElements[12].Value;

        IEnumerable<XElement> dailyForecasts = from item in xdoc.Descendants("weather")
                                               select item;


        var elementsForNextDays = dailyForecasts.ToArray();
        xEls = elementsForNextDays[0].Elements().ToArray();

        lblObservationTime0.Text = "Observation Time: " + xEls[0].Value;
        lblTemperature0.Text = "Maximum Temperature: " + xEls[2].Value + "F";
        lblWindSpeed0.Text = "Wind Speed: " + xEls[5].Value + "MPH";

        var xElsss = elementsForNextDays[1].Elements().ToArray();

        lblObservationTime1.Text = "Observation Time: " + xElsss[0].Value;
        lblTemperature1.Text = "Maximum Temperature: " + xElsss[2].Value + "F";
        lblWindSpeed1.Text = "Wind Speed: " + xElsss[5].Value + "MPH";

        btnChange.Visible = true;
    }
        private string GetMetadata(XDocument xroot, string field)
        {
            if (!xroot.Descendants(field).Any())
                return "";

            var elm = xroot.Descendants(field).FirstOrDefault();
            if (elm == null)
                return "";

            return elm.Value;
        }
예제 #25
0
 private IEnumerable<string> GetClideComponents(XDocument doc)
 {
     return doc
         .Descendants("{http://schemas.microsoft.com/developer/vsx-schema/2010}CustomExtension")
         .Where(element => element.Attribute("Type").Value == "ClideComponent")
         .Select(element => element.Value)
         .Concat(doc
             .Descendants("{http://schemas.microsoft.com/developer/vsx-schema/2011}Asset")
             .Where(element => element.Attribute("Type").Value == "ClideComponent")
             .Select(element => element.Attribute("Path").Value));
 }
예제 #26
0
 /// <summary>
 /// Gets an array of text values of an element from the given response.
 /// </summary>
 /// </summary>
 /// <param name="elementName">The element name to find.</param>
 /// <returns>An array of string values.</returns>
 public string[] GetElementArray(string elementName, string attributeName)
 {
     System.Xml.Linq.XDocument doc = GetXDocument();
     if (string.IsNullOrEmpty(elementName) || elementName == "*")
     {
         return(doc.Descendants().Attributes(attributeName).Select(a => a.Value).ToArray());
     }
     else
     {
         return(doc.Descendants(elementName).Attributes(attributeName).Select(a => a.Value).ToArray());
     }
 }
예제 #27
0
        private static IEnumerable<XAttribute> GetLinkContainingAttributes(XDocument document)
        {
            var hrefAttributes = document.Descendants()
                .Where(e => e.Name.LocalName == "a")
                .Select(a => a.Attribute(HrefAttributeName));

            var actionAttributes = document.Descendants()
                .Where(e => e.Name.LocalName == "form")
                .Select(a => a.Attribute(ActionAttributeName));

            return hrefAttributes.Concat(actionAttributes).Where(a => a != null);
        }
예제 #28
0
 /// <summary>
 /// Gets an attribute value from the given response.
 /// </summary>
 /// <param name="response">The response from Flickr, containing the XML returned.</param>
 /// <param name="element">The element name to find.</param>
 /// <param name="attribute">The attribute of the element to return.</param>
 /// <returns>The string value of the given attribute, if found.</returns>
 public string GetAttributeValue(string element, string attribute)
 {
     System.Xml.Linq.XDocument doc = GetXDocument();
     if (string.IsNullOrEmpty(element) || element == "*")
     {
         return(doc.Descendants().Attributes(attribute).First().Value);
     }
     else
     {
         return(doc.Descendants(element).Attributes(attribute).First().Value);
     }
 }
예제 #29
0
 public static bool ClassParse(XDocument Lessons, out string[] ClassIds)
 {
     ClassIds = new string[0]; //Лист классов
       if (Lessons != null)
     foreach (string Validator in Lessons.Descendants("ValidLess"))
       if (Validator == "545k#cOFj$qM2LbnEY")
       {
     foreach (string ClassNum in Lessons.Descendants("Class")) //Считывание списка классов
       ClassIds = HelpDeriver(ClassNum);
     return true;
       }
       return false;
 }
예제 #30
0
		public static IntacctServiceResponse Parse(XDocument doc, ICollection<IIntacctOperation> operations)
		{
			var control = doc.Descendants("control");
			var success = control.Elements("status").Single().Value == "success";

			if (! success) return ParseErrorsIntoResponse(doc.Descendants("errormessage").First());

			var response = IntacctServiceResponse.Successful;

			ParseOperations(response, operations, doc.Descendants("operation"));

			return response;
		}
예제 #31
0
        public static IEnumerable<InfoPathFeature> ParseFeature(XDocument document)
        {
            Mode m = new Mode();
            string mode = null;

            // look for fancy new modes first (these were new for xsf3 / IP2010)
            IEnumerable<XElement> allModeElements = document.Descendants(xsf3Namespace + solutionMode);
            foreach (XElement element in allModeElements)
            {
                if (mode != null) throw new ArgumentException("Found more than one mode!");
                XAttribute name = element.Attribute(modeAttribute);
                mode = name.Value;
            }

            // and if we didn't find the above, fall back to client v server in xsf2:solutionDefinition
            if (mode == null)
            {
                IEnumerable<XElement> allSolutionDefs = document.Descendants(xsf2Namespace + solutionDefinition);
                foreach (XElement solutionDef in allSolutionDefs)
                {
                    if (mode != null) throw new ArgumentException("Found more than one xsf2:solutionDefition!");
                    XElement extension = solutionDef.Element(xsf2Namespace + solutionPropertiesExtension);
                    if (extension != null && extension.Attribute(branchAttribute) != null && extension.Attribute(branchAttribute).Equals("contentType"))
                    {
                        mode = "Document Information Panel";
                    }
                    else
                    {
                        XAttribute compat = solutionDef.Attribute(runtimeCompatibilityAttribute);
                        mode = compat.Value;
                    }
                }
            }

            // and if we still found nothing, it's a 2003 form and must be client:
            if (mode == null)
                mode = "client";

            m.ModeName = mode;

            string compatibility = null;
            foreach (XElement xDoc in document.Descendants(xsfNamespace + xDocumentClass))
            {
                if (compatibility != null) throw new ArgumentException("Multiple xDocumentClass nodes found!");
                compatibility = xDoc.Attribute(solutionFormatVersionAttribute).Value;
            }
            m.Compatibility = compatibility;

            yield return m;
            yield break;
        }
        //パッケージ文書を更新する
        public static void UpdatePackageDocument(string packFile)
        {
            var doc = new XDocument();

            //opfファイルを読み込む
            try
            {
                doc = XDocument.Load(packFile);
            }
            catch (Exception ex)
            {
                throw(new Exception("パッケージ文書を読み込めませんでした"+ex.ToString()));
            }

            //Epub3であればlastmodifiedを書き換える
            var packNode = doc.Descendants().Where(e => (e.Name.LocalName == "package")&&(e.Name.Namespace==NS_PACKAGE)).FirstOrDefault();
            if (packNode == null)   //パッケージ文書が存在しなければ
            {
                throw (new Exception("パッケージ文書にpackage要素がありません"));
            }
            if (packNode.Attribute("version") == null)  //version属性がないなら
            {
                throw (new Exception("パッケージ文書にEPUBバージョンがありません"));
            }
            var epubVer = packNode.Attribute("version").Value;
            if (epubVer.Equals("3.0"))  //EPUB3ならmodified属性を上書きする
            {
                try
                {
                    var lastModifiedNode 
                        = doc.Descendants()
                        .Where(e => e.Name.LocalName == "meta")                                         //metaタグで
                        .Where(e=>e.Attribute("property").Value=="dcterms:modified").First();           //属性がmodified
                    var utc = DateTime.UtcNow;                          //協定世界時を取得
                    lastModifiedNode.Value = (utc.ToString("s") + 'Z'); //YYYY-MM-DDThh:mm:ssZ
                }
                catch (Exception ex)
                {
                    throw (new Exception("パッケージ文書にmodifiedが存在しません"+ex.ToString()));
                }
                try
                {
                    doc.Save(packFile);
                }
                catch(Exception ex)
                {
                    throw(new Exception("パッケージ文書の上書きに失敗しました"+ex.ToString()));
                }
            }
        }
예제 #33
0
        private static void ExtractData(XDocument cli)
        {
            XElement summ = cli.Descendants("Summary").FirstOrDefault();
            if (summ == null)
            {
                Console.WriteLine("Summary element not found");
            }

            //Console.WriteLine(ExtractSummary(summ));
            writer.WriteLine(ExtractSummaryHdr());
            writer.WriteLine(ExtractSummary(summ));
            XElement propfiles = cli.Descendants("PropertyFiles").FirstOrDefault();
               // Console.WriteLine("Properties {0}", propfiles.Descendants("PropertyFile").Count());
            foreach (XElement prop in propfiles.Descendants("PropertyFile").Descendants("Property"))
            {
                //Console.WriteLine(ExtractPropertyInfo(prop));
                writer.WriteLine(ExtractPropertyInfoHdr());
                writer.WriteLine(ExtractPropertyInfo(prop));

            }
            foreach (XElement lease in propfiles.Descendants("LeaseFile"))
            {
                //Console.WriteLine(ExtractLeaseInfo(lease));
                writer.WriteLine(ExtractLeaseInfoHdr());
                writer.WriteLine(ExtractLeaseInfo(lease));

                if (lease.Descendants("FileTransactions").Count() > 0)
                    writer.WriteLine(ExtractFtransHdr(lease));

                FileTransactions fTrans = new FileTransactions();
                fTrans.GetIdValues(lease);
                if (fTrans != null && fTrans.IdValues.Count > 0)
                {
                    foreach (var x in fTrans.IdValues)
                    {
                        writer.WriteLine(ExtractFtrans(fTrans,x.Key));
                    }
                }

                if (lease.Descendants("Tenants").Count() > 0)
                    writer.WriteLine(ExtractTenantInfoHdr());

                foreach (XElement tenant in lease.Descendants("Tenants"))
                {
                    //Console.WriteLine(ExtractTenantInfo(tenant));
                    writer.WriteLine(ExtractTenantInfo(tenant));
                }
            }
        }
예제 #34
0
 //Возвращает список текстов класса если DataType = text и дат если date
 public static List<string> DelParse(XDocument Lessons, string Class, string LessonType, string DataType)
 {
     List<string> Data = new List<string>();
       foreach (string Text in Lessons.Descendants(Class).Elements(LessonType).Elements(DataType)) //Можно получить Class и lesson
     Data.Add(TextDeriver(Text));  //Мы получаем одну строку, поэтому однострочный дерайвер
       return Data;
 }
예제 #35
0
        //------------------------------------------------------------------------------------------------
        //Xmlデータを初期化する
        //------------------------------------------------------------------------------------------------
        public void XmlAllDelete()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            //Xmlファイル内を検索
            //ぜんぶけす
            try
            {
                var query = from y in XmlDoc.Descendants("Chord")
                            select y;

                foreach (XElement item in query.ToList())
                {
                    item.Remove();
                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
            }
            catch (Exception ex)
            {
            }

            MessageBox.Show("更新が完了しました。",
                            "Infomation", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }
예제 #36
0
    public void Update(string fileName, MathRule mathRule)
    {
        System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
        var node = (from t in document.Descendants("Column")
                    where t.Element("DataBase").Value == mathRule.ColumnInDB
                    select t).FirstOrDefault();

        // check exist element excel
        string[]      arr  = node.Element("Excel").Value.Split(';');
        List <string> list = new List <string>();

        for (int i = 0; i < arr.Length; i++)
        {
            list.Add(arr[i].Trim());
        }
        if (!list.Contains(mathRule.ColumnInExcel.Trim()))
        {
            node.Element("Excel").Value += ";" + mathRule.ColumnInExcel;
        }
        // end check
        //node.Attribute("AllowBlank").Value = mathRule.AllowBlank;
        //node.Attribute("DataType").Value = mathRule.DataType;
        //node.Attribute("DisplayOnGrid").Value = mathRule.DisplayOnGrid.ToString();
        //if (!string.IsNullOrEmpty(mathRule.DefaultValue))
        //    node.Attribute("DefaultValue").Value = mathRule.DefaultValue;
        //else
        //    node.Attribute("DefaultValue").Value = "";
        document.Save(fileName);
    }
        private async void setimg()
        {
            try
            {
                System.Xml.Linq.XDocument xmlDoc  = XDocument.Load("http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US");
                IEnumerable <string>      strTest = from node in xmlDoc.Descendants("url") select node.Value;
                string strURL       = "http://www.bing.com" + strTest.First();
                Uri    source       = new Uri(strURL);
                var    bitmapImage  = new BitmapImage();
                var    httpClient   = new HttpClient();
                var    httpResponse = await httpClient.GetAsync(source);

                byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();

                using (var stream = new InMemoryRandomAccessStream())
                {
                    using (DataWriter dw = new DataWriter(stream))
                    {
                        dw.WriteBytes(b);
                        await dw.StoreAsync();

                        stream.Seek(0);
                        bitmapImage.SetSource(stream);
                        Image1.Source = bitmapImage;
                        var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("CGPA_Bing.jpg", CreationCollisionOption.ReplaceExisting);

                        using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
                        }
                    }
                }
            }
            catch (Exception) { readimg(); }
        }
예제 #38
0
        public void UpdateTuDien(string fileName, MathRule mathRule)
        {
            System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
            var node = (from t in document.Descendants("Column")
                        where t.Element("DataBase").Value == mathRule.ColumnInDB
                        select t).FirstOrDefault();

            node.Element("Excel").Value = mathRule.ColumnInExcel;
            document.Save(fileName);
        }
예제 #39
0
        //------------------------------------------------------------------------------------------------
        //新規登録フォームのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void NewDataAdd()
        {
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database());

            //Xmlファイルに書き込み
            Root      = textBox1_Root.Text;
            Degree    = textBox1_degree.Text;;
            Position1 = textBox_position1.Text;
            Position2 = textBox3_position2.Text;
            Position3 = textBox2_position3.Text;
            Position4 = textBox5_position4.Text;
            BarreFlg  = textBox6_barreflg.Text;
            Barre     = textBox7_barre.Text;
            High      = textBox8_high.Text;

            try
            {
                var query = (from y in XmlDoc.Descendants("Chord")
                             select y);

                int Count = query.Elements("Chord").Count();

                var writeXml = new XElement("Chord",
                                            new XAttribute("ID", Count + 1),
                                            new XElement("Root", Root),
                                            new XElement("Degree", Degree),
                                            new XElement("Position1", Position1),
                                            new XElement("Position2", Position2),
                                            new XElement("Position3", Position3),
                                            new XElement("Position4", Position4),
                                            new XElement("BarreFlg", BarreFlg),
                                            new XElement("Barre", Barre),
                                            new XElement("High", High));

                XmlDoc.Elements().First().Add(writeXml);
                XmlDoc.Save(createConfigXML.CurrentPath_database());
            }
            catch (Exception ex)
            {
            }
        }
예제 #40
0
        public List <MathRule> GetAll(System.Xml.Linq.XDocument document)
        {
            var rs = from t in document.Descendants("Column")
                     select new MathRule
            {
                ColumnInDB       = t.Element("DataBase").Value,
                ColumnInSoftware = t.Element("Software").Value,
                ColumnInExcel    = t.Element("Excel").Value,
                AllowBlank       = t.Attribute("AllowBlank").Value,
                DataType         = t.Attribute("DataType").Value,
                DisplayOnGrid    = bool.Parse(t.Attribute("DisplayOnGrid").Value),
                DefaultValue     = t.Attribute("DefaultValue").Value
            };

            return(rs.ToList());
        }
예제 #41
0
        //------------------------------------------------------------------------------------------------
        //Xml内のデータを整理する(すっからかんのデータを消す)
        //------------------------------------------------------------------------------------------------
        public void SortXml()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            var query = from y in XmlDoc.Descendants("Chord")
                        select y;
            int itemCount = 1;

            foreach (XElement item in query.ToList())
            {
                //すっからかんのデータは消す
                try
                {
                    if (item.Element("Root").Value == "" &&
                        item.Element("Degree").Value == "" &&
                        item.Element("Position1").Value == "" &&
                        item.Element("Position2").Value == "" &&
                        item.Element("Position3").Value == "" &&
                        item.Element("Position4").Value == "" &&
                        item.Element("BarreFlg").Value == "" &&
                        item.Element("Barre").Value == "" &&
                        item.Element("High").Value == "")
                    {
                        item.Remove();
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                    }
                }
                catch (Exception ex)
                {
                }
            }

            //IDの値を並べなおし
            try
            {
                foreach (XElement item in query.ToList())
                {
                    item.Attribute("ID").Value = Convert.ToString(itemCount);
                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                    itemCount++;
                }
            }
            catch (Exception ex)
            {
            }
        }
예제 #42
0
        public MathRule GetByColumnName(System.Xml.Linq.XDocument document, string ColumnInDB)
        {
            var rs = from t in document.Descendants("Column")
                     where t.Element("DataBase").Value == ColumnInDB
                     select new MathRule
            {
                ColumnInDB       = t.Element("DataBase").Value.ToString(),
                ColumnInSoftware = t.Element("Software").Value.ToString(),
                ColumnInExcel    = t.Element("Excel").Value.ToString(),
                AllowBlank       = t.Attribute("AllowBlank").Value,
                DataType         = t.Attribute("DataType").Value,
                DisplayOnGrid    = bool.Parse(t.Attribute("DisplayOnGrid").Value),
                DefaultValue     = t.Attribute("DefaultValue").Value
            };

            return(rs.FirstOrDefault());
        }
예제 #43
0
        public List <Feed> getBlogs(System.Xml.Linq.XDocument xmlFeed)
        {
            List <Feed> results = new List <Feed>();
            XNamespace  xmlns   = "http://www.w3.org/2005/Atom";

            var tmpresults = from item in xmlFeed.Descendants(xmlns + "entry")
                             select new Feed
            {
                Title       = item.Element(xmlns + "title").Value,
                PublishDate = item.Element(xmlns + "published").Value,
                Url         = (from l in item.Elements(xmlns + "link")
                               where l.Attribute("rel").Value == "alternate"
                               select l.Attribute("href").Value).First(),
                Content    = item.Element(xmlns + "content").Value,
                Categories = from c in item.Elements(xmlns + "category")
                             select c.Attribute("term").Value
            };

            results = tmpresults.ToList();

            return(results);
        }
예제 #44
0
        public void ReadFile()
        {
            try
            {
                //Load xml
                System.Xml.Linq.XDocument xdoc = XDocument.Load(@"C:\Users\gabriel\Desktop\SmartHome - Datas\ecole\capteurs.xtim");

                xdoc.Descendants("capteur").Where(p => p.Element("box").Value.Equals("netatmo")).Select(
                    p => new
                {
                    id          = p.Element("id").Value,
                    description = p.Element("description").Value,
                    nom         = p.Element("grandeur").Attribute("nom").Value,

                    unite = p.Element("grandeur").Attribute("unite").Value,

                    abreviation = p.Element("grandeur").Attribute("abreviation").Value,


                    box  = p.Element("box").Value,
                    lieu = p.Element("lieu").Value
                }).ToList().ForEach(p =>
                {
                    Capteur capt = new Capteur(p.id, p.description, p.nom, p.unite, p.abreviation, p.box, p.lieu);
                    listCapteur.AddLast(capt);
                    LinkedList <Detail> liste = ReadFileDetail(p.id);
                    if (liste.Count == 0 || liste == null)
                    {
                        capt.listeDetail = liste;
                    }
                });
                ;
            }
            catch (Exception e)
            {
                Console.WriteLine("the error is " + e.Message);
                Console.ReadLine();
            }
        }
예제 #45
0
        public void Update(string fileName, MathRule mathRule)
        {
            System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(fileName);
            var node = (from t in document.Descendants("Column")
                        where t.Element("DataBase").Value == mathRule.ColumnInDB
                        select t).FirstOrDefault();

            // check exist element excel
            string[]      arr  = node.Element("Excel").Value.Split(';');
            List <string> list = new List <string>();

            for (int i = 0; i < arr.Length; i++)
            {
                list.Add(arr[i].Trim());
            }

            if (!list.Contains(mathRule.ColumnInExcel.Trim()))
            {
                node.Element("Excel").Value += ";" + mathRule.ColumnInExcel;
            }

            document.Save(fileName);
        }
예제 #46
0
        protected override void Seed(CAFE.DAL.DbContexts.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            try
            {
                var permanentUserName = WebConfigurationManager.AppSettings["PermanentUserName"];
                var users             = new List <DbUser>
                {
                    new DbUser()
                    {
                        Id                   = Guid.Parse("2218929f-988c-e611-9c39-f0761cf9a82c"),
                        Email                = "*****@*****.**",
                        Name                 = "Administrator",
                        Surname              = "First",
                        UserName             = "******",
                        PostalAddress        = "38 avenue de l'Opera, F-75002 Paris, France",
                        PhoneNumber          = "+380951234567",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2010, 10, 10, 10, 10, 10),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true
                    },
                    new DbUser()
                    {
                        Id                   = Guid.Parse("B4ADCD73-F17F-4F8D-833A-CD546702654A"),
                        Email                = "*****@*****.**",
                        Name                 = "User",
                        Surname              = "First",
                        UserName             = "******",
                        PostalAddress        = "Unit 42, Land of Bargains Shopping Paradise, 12 Highway 101, Boston, MA, USA",
                        PhoneNumber          = "+130591234567",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2011, 1, 1, 1, 1, 1),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true,
                        Roles                = new List <DbRole> {
                        }
                    },
                    new DbUser()
                    {
                        Id                   = Guid.Parse("B10C1E4A-61A1-4B0D-A2C5-F3A2AF1483BF"),
                        Email                = permanentUserName + "@cafe.com",
                        Name                 = permanentUserName,
                        Surname              = "User",
                        UserName             = permanentUserName,
                        PostalAddress        = "When User decides to delete an account but keep the data, this data will be assigned to this account",
                        PhoneNumber          = "",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2016, 1, 1, 1, 1, 1),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true,
                        Roles                = new List <DbRole> {
                        }
                    }
                };

                var roles = new[]
                {
                    new DbRole()
                    {
                        Id            = Guid.Parse("2318929f-988c-e611-9c39-f0761cf9a82c"),
                        Name          = "Administrator",
                        Discriminator = "Administrator's role",
                        IsGroup       = false,
                        Users         = new [] { users[0] }
                    },
                    new DbRole()
                    {
                        Id            = Guid.Parse("58307169-A9A7-4D48-B2C2-E86A466B911D"),
                        Name          = "Curator",
                        Discriminator = "Curator's role",
                        IsGroup       = false
                    },
                    new DbRole()
                    {
                        Id            = Guid.Parse("81C6630F-ADE9-45F5-A3CE-029D0FEF9FC8"),
                        Name          = "User",
                        Discriminator = "User's role",
                        IsGroup       = false,
                        Users         = new [] { users[1], users[2] }
                    }
                };

                foreach (var role in roles)
                {
                    context.Roles.AddOrUpdate(x => x.Id, role);
                }

                foreach (var user in users)
                {
                    context.Users.AddOrUpdate(x => x.Id, user);
                }

                /*
                 * var userFiles = new[]
                 * {
                 *  new DbUserFile
                 *  {
                 *     Id = Guid.Parse("af3b0a4f-fd2a-45dc-b4c2-444289636332"),
                 *     Name = "test-file.txt",
                 *     CreationDate = System.DateTime.Parse("2016-10-27 17:39:25.900"),
                 *     AcceptedGroups = new List<DbRole> { },
                 *     AcceptedUsers = new List<DbUser> { users[1] },
                 *     AccessMode = DbUserFile.DbFileAccessMode.Explicit,
                 *     Type = DbUserFile.DbFileType.Other,
                 *     Description = "This is text file",
                 *     Owner = users[0]
                 *  },
                 *  new DbUserFile
                 *  {
                 *     Id = Guid.Parse("fa3f9e9f-ced2-4653-8de1-a960945e4a79"),
                 *     Name = "test-file.mp3",
                 *     CreationDate = System.DateTime.Parse("2016-10-27 18:12:27.153"),
                 *     AcceptedGroups = new List<DbRole> { },
                 *     AcceptedUsers = new List<DbUser> { },
                 *     AccessMode = DbUserFile.DbFileAccessMode.Explicit,
                 *     Type = DbUserFile.DbFileType.Audio,
                 *     Description = "This is audio file",
                 *     Owner = users[0]
                 *  }
                 * };
                 *
                 * foreach (var userFile in userFiles)
                 *  context.UserFiles.AddOrUpdate(x => x.Id, userFiles);
                 *
                 * var accessibleResources = new[]
                 * {
                 *  new DbAccessibleResource
                 *  {
                 *     Id = 1,
                 *     Kind = 0,
                 *     Owner = users[0],
                 *     ResourceId = Guid.Parse("af3b0a4f-fd2a-45dc-b4c2-444289636332")
                 *  },
                 *  new DbAccessibleResource
                 *  {
                 *     Id = 2,
                 *     Kind = 0,
                 *     Owner = users[0],
                 *     ResourceId = Guid.Parse("fa3f9e9f-ced2-4653-8de1-a960945e4a79")
                 *  }
                 * };
                 *
                 * var accessRequests = new[]
                 * {
                 *  new DbAccessRequest
                 *  {
                 *      Id = 1,
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:15:26.810"),
                 *      RequestSubject = "Access request 1",
                 *      RequestMessage = "Gime me access, please",
                 *      RequestedResources = new List<DbAccessibleResource> { accessibleResources[0] }
                 *  },
                 *  new DbAccessRequest
                 *  {
                 *      Id = 2,
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:16:07.120"),
                 *      RequestSubject = "Access request 2",
                 *      RequestMessage = "I need to access to this mp3 file!",
                 *      RequestedResources = new List<DbAccessibleResource> { accessibleResources[1] },
                 *  }
                 * };
                 *
                 *
                 * var conversations = new[]
                 * {
                 *  new DbConversation
                 *  {
                 *      Id = 1,
                 *      HasRecieverUnreadMessages = false,
                 *      Receiver = users[0],
                 *      Request = accessRequests[0],
                 *      Requester = users[1],
                 *      Status = DbAccessRequestStatus.Open
                 *  },
                 *  new DbConversation
                 *  {
                 *      Id = 2,
                 *      HasRecieverUnreadMessages = true,
                 *      Receiver = users[0],
                 *      Request = accessRequests[1],
                 *      Requester = users[1],
                 *      Status = DbAccessRequestStatus.Accepted
                 *  }
                 * };
                 *
                 * var messages = new[]
                 * {
                 *  new DbMessage
                 *  {
                 *      Id = 1,
                 *      Conversation = conversations[0],
                 *      Text = "Gime me access, please.",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:15:27.137"),
                 *      Receiver = users[0],
                 *      Sender = users[1]
                 *  },
                 *  new DbMessage
                 *  {
                 *      Id = 2,
                 *      Conversation = conversations[1],
                 *      Text = "I need to access to this mp3 file!",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:16:07.137"),
                 *      Receiver = users[0],
                 *      Sender = users[1]
                 *  },
                 *  new DbMessage
                 *  {
                 *      Id = 3,
                 *      Conversation = conversations[0],
                 *      Text = "Ok, I will give you access. Enjoy it!!",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:24:52.193"),
                 *      Receiver = users[1],
                 *      Sender = users[0]
                 *  }
                 * };
                 *
                 *
                 * foreach (var role in roles)
                 *  context.Roles.AddOrUpdate(x => x.Id, role);
                 *
                 * foreach (var user in users)
                 *  context.Users.AddOrUpdate(x => x.Id, user);
                 *
                 * foreach (var accessibleResource in accessibleResources)
                 *  context.AccessibleResources.AddOrUpdate(x => x.Id, accessibleResource);
                 *
                 * foreach (var userFile in userFiles)
                 *  context.UserFiles.AddOrUpdate(x => x.Id, userFiles);
                 *
                 * foreach (var accessRequest in accessRequests)
                 *  context.AccessRequests.AddOrUpdate(x => x.Id, accessRequest);
                 *
                 * foreach (var conversation in conversations)
                 *  context.Conversations.AddOrUpdate(x => x.Id, conversation);
                 *
                 * foreach (var message in messages)
                 *  context.Messages.AddOrUpdate(x => x.Id, message);
                 */

                ////////Seed for vocabularies

                var directory = AppDomain.CurrentDomain.BaseDirectory;
                //For Denis =>
                //string schemaPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName + "\\Tools\\ModelGenerator\\Compiled\\ease.xsd";
                var           baseBath         = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).FullName;
                string        schemaPath       = baseBath + "\\ease.xsd";
                XmlTextReader reader           = new XmlTextReader(schemaPath);
                XmlSchema     myschema         = XmlSchema.Read(reader, ValidationCallback);
                var           vocabularyValues = new List <DbVocabularyValue>();

                //First check that vocabulary values doesn't exists
                if (!context.VocabularyValues.Any())
                {
                    //Getting asm when stores vocabulary enums
                    var asm =
                        AppDomain.CurrentDomain.GetAssemblies()
                        .AsEnumerable()
                        .Where(w => w.FullName.Contains("CAFE.Core"))
                        .FirstOrDefault();

                    //Get enum types that is Enum, public and it's name ends with 'Vocabulary'
                    var enumTypes = asm.GetTypes()
                                    .Where(t => t.IsEnum && t.IsPublic && t.Name.ToLower().EndsWith("vocabulary"));

                    var enumDics = new Dictionary <string, List <string> >();

                    //Enumerate through each enum types and getting name or alias(XmlEnumAttribute)
                    foreach (var enumType in enumTypes)
                    {
                        var enumNames  = new List <string>();
                        var enemValues = Enum.GetNames(enumType).AsEnumerable();
                        foreach (var enemValue in enemValues)
                        {
                            var findedAlias = enemValue;
                            var memInfo     = enumType.GetMember(enemValue);
                            var attributes  = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute),
                                                                             false);
                            if (attributes.Length > 0)
                            {
                                findedAlias = ((XmlEnumAttribute)attributes[0]).Name;
                            }

                            enumNames.Add(findedAlias);
                        }

                        enumDics.Add(enumType.Name, enumNames);
                    }

                    //Store finded vocabulary values into db with enum type
                    foreach (var enumDic in enumDics)
                    {
                        //Trace.WriteLine(enumDic.Key);

                        var simpleTypeItems = new XmlSchemaObjectCollection();
                        foreach (object item in myschema.Items)
                        {
                            if (item is XmlSchemaSimpleType)
                            {
                                var simpleType = item as XmlSchemaSimpleType;

                                //Trace.WriteLine(simpleType.Name);

                                if (simpleType.Name == enumDic.Key)
                                {
                                    var restrictionType = simpleType.Content as XmlSchemaSimpleTypeRestriction;
                                    if (restrictionType != null)
                                    {
                                        simpleTypeItems = restrictionType.Facets;
                                    }
                                    var compositeType = simpleType.Content as XmlSchemaSimpleTypeUnion;
                                    if (compositeType != null)
                                    {
                                        if (compositeType.MemberTypes.Any())
                                        {
                                            var firstFacetsType = compositeType.MemberTypes.First();
                                            if (firstFacetsType != null)
                                            {
                                                var foundType = FindTypeByName(firstFacetsType.Name, myschema.Items);
                                                if (foundType != null)
                                                {
                                                    var firstRestrictionType = foundType.Content as XmlSchemaSimpleTypeRestriction;
                                                    if (firstRestrictionType != null)
                                                    {
                                                        simpleTypeItems = firstRestrictionType.Facets;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }

                        foreach (var enVal in enumDic.Value)
                        {
                            //Trace.WriteLine(enVal);

                            var documentation = new XmlSchemaDocumentation();
                            foreach (var item in simpleTypeItems)
                            {
                                if (!(item is XmlSchemaEnumerationFacet))
                                {
                                    continue;
                                }

                                var name = (item as XmlSchemaEnumerationFacet).Value;

                                if (name != enVal)
                                {
                                    continue;
                                }

                                var items = (item as XmlSchemaEnumerationFacet).Annotation?.Items;
                                if (null == items)
                                {
                                    continue;
                                }

                                var itemfound = false;
                                foreach (var facetItem in items)
                                {
                                    if (facetItem is XmlSchemaDocumentation)
                                    {
                                        documentation = facetItem as XmlSchemaDocumentation;
                                        itemfound     = true;
                                        break;
                                    }
                                }
                                if (itemfound)
                                {
                                    break;
                                }
                            }

                            vocabularyValues.Add(new DbVocabularyValue()
                            {
                                Type        = enumDic.Key,
                                Value       = enVal,
                                Description = documentation?.Markup?[0].InnerText
                            });
                        }
                    }
                }

                if (!context.SchemaItemDescriptions.Any())
                {
                    var items = LoadXsdDescriptions(schemaPath);
                    WriteSchemaDataToDatabase(items, context);
                }

                //Adding descriptions for labels
                System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(schemaPath);
                var elements2 = doc.Descendants().Where(d => d.Name.LocalName == "documentation");

                foreach (var item in elements2)
                {
                    var name = item.Parent.Parent.FirstAttribute.Value;
                    if (null == vocabularyValues.FirstOrDefault(v => v.Type == name))
                    {
                        vocabularyValues.Add(new DbVocabularyValue()
                        {
                            Type        = name,
                            Value       = "-1",
                            Description = item.Value
                        });
                    }
                }

                context.VocabularyValues.AddRange(vocabularyValues);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #47
0
 internal static string getNodeText(System.Xml.Linq.XDocument xDocument, string nodeName)
 {
     return(xDocument.Descendants(nodeName).FirstOrDefault() == null ? "" : xDocument.Descendants(nodeName).FirstOrDefault().Value);
 }
예제 #48
0
    void ParseWMSCapabilities(DataRecord Record, string Str)
    {
        Record.WMSCapabilities = Str;

        // if(!manager.records.ContainsKey(key) || !manager.records[key].services.ContainsKey("wms"))
        //Debug.LogError(key);
        XmlReader reader = createStringReader(Str);

        System.Xml.Linq.XDocument document = System.Xml.Linq.XDocument.Load(reader);

        var query = document.Descendants("LatLonBoundingBox");//.Descendants("WMT_MS_Capabilities");
        var title = document.Descendants("Title");


        foreach (var t in title)
        {
            //Debug.LogError(t.Name + " " + t.Value);//t.t;
            Record.title = t.Value;
            break;
        }

        int   count = 0;
        float minx = 0, miny = 0, maxx = 0, maxy = 0;

        foreach (var c in query.Attributes())
        {
            switch (c.Name.ToString())
            {
            case "minx":
                minx = float.Parse(c.Value);
                break;

            case "maxx":
                maxx = float.Parse(c.Value);
                break;

            case "miny":
                miny = float.Parse(c.Value);
                break;

            case "maxy":
                maxy = float.Parse(c.Value);
                break;
            }
            count++;
            if (count == 4)
            {
                break;
            }
        }


        // Coordinate System CODE!!!!!!!

        /*int zone = coordsystem.GetZone(maxy, minx);
         * int zone2 = coordsystem.GetZone(miny, maxx);
         * Debug.LogError(zone + " " + zone2);
         * Vector2 upperleft = coordsystem.transformToUTM(minx, maxy);
         * Vector2 lowerright = coordsystem.transformToUTM(maxx, miny);
         * if (zone != zone2)
         * {
         *  // Thanks to https://www.maptools.com/tutorials/utm/details
         *  if (zone < zone2)
         *      upperleft.x -= Mathf.Abs(zone - zone2) * 674000f;
         *  else
         *      lowerright.x -= Mathf.Abs(zone - zone2) * 674000f;
         * }
         * //Debug.LogError(upperleft);
         * manager.records[key].boundingBox = new Rect(upperleft.x, upperleft.y - Mathf.Abs(upperleft.y - lowerright.y), Mathf.Abs(upperleft.x - lowerright.x), Mathf.Abs(upperleft.y - lowerright.y));*/
        // We need to figure out what to assign the rect -- for now it is the logical thing to do
        Record.boundingBox = new Rect(minx, maxy, Mathf.Abs(maxx - minx), Mathf.Abs(maxy - miny));
    }
        private List <string> UpdateShortCutXML(string sysConfigText)
        {
            List <string> returnAttachments = new List <string>();

            if (string.IsNullOrWhiteSpace(sysConfigText))
            {
                return(returnAttachments);
            }

            System.Xml.Linq.XDocument sysConfigDoc = System.Xml.Linq.XDocument.Parse(sysConfigText, LoadOptions.PreserveWhitespace);
            sysConfigDoc.Declaration = new XDeclaration("1.0", "utf-8", null);

            // Find the <Shortcut> Node so we can update its values
            XElement shortcutNode = sysConfigDoc.Descendants("Shortcut").FirstOrDefault();

            if (shortcutNode == null) // Create the node if missing
            {
                if (sysConfigDoc.Element("configuration") == null)
                {
                    sysConfigDoc.Add(new XElement("configuration"));
                }

                sysConfigDoc.Element("configuration").Add(new XElement("Shortcut"));
                shortcutNode = sysConfigDoc.Element("configuration").Element("Shortcut");
            }

            shortcutNode.SetElementValue("Company", ((Session)oTrans.Session).CompanyID);
            shortcutNode.SetElementValue("Plant", ((Session)oTrans.Session).PlantID);
            shortcutNode.SetElementValue("AppServerURL", ((Session)oTrans.Session).AppServer);

            shortcutNode.SetElementValue("DateTime", DateTime.Now.ToString());
            shortcutNode.SetElementValue("Originator", ((Session)oTrans.Session).UserID);

            // Set the <Process> child nodes
            XElement processNode = shortcutNode.Element("Process");

            if (processNode == null)
            {
                shortcutNode.Add(new XElement("Process"));
                processNode = shortcutNode.Element("Process");
            }

            processNode.SetElementValue("ProcessID", "ITAR001"); // MenuID is normally stored in XXXDef.SysCharacter01
            processNode.SetElementValue("Description", "UD01 Notify");

            // Set the RecordIDS node and its child elements
            XElement recordIDsElement = shortcutNode.Element("RecordIDS");

            if (recordIDsElement == null)
            {
                shortcutNode.Add(new XElement("RecordIDS"));
                recordIDsElement = shortcutNode.Element("RecordIDS");
            }

            var keyFieldsValues = GetKeyValues();
            var keyFieldTypes   = GetKeyTpes();
            var keyFields       = GetKeyFields();

            recordIDsElement.SetAttributeValue("KeyFields", keyFields);
            recordIDsElement.SetAttributeValue("KeyFieldsType", "System.String");
            recordIDsElement.SetAttributeValue("TableName", "UD001List");
            recordIDsElement.SetAttributeValue("DataSourceType", "UD01ListDataSet");
            recordIDsElement.SetElementValue("RecordID", keyFieldsValues);
            StringBuilder sb = new StringBuilder();

            //StringWriter swriter = new StringWriter(sb);
            using (StringWriter writer = new Utf8StringWriter(sb))
            {
                sysConfigDoc.Save(writer);
            }
            returnAttachments.Add(sb.ToString());
            return(returnAttachments);
        }
예제 #50
0
        //------------------------------------------------------------------------------------------------
        //選択されているデータをXmlから消去する。
        //------------------------------------------------------------------------------------------------
        public void ChoiceDelete()
        {
            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            int idxRows;

            foreach (DataGridViewCell c in dataGridView1.SelectedCells)
            {
                try
                {
                    idxRows = c.RowIndex;

                    var query = (from y in XmlDoc.Descendants("Chord")
                                 where y.Attribute("ID").Value == Convert.ToString(idxRows + 1)
                                 select y).Single();

                    switch (c.ColumnIndex)
                    {
                    case 1:
                        query.Element("Root").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 2:
                        query.Element("Degree").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 3:
                        query.Element("Position1").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 4:
                        query.Element("Position2").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;


                    case 5:
                        query.Element("Position3").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 6:
                        query.Element("Position4").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;


                    case 7:
                        query.Element("BarreFlg").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 8:
                        query.Element("Barre").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;

                    case 9:
                        query.Element("High").Value = "";
                        XmlDoc.Save(createConfigXML.CurrentPath_database());
                        break;
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
예제 #51
0
 /// <summary>
 /// Gets a text value of an element from the given response.
 /// </summary>
 /// <param name="response">The response from Flickr, containing the XML returned.</param>
 /// <param name="element">The element name to find.</param>
 /// <returns>The string value of the given element, if found.</returns>
 public string GetElementValue(string element)
 {
     System.Xml.Linq.XDocument doc = GetXDocument();
     return(doc.Descendants(element).First().Value);
 }
예제 #52
0
파일: FH.cs 프로젝트: kguo0427/TLink
        public void exportXML()
        {
            //output to the xml file
            string path = this.xmlPath;

            linq.XNamespace ns = "http://www.edi.com.au/EnterpriseService/";

            linq.XDocument doc = linq.XDocument.Load(path);

            linq.XElement rateEntries = new linq.XElement(ns + "RateEntries");
            foreach (RateEntry r in reList)
            {
                linq.XElement entry = new linq.XElement(ns + "RateEntry");
                if (r.category != "")
                {
                    entry.Add(new linq.XElement(ns + "Category", r.category));
                }
                entry.Add(new linq.XElement(ns + "Mode", "SEA"));
                if (r.startDate != "")
                {
                    entry.Add(new linq.XElement(ns + "StartDate", r.startDate));
                }
                if (r.endDate != "")
                {
                    entry.Add(new linq.XElement(ns + "EndDate", r.endDate));
                }
                if (r.ContainerCode != "")
                {
                    linq.XElement ct = new linq.XElement(ns + "ContainerType");
                    ct.Add(new linq.XElement(ns + "ContainerCode", r.ContainerCode));
                    entry.Add(ct);
                }
                if (r.contractNum != "")
                {
                    entry.Add(new linq.XElement(ns + "ContractNumber", r.contractNum));
                }
                if (r.origin != "")
                {
                    entry.Add(new linq.XElement(ns + "Origin", r.origin));
                }
                if (r.destination != "")
                {
                    entry.Add(new linq.XElement(ns + "Destination", r.destination));
                }
                if (r.commodityCode != "")
                {
                    entry.Add(new linq.XElement(ns + "CommodityCode", r.commodityCode));
                }
                linq.XElement rls = new linq.XElement(ns + "RateLines");
                foreach (RateLine rl in r.rl)
                {
                    linq.XElement rateline = new linq.XElement(ns + "RateLine");
                    rateline.Add(new linq.XElement(ns + "Description", "Ocean Freight"));
                    rateline.Add(new linq.XElement(ns + "Currency", "USD"));
                    rateline.Add(new linq.XElement(ns + "ChargeCode", "FRT"));
                    linq.XElement rc  = new linq.XElement(ns + "RateCalculator");
                    linq.XElement unt = new linq.XElement(ns + "UNTCalculator");
                    unt.Add(new linq.XElement(ns + "PerUnitPrice", rl.price));
                    linq.XElement notes = new linq.XElement(ns + "Notes");
                    linq.XElement note  = new linq.XElement(ns + "Note");
                    note.Add(new linq.XElement(ns + "NoteType", "TradeLaneChargeInformation"));
                    note.Add(new linq.XElement(ns + "NoteData", rl.note));
                    rc.Add(unt);
                    notes.Add(note);
                    rateline.Add(rc);
                    rateline.Add(notes);
                    rls.Add(rateline);
                }
                entry.Add(rls);
                rateEntries.Add(entry);
            }
            var ele = doc.Descendants(ns + "Rate").FirstOrDefault();

            if (doc.Descendants(ns + "RateEntries").Any())
            {
                doc.Descendants(ns + "RateEntries").FirstOrDefault().Remove();
            }
            ele.Add(rateEntries);
            doc.Save(path);
        }
    private async static Task <CitrixAuthCredential> GetCredentialsFromStoreFront(string SFURL, string Username, string Password, string Domain, bool IsSSL)
    {
        CitrixAuthCredential _sfCredential = null;

        Dictionary <string, string> _returnedValues = new Dictionary <string, string>();
        string _csrfToken       = Guid.NewGuid().ToString();
        string _aspnetSessionID = Guid.NewGuid().ToString();

        string _username = Username;
        string _password = Password;
        string _domain   = Domain;

        string _authenticationBody = string.Format(@"username={0}\{1}&password={2}", _domain, _username, _password);

        CookieContainer   _cookieContainer = new CookieContainer();
        HttpClientHandler _clientHandler   = new HttpClientHandler();

        _clientHandler.CookieContainer = _cookieContainer;

        System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient(_clientHandler);

        //_client.BaseAddress = new Uri(SFURL);

        string _postAuthUrl = (SFURL.EndsWith("/")) ? "PostCredentialsAuth/Login" : "/PostCredentialsAuth/Login";
        string _postURL     = string.Format("{0}{1}", SFURL, _postAuthUrl);

        if (IsSSL)
        {
            _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "Yes");
        }
        else
        {
            _client.DefaultRequestHeaders.Add("X-Citrix-IsUsingHTTPS", "No");
        }
        _client.DefaultRequestHeaders.Add("Csrf-Token", _csrfToken);

        StringContent _bodyContent = new StringContent(_authenticationBody, Encoding.UTF8, "application/x-www-form-urlencoded");

        HttpResponseMessage _authResp = await _client.PostAsync(_postURL, _bodyContent);

        if (_authResp.StatusCode != System.Net.HttpStatusCode.OK)
        {
            throw new Exception(String.Format("Error: {0}", _authResp.ReasonPhrase));
        }
        else
        {
            /*
             * <?xml version="1.0" encoding="UTF-8"?>
             * <AuthenticationStatus xmlns="http://citrix.com/deliveryservices/webAPI/2-6/authStatus">
             * <Result>success</Result>
             * <AuthType>Certificate</AuthType>
             * </AuthenticationStatus>
             */
            string _returnedContent = await _authResp.Content.ReadAsStringAsync();

            System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(_returnedContent);
            //XmlDocument doc = new XmlDocument();
            //doc.LoadXml(_returnedContent);

            //XmlNamespaceManager _namespaceMgr = new XmlNamespaceManager(doc.NameTable);
            //_namespaceMgr.AddNamespace("mockns", @"http://citrix.com/delivery-services/webAPI/2-6/authStatus");
            XNamespace ns = doc.Root.GetDefaultNamespace();
            XElement   _resultAuthNode = doc.Descendants(ns + "Result").SingleOrDefault();
            //XmlNode _resultAuthNode = doc.SelectSingleNode("//mockns:Result", _namespaceMgr);
            if (_resultAuthNode != null)
            {
                //if (_resultAuthNode.InnerText.ToLower() == "success")
                if (_resultAuthNode.Value.ToLower() == "success")
                {
                    string _cookiePath = "/";
                    string _cookieHost = _authResp.RequestMessage.RequestUri.Host;

                    foreach (var header in _authResp.Headers.Where(i => i.Key == "Set-Cookie"))
                    {
                        foreach (string cookieValue in header.Value)
                        {
                            //"ASP.NET_SessionId=miphlcqdo53dwdipdxj3vp4i; path=/; HttpOnly"
                            string[] cookieElements   = cookieValue.Split(';');
                            string[] keyValueElements = cookieElements[0].Split('=');

                            //path
                            //string[] pathCookieElements = cookieElements[1].Split('=');
                            //_cookiePath = pathCookieElements[1];

                            _returnedValues.Add(keyValueElements[0], keyValueElements[1]);
                        }
                    }

                    _sfCredential = new CitrixAuthCredential
                    {
                        AuthToken     = _returnedValues["CtxsAuthId"].ToString(),
                        CSRFToken     = _returnedValues["CsrfToken"].ToString(),
                        SessionID     = _returnedValues["ASP.NET_SessionId"].ToString(),
                        CookiePath    = _cookiePath,
                        CookieHost    = _cookieHost,
                        StorefrontUrl = SFURL
                    };
                }
            }
            else
            {
                _sfCredential = null;
            }
        }
        return(_sfCredential);
    }
예제 #54
0
        private static async Task <List <object> > LoadXMLReportAsync(String xml, int ReportType)
        {
            List <object> rawData = null;
            await Task.Factory.StartNew(delegate
            {
                XNamespace m = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
                XNamespace d = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");
                System.Xml.Linq.XDocument doc = XDocument.Parse(xml);

                if (ReportType == 1 || ReportType == 2 || ReportType == 5)
                {
                    IEnumerable <object> Companies = from s in doc.Descendants().Where(x => x.Name.LocalName == "properties")

                                                     select new SaleReportD
                    {
                        ID = s.Element(d + "ID").Value,
                        //SortId = int.Parse(s.Element(d + "Name").Value),
                        Name        = s.Element(d + "Name").Value,
                        SalesAmount = (s.Element(d + "SalesAmount").Value),
                        CostPrice   = (s.Element(d + "CostPrice").Value)
                    };
                    //var sortedCars = Companies.OrderBy(c => c.SortId);
                    //List<object> myAnythingList = (sortedCars as IEnumerable<object>).Cast<object>().ToList();
                    rawData = Companies.ToList();
                }
                if (ReportType == 3)
                {
                    IEnumerable <object> Companies = from s in doc.Descendants().Where(x => x.Name.LocalName == "properties")

                                                     select new SaleReportA
                    {
                        ID          = int.Parse(s.Element(d + "ID").Value),
                        Name        = s.Element(d + "Name").Value,
                        SalesAmount = (s.Element(d + "SalesAmount").Value),
                        CostPrice   = (s.Element(d + "CostPrice").Value)
                    };
                    rawData = Companies.ToList();
                }
                if (ReportType == 4)
                {
                    IEnumerable <object> Companies = from s in doc.Descendants().Where(x => x.Name.LocalName == "properties")

                                                     select new SaleReportA
                    {
                        ID          = int.Parse(s.Element(d + "ID").Value),
                        Name        = s.Element(d + "Name").Value,
                        SalesAmount = (s.Element(d + "SalesAmount").Value),
                        CostPrice   = (s.Element(d + "CostPrice").Value)
                    };
                    rawData = Companies.ToList();
                }

                if (ReportType == 5)
                {
                    IEnumerable <SalereportT> Companies = from s in doc.Descendants().Where(x => x.Name.LocalName == "properties")

                                                          select new SalereportT
                    {
                        ID          = s.Element(d + "ID").Value,
                        SortId      = int.Parse(s.Element(d + "Name").Value),
                        Name        = s.Element(d + "Name").Value,
                        SalesAmount = (s.Element(d + "SalesAmount").Value),
                        CostPrice   = (s.Element(d + "CostPrice").Value)
                    };
                    var sortedCars = Companies.OrderBy(c => c.SortId);
                    List <object> myAnythingList = (sortedCars as IEnumerable <object>).Cast <object>().ToList();
                    rawData = myAnythingList.ToList();
                }
            });

            return(rawData);
        }
예제 #55
0
        //------------------------------------------------------------------------------------------------
        //DataGridviewのデータをXmlに書き込む
        //------------------------------------------------------------------------------------------------
        public void WriteXml()
        {
            int RowCount  = dataGridView1.RowCount;
            var Root      = "";
            var Degree    = "";
            var Position1 = "";
            var Position2 = "";
            var Position3 = "";
            var Position4 = "";
            var BarreFlg  = "";
            var Barre     = "";
            var High      = "";

            XElement query;

            XmlDoc = new XDocument();
            XmlDoc = XDocument.Load(createConfigXML.CurrentPath_database(), LoadOptions.PreserveWhitespace);

            //Xmlファイルに書き込み
            for (int i = 0; i < RowCount; i++)
            {
                Root      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                Degree    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                Position1 = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                Position2 = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                Position3 = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                Position4 = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                BarreFlg  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                Barre     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                High      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);

                try
                {
                    var writeXml = new XElement("Data",
                                                new XAttribute("ID", i + 1),
                                                new XElement("Root", ""),
                                                new XElement("Degree", ""),
                                                new XElement("Position1", ""),
                                                new XElement("Position2", ""),
                                                new XElement("Position3", ""),
                                                new XElement("Position4", ""),
                                                new XElement("BarreFlg", ""),
                                                new XElement("Barre", ""),
                                                new XElement("High", ""));

                    XmlDoc.Elements().First().Add(writeXml);
                    XmlDoc.Save(createConfigXML.CurrentPath_database());

                    //データグリッドビューの値をXmlに書き込み
                    query = (from y in XmlDoc.Descendants("Chord")
                             where y.Attribute("ID").Value == Convert.ToString(i + 1)
                             select y).Single();

                    query.Element("Root").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
                    query.Element("Degree").Value    = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
                    query.Element("Position1").Value = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
                    query.Element("Position2").Value = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
                    query.Element("Position3").Value = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
                    query.Element("Position4").Value = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
                    query.Element("BarreFlg").Value  = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
                    query.Element("Barre").Value     = Convert.ToString(dataGridView1.Rows[i].Cells[8].Value);
                    query.Element("High").Value      = Convert.ToString(dataGridView1.Rows[i].Cells[9].Value);



                    XmlDoc.Save(createConfigXML.CurrentPath_database());
                }
                catch (Exception ex)
                {
                }
            }
        }