Exemplo n.º 1
0
 public static Molecule ParseCML(FileStream file)
 {
     Dictionary<int, BondingAtom> atoms = new Dictionary<int, BondingAtom>();
     XmlTextReader reader = new XmlTextReader(file);
     reader.ReadToFollowing("molecule");
     reader.ReadToDescendant("atomArray");
     reader.ReadToDescendant("atom");
     do
     {
         atoms.Add(int.Parse(reader.GetAttribute("id").Substring(1)) - 1, new BondingAtom(Elements.FromSymbol(reader.GetAttribute("elementType"))));
     } while (reader.ReadToNextSibling("atom"));
     reader.ReadToNextSibling("bondArray");
     reader.ReadToDescendant("bond");
     do
     {
         string[] atomRefs = reader.GetAttribute("atomRefs2").Split(' ');
         int order = 0;
         switch (reader.GetAttribute("order"))
         {
             case "S":
                 order = 1;
                 break;
             case "D":
                 order = 2;
                 break;
             case "T":
                 order = 3;
                 break;
         }
         atoms[int.Parse(atomRefs[0].Substring(1)) - 1].Bond(atoms[int.Parse(atomRefs[1].Substring(1)) - 1], order);
     } while (reader.ReadToNextSibling("bond"));
     return new Molecule(new List<BondingAtom>(atoms.Values));
 }
Exemplo n.º 2
0
        public static LocalizationData ReadXml(XmlTextReader xr)
        {
            Dictionary<String, Field[]> res = new Dictionary<string, Field[]>();
            if (xr.ReadToDescendant("localization"))
                if (xr.ReadToDescendant("type"))
                    do
                    {
                        List<Field> fields = new List<Field>();
                        var name = xr.GetAttribute("name");
                        if (xr.ReadToDescendant("field"))
                            do
                            {
                                switch (xr.NodeType)
                                {
                                    case XmlNodeType.Element:
                                        if (xr.Name == "field")
                                            fields.Add(new Field { FieldName = xr.GetAttribute("name"), LocalizedText = xr.ReadElementContentAsString() });
                                        break;
                                }
                            } while (xr.ReadToNextSibling("field"));

                        if (fields.Count > 0)
                            res[name] = fields.ToArray();
                    }
                    while (xr.ReadToNextSibling("type"));
            return new LocalizationData(res);
        }
Exemplo n.º 3
0
 public string GetXMLValue(XmlTextReader reader, String nodeName)
 {
     if (reader.ReadToDescendant(nodeName))
         return reader.ReadElementContentAsString();
     else
         return "";
 }
 private static bool TryExtractImageUri(string fragment, out Uri imageUri)
 {
     try
     {
         XmlReader rdr = new XmlTextReader(fragment, XmlNodeType.Element, null);
         rdr.Read();
         if (rdr.Name != "img")
         {
             if (!rdr.ReadToDescendant("img"))
             {
                 imageUri = null;
                 return false;
             }
         }
         string attribute = rdr.GetAttribute("src");
         if (!string.IsNullOrEmpty(attribute))
         {
             imageUri = new Uri(attribute);
             return true;
         }
         else
         {
             imageUri = default(Uri);
             return false;
         }
     }
     catch (Exception ex)
     {
         imageUri = default(Uri);
         return false;
     }
 }
        public void PhotosSerializationSkipBlankPhotoRowTest()
        {
            const string xml = @"<photos page=""1"" pages=""1"" perpage=""500"" total=""500"">
                    <photo id=""3662960087"" owner=""18499405@N00"" secret=""9f8fcf9269"" server=""3379"" farm=""4"" title=""gecko closeup""
                        ispublic=""1"" isfriend=""0"" isfamily=""0"" dateupload=""1246050291""
                        tags=""reptile jinaacom geckocloseup geckoanatomy jinaajinahibrahim"" latitude=""1.45"" />
                    <photo id="""" owner="""" secret="""" server="""" farm=""0"" title=""""
                        ispublic="""" isfriend="""" isfamily="""" dateupload="""" tags="""" latitude="""" />
                    <photo id=""3662960087"" owner=""18499405@N00"" secret=""9f8fcf9269"" server=""3379"" farm=""4"" title=""gecko closeup""
                        ispublic=""1"" isfriend=""0"" isfamily=""0"" dateupload=""1246050291"" tags=""reptile jinaacom geckocloseup geckoanatomy jinaajinahibrahim"" latitude=""1.45"" />
                    </photos>";

            var photos = new PhotoCollection();

            var sr = new StringReader(xml);
            var reader = new XmlTextReader(sr) {WhitespaceHandling = WhitespaceHandling.Significant};

            reader.ReadToDescendant("photos");

            ((IFlickrParsable) photos).Load(reader);

            Assert.IsNotNull(photos, "Photos should not be null");
            Assert.AreEqual(500, photos.Total, "Total photos should be 500");
            Assert.AreEqual(2, photos.Count, "Should only contain 2 photo");
        }
Exemplo n.º 6
0
 public override void ProcessFile(string filePath, Dictionary<string, LocalizableEntity> map)
 {
     Logger.LogFormat("Processing file {0}", filePath);
     XmlTextReader xr = new XmlTextReader(filePath);
     string propertyPath = string.Empty;
     try
     {
         if (xr.ReadToDescendant("localization"))
             if (xr.ReadToDescendant("type"))
                 do
                 {
                     var className = xr.GetAttribute("name");
                     if (xr.ReadToDescendant("field"))
                         do
                         {
                             switch (xr.NodeType)
                             {
                                 case XmlNodeType.Element:
                                     if (xr.Name == "field")
                                     {
                                         String fieldName = xr.GetAttribute("name");
                                         String fieldValue = xr.ReadElementContentAsString();
                                         LocalizableEntity property = GetLocalizableProperty(filePath, className, fieldName, fieldValue);
                                         propertyPath = property.FullEntityPath;
                                         map.Add(propertyPath, property);
                                     }
                                     break;
                             }
                         } while (xr.ReadToNextSibling("field"));
                 } while (xr.ReadToNextSibling("type"));
     }
     catch (Exception ex)
     {
         Logger.LogFormat("Error ({0})", filePath);
         throw new ExtractorException("Error: '{0}'. Property path: '{1}'", ex.Message, propertyPath);
     }
     finally
     {
         xr.Close();
     }
 }
Exemplo n.º 7
0
 static OrderWizard()
 {
     string conditionsDataPath =
         HttpContext.Current.Server.MapPath(PathToJoesPubSeatingConditions);
     XmlTextReader reader = new XmlTextReader(conditionsDataPath);
     if (!reader.ReadToFollowing("pubSeatingConditions"))
         throw new XmlException("Can't find <pubSeatingConditions> node.");
     if (!reader.ReadToDescendant("section"))
         throw new XmlException("Can't find any <section> nodes.");
     syosSeatingConditions = new Dictionary<int, string>();
     do
     {
         if (!reader.MoveToAttribute("id"))
             throw new XmlException("Can't find \"id\" attribute for <section>.");
         int id = Int32.Parse(reader.Value.Trim());
         reader.MoveToElement();
         string conditions = reader.ReadElementContentAsString();
         syosSeatingConditions.Add(id, conditions);
     }
     while (reader.ReadToNextSibling("section"));
 }
		// true if the resx file or any file referenced
		// by the resx is newer than the .resources file
		public static bool IsResgenRequired (string resx_filename)
		{
			if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
				throw new ArgumentException (".resx file expected", "resx_filename");

			string resources_filename = Path.ChangeExtension (resx_filename, ".resources");

			if (IsFileNewerThan (resx_filename, resources_filename))
				return true;

			XmlTextReader xr = null;
			try {
				// look for
				// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
				//   <value>... filename;.. </value>
				// </data>
				xr = new XmlTextReader (resx_filename);
				string basepath = Path.GetDirectoryName (resx_filename);
				while (xr.Read ()) {
					if (xr.NodeType != XmlNodeType.Element ||
						String.Compare (xr.LocalName, "data") != 0)
						continue;

					string type = xr.GetAttribute ("type");
					if (String.IsNullOrEmpty (type))
						continue;

					if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
						continue;

					xr.ReadToDescendant ("value");
					if (xr.NodeType != XmlNodeType.Element)
						continue;

					string value = xr.ReadElementContentAsString ();

					string [] parts = value.Split (';');
					if (parts.Length > 0) {
						string referenced_filename = MSBuildProjectService.FromMSBuildPath (
								String.Empty, Path.Combine (basepath, parts [0]).Trim ());
						if (File.Exists (referenced_filename) &&
							IsFileNewerThan (referenced_filename, resources_filename))
							return true;
					}
				}
			} catch (XmlException) {
				// Ignore xml errors, let resgen handle it
				return true;
			} finally {
				if (xr != null)
					xr.Close ();
			}

			return false;
		}
Exemplo n.º 9
0
        //This returns all Files that are included in the plugin folder from GitHub.
        internal static List<string> ReturnGitHubContentFiles()
        {
            List<string> returnValues = new List<string>();

            try
            {
                using (XmlTextReader reader = new XmlTextReader(GitHubProjectUrl))
                {
                    // simply (and easily) skip the junk at the beginning
                    reader.MoveToContent();
                    reader.ReadToDescendant("ItemGroup");

                    if ((reader.NodeType == XmlNodeType.Element) &&
                          (reader.Name == "ItemGroup"))
                    {
                        while (reader.Read())
                        {

                            if ((reader.NodeType == XmlNodeType.Element) &&
                                  (reader.IsStartElement()) &&
                                    reader.HasAttributes)
                            {
                                switch (reader.LocalName)
                                {
                                    case "Content":
                                    case "None":
                                    case "Compile":
                                        string s = reader.GetAttribute(0);
                                        returnValues.Add(s);
                                        break;
                                }
                            }

                        }
                    }
                }

            }
            catch (Exception)
            {

            }

            return returnValues;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        public void Deserialize(string data) {
            // If there is nothing to deserialize, return a newly created instance of the target type.
            if (String.IsNullOrEmpty(data))
                return;

            // Decompress and deserialize the data.
            byte[] decoded_buffer = Convert.FromBase64String(data);
            using (var zipped = new MemoryStream(decoded_buffer)) {
                using (var s = new GZipStream(zipped, CompressionMode.Decompress)) {
                    using (var reader = new XmlTextReader(s)) {

                        if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "configuration") {
                            if (reader.ReadToDescendant("entry")) {
                                var depth = reader.Depth;

                                ReadEntryFromXml(reader);

                                var shouldContinue = true;
                                while (shouldContinue && reader.Depth == depth)
                                    shouldContinue = ReadEntryFromXml(reader);
                            }

                            reader.Read();
                        }

                    }
                }
            }
        }
Exemplo n.º 11
0
    public bool Import(string fileName, bool deleteBeforeImport, bool showProgress)
    {
      //System.Diagnostics.Debugger.Launch();
      _errorMessage = "";
      if (_isImporting == true)
      {
        _errorMessage = "already importing...";
        return false;
      }
      _isImporting = true;

      bool result = false;
      XmlTextReader xmlReader = null;


      // remove old programs
      _status.Status = "Removing old programs";
      _status.Channels = 0;
      _status.Programs = 0;
      _status.StartTime = DateTime.Now;
      _status.EndTime = new DateTime(1971, 11, 6);
      if (showProgress && ShowProgress != null) ShowProgress(_status);

      layer.RemoveOldPrograms();

      /*
      // for each channel, get the last program's time
      Dictionary<int, DateTime> lastProgramForChannel = new Dictionary<int, DateTime>();
      IList channels = Channel.ListAll();
      foreach (Channel ch in channels)
      {
        SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof(TvDatabase.Program));
        sb.AddConstraint(Operator.Equals, "idChannel", ch.IdChannel);
        sb.AddOrderByField(false, "starttime");
        sb.SetRowLimit(1);
        SqlStatement stmt = sb.GetStatement(true);
        IList programsInDbs = ObjectFactory.GetCollection(typeof(TvDatabase.Program), stmt.Execute());

        DateTime lastProgram = DateTime.MinValue;
        if (programsInDbs.Count > 0)
        {
          TvDatabase.IProgram p = (TvDatabase.Program)programsInDbs[0];
          lastProgram = p.EndTime;
        }
        lastProgramForChannel[ch.IdChannel] = lastProgram;
      }*/

      //TVDatabase.SupressEvents = true;
      bool useTimeZone = layer.GetSetting("xmlTvUseTimeZone", "false").Value == "true";
      int hours = Int32.Parse(layer.GetSetting("xmlTvTimeZoneHours", "0").Value);
      int mins = Int32.Parse(layer.GetSetting("xmlTvTimeZoneMins", "0").Value);
      int timeZoneCorrection = hours * 60 + mins;

      ArrayList Programs = new ArrayList();
      Dictionary<int, ChannelPrograms> dChannelPrograms = new Dictionary<int, ChannelPrograms>();
      try
      {
        Log.WriteFile("xmltv import {0}", fileName);

        //
        // Make sure the file exists before we try to do any processing
        //
        if (File.Exists(fileName))
        {
          _status.Status = "Loading channel list";
          _status.Channels = 0;
          _status.Programs = 0;
          _status.StartTime = DateTime.Now;
          _status.EndTime = new DateTime(1971, 11, 6);
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Dictionary<int, Channel> guideChannels = new Dictionary<int, Channel>();

          IList<Channel> allChannels = Channel.ListAll();

          int iChannel = 0;

          xmlReader = new XmlTextReader(fileName);

          #region import non-mapped channels by their display-name

          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first channel
            if (xmlReader.ReadToDescendant("channel"))
            {
              do
              {
                String id = xmlReader.GetAttribute("id");
                if (id == null || id.Length == 0)
                {
                  Log.Error("  channel#{0} doesnt contain an id", iChannel);
                }
                else
                {
                  String displayName = null;

                  XmlReader xmlChannel = xmlReader.ReadSubtree();
                  xmlChannel.ReadStartElement(); // read channel
                  // now, xmlChannel is positioned on the first sub-element of <channel>
                  while (!xmlChannel.EOF)
                  {
                    if (xmlChannel.NodeType == XmlNodeType.Element)
                    {
                      switch (xmlChannel.Name)
                      {
                        case "display-name":
                        case "Display-Name":
                          if (displayName == null) displayName = xmlChannel.ReadString();
                          else xmlChannel.Skip();
                          break;
                          // could read more stuff here, like icon...
                        default:
                          // unknown, skip entire node
                          xmlChannel.Skip();
                          break;
                      }
                    }
                    else
                      xmlChannel.Read();
                  }
                  if (xmlChannel != null)
                  {
                    xmlChannel.Close();
                    xmlChannel = null;
                  }

                  if (displayName == null || displayName.Length == 0)
                  {
                    Log.Error("  channel#{0} xmlid:{1} doesnt contain an displayname", iChannel, id);
                  }
                  else
                  {
                    Channel chan = null;

                    // a guide channel can be mapped to multiple tvchannels
                    foreach (Channel ch in allChannels)
                    {
                      if (ch.ExternalId == id)
                      {
                        chan = ch;
                        chan.ExternalId = id;
                      }

                      if (chan == null)
                      {
                        // no mapping found, ignore channel
                        continue;
                      }

                      ChannelPrograms newProgChan = new ChannelPrograms();
                      newProgChan.Name = chan.DisplayName;
                      newProgChan.ExternalId = chan.ExternalId;
                      Programs.Add(newProgChan);

                      Log.WriteFile("  channel#{0} xmlid:{1} name:{2} dbsid:{3}", iChannel, chan.ExternalId,
                                    chan.DisplayName, chan.IdChannel);
                      if (!guideChannels.ContainsKey(chan.IdChannel))
                      {
                        guideChannels.Add(chan.IdChannel, chan);
                        dChannelPrograms.Add(chan.IdChannel, newProgChan);
                      }
                    }

                    _status.Channels++;
                    if (showProgress && ShowProgress != null) ShowProgress(_status);
                  }
                }
                iChannel++;
                // get the next channel
              } while (xmlReader.ReadToNextSibling("channel"));
            }
          }

          //xmlReader.Close();

          #endregion

          SqlBuilder sb = new SqlBuilder(StatementType.Select, typeof (Channel));
          sb.AddOrderByField(true, "externalId");
          sb.AddConstraint("externalId IS NOT null");
          sb.AddConstraint(Operator.NotEquals, "externalId", "");

          SqlStatement stmt = sb.GetStatement(true);
          allChannels = ObjectFactory.GetCollection<Channel>(stmt.Execute());
          if (allChannels.Count == 0)
          {
            _isImporting = false;
            if (xmlReader != null)
            {
              xmlReader.Close();
              xmlReader = null;
            }

            return true;
          }

          ///////////////////////////////////////////////////////////////////////////
          /*  design:
           * 1. create a Dictionary<string,Channel> using the externalid as the key,
           *    add all channels to this Dictionary 
           *    Note: channel -> guidechannel is a one-to-many relationship. 
           * 2. Read all programs from the xml file
           * 3. Create a program for each mapped channel
           */
          ///////////////////////////////////////////////////////////////////////////
          Dictionary<string, List<Channel>> allChannelMappingsByExternalId = new Dictionary<string, List<Channel>>();

          string previousExternalId = null;
          // one-to-many so we need a collection of channels for each externalId
          List<Channel> eidMappedChannels = new List<Channel>();

          for (int i = 0; i < allChannels.Count; i++)
          {
            Channel ch = (Channel)allChannels[i];

            if (previousExternalId == null)
            {
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }
            else if (ch.ExternalId == previousExternalId)
            {
              eidMappedChannels.Add(ch);
            }
            else
            {
              // got all channels for this externalId. Add the mappings
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
              // new externalid, create a new List & add the channel to the new List
              eidMappedChannels = new List<Channel>();
              eidMappedChannels.Add(ch);
              previousExternalId = ch.ExternalId;
            }

            if (i == allChannels.Count - 1)
            {
              allChannelMappingsByExternalId.Add(previousExternalId, eidMappedChannels);
            }
          }

          int programIndex = 0;
          _status.Status = "Loading TV programs";
          if (showProgress && ShowProgress != null) ShowProgress(_status);

          Log.Debug("xmltvimport: Reading TV programs");
          if (xmlReader != null)
          {
            xmlReader.Close();
            xmlReader = null;
          }
          xmlReader = new XmlTextReader(fileName);
          if (xmlReader.ReadToDescendant("tv"))
          {
            // get the first programme
            if (xmlReader.ReadToDescendant("programme"))
            {
              #region read programme node

              do
              {
                ChannelPrograms channelPrograms = new ChannelPrograms();

                String nodeStart = xmlReader.GetAttribute("start");
                String nodeStop = xmlReader.GetAttribute("stop");
                String nodeChannel = xmlReader.GetAttribute("channel");

                String nodeTitle = null;
                String nodeCategory = null;
                String nodeDescription = null;
                String nodeEpisode = null;
                String nodeRepeat = null;
                String nodeEpisodeNum = null;
                String nodeEpisodeNumSystem = null;
                String nodeDate = null;
                String nodeStarRating = null;
                String nodeClassification = null;

                XmlReader xmlProg = xmlReader.ReadSubtree();
                xmlProg.ReadStartElement(); // read programme
                // now, xmlProg is positioned on the first sub-element of <programme>
                while (!xmlProg.EOF)
                {
                  if (xmlProg.NodeType == XmlNodeType.Element)
                  {
                    switch (xmlProg.Name)
                    {
                      case "title":
                        if (nodeTitle == null) nodeTitle = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "category":
                        if (nodeCategory == null) nodeCategory = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "desc":
                        if (nodeDescription == null) nodeDescription = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "sub-title":
                        if (nodeEpisode == null) nodeEpisode = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "previously-shown":
                        if (nodeRepeat == null) nodeRepeat = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "episode-num":
                        if (xmlProg.GetAttribute("system").Equals("xmltv_ns")) 
                        {
                            nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                            nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else if (nodeEpisodeNum == null && xmlProg.GetAttribute("system").Equals("onscreen"))
                        {
                          nodeEpisodeNumSystem = xmlProg.GetAttribute("system");
                          nodeEpisodeNum = xmlProg.ReadString();
                        }
                        else xmlProg.Skip();
                        break;
                      case "date":
                        if (nodeDate == null) nodeDate = xmlProg.ReadString();
                        else xmlProg.Skip();
                        break;
                      case "star-rating":
                        if (nodeStarRating == null) nodeStarRating = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      case "rating":
                        if (nodeClassification == null) nodeClassification = xmlProg.ReadInnerXml();
                        else xmlProg.Skip();
                        break;
                      default:
                        // unknown, skip entire node
                        xmlProg.Skip();
                        break;
                    }
                  }
                  else
                    xmlProg.Read();
                }
                if (xmlProg != null)
                {
                  xmlProg.Close();
                  xmlProg = null;
                }

                #endregion

                #region verify/convert values (programme)

                if (nodeStart != null && nodeChannel != null && nodeTitle != null &&
                    nodeStart.Length > 0 && nodeChannel.Length > 0 && nodeTitle.Length > 0)
                {
                  string description = "";
                  string category = "-";
                  string serEpNum = "";
                  string date = "";
                  string seriesNum = "";
                  string episodeNum = "";
                  string episodeName = "";
                  string episodePart = "";
                  int starRating = -1;
                  string classification = "";

                  string title = ConvertHTMLToAnsi(nodeTitle);

                  long startDate = 0;
                  if (nodeStart.Length >= 14)
                  {
                    if (Char.IsDigit(nodeStart[12]) && Char.IsDigit(nodeStart[13]))
                      startDate = Int64.Parse(nodeStart.Substring(0, 14)); //20040331222000
                    else
                      startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }
                  else if (nodeStart.Length >= 12)
                  {
                    startDate = 100 * Int64.Parse(nodeStart.Substring(0, 12)); //200403312220
                  }

                  long stopDate = startDate;
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length >= 14)
                    {
                      if (Char.IsDigit(nodeStop[12]) && Char.IsDigit(nodeStop[13]))
                        stopDate = Int64.Parse(nodeStop.Substring(0, 14)); //20040331222000
                      else
                        stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                    else if (nodeStop.Length >= 12)
                    {
                      stopDate = 100 * Int64.Parse(nodeStop.Substring(0, 12)); //200403312220
                    }
                  }

                  startDate = CorrectIllegalDateTime(startDate);
                  stopDate = CorrectIllegalDateTime(stopDate);
                  string timeZoneStart = "";
                  string timeZoneEnd = "";
                  if (nodeStart.Length > 14)
                  {
                    timeZoneStart = nodeStart.Substring(14);
                    timeZoneStart = timeZoneStart.Trim();
                    timeZoneEnd = timeZoneStart;
                  }
                  if (nodeStop != null)
                  {
                    if (nodeStop.Length > 14)
                    {
                      timeZoneEnd = nodeStop.Substring(14);
                      timeZoneEnd = timeZoneEnd.Trim();
                    }
                  }

                  //
                  // add time correction
                  //

                  // correct program starttime
                  DateTime dateTimeStart = longtodate(startDate);
                  dateTimeStart = dateTimeStart.AddMinutes(timeZoneCorrection);

                  if (useTimeZone)
                  {
                    int off = GetTimeOffset(timeZoneStart);
                    int h = off / 100; // 220 -> 2,  -220 -> -2
                    int m = off - (h * 100); // 220 -> 20, -220 -> -20

                    dateTimeStart = dateTimeStart.AddHours(-h);
                    dateTimeStart = dateTimeStart.AddMinutes(-m);
                    dateTimeStart = dateTimeStart.ToLocalTime();
                  }
                  startDate = datetolong(dateTimeStart);

                  if (nodeStop != null)
                  {
                    // correct program endtime
                    DateTime dateTimeEnd = longtodate(stopDate);
                    dateTimeEnd = dateTimeEnd.AddMinutes(timeZoneCorrection);

                    if (useTimeZone)
                    {
                      int off = GetTimeOffset(timeZoneEnd);
                      int h = off / 100; // 220 -> 2,  -220 -> -2
                      int m = off - (h * 100); // 220 -> 20, -220 -> -20

                      dateTimeEnd = dateTimeEnd.AddHours(-h);
                      dateTimeEnd = dateTimeEnd.AddMinutes(-m);
                      dateTimeEnd = dateTimeEnd.ToLocalTime();
                    }
                    stopDate = datetolong(dateTimeEnd);
                  }
                  else stopDate = startDate;

                  //int channelId = -1;
                  //string channelName = "";

                  if (nodeCategory != null)
                    category = nodeCategory;

                  if (nodeDescription != null)
                  {
                    description = ConvertHTMLToAnsi(nodeDescription);
                  }
                  if (nodeEpisode != null)
                  {
                    episodeName = ConvertHTMLToAnsi(nodeEpisode);
                    if (title.Length == 0)
                      title = nodeEpisode;
                  }

                  if (nodeEpisodeNum != null)
                  {
                    if (nodeEpisodeNumSystem != null)
                    {
                      // http://xml.coverpages.org/XMLTV-DTD-20021210.html
                      if (nodeEpisodeNumSystem == "xmltv_ns")
                      {
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                        int dot1 = serEpNum.IndexOf(".", 0);
                        int dot2 = serEpNum.IndexOf(".", dot1 + 1);
                        seriesNum = serEpNum.Substring(0, dot1);
                        episodeNum = serEpNum.Substring(dot1 + 1, dot2 - (dot1 + 1));
                        episodePart = serEpNum.Substring(dot2 + 1, serEpNum.Length - (dot2 + 1));
                        //xmltv_ns is theorically zero-based number will be increased by one
                        seriesNum = CorrectEpisodeNum(seriesNum, 1);
                        episodeNum = CorrectEpisodeNum(episodeNum, 1);
                        episodePart = CorrectEpisodeNum(episodePart, 1);
                      }
                      else if (nodeEpisodeNumSystem == "onscreen")
                      {
                        // example: 'Episode #FFEE' 
                        serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum);
                        int num1 = serEpNum.IndexOf("#", 0);
                        if (num1 > 0)
                        {
                          episodeNum = CorrectEpisodeNum(serEpNum.Substring(num1, serEpNum.Length - num1), 0);
                        }
                        else
                        {
                          if (serEpNum.IndexOf(":", 0) > 0)
                          {
                            episodeNum = CorrectEpisodeNum(serEpNum, 0);
                          }
                          else
                          {
                            Regex regEpisode = new Regex("(?<episode>\\d*)\\D*(?<series>\\d*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
                            Match m = regEpisode.Match(serEpNum);
                            if (m.Success)
                            {
                              episodeNum = CorrectEpisodeNum(m.Groups["episode"].Value, 0);
                              seriesNum = CorrectEpisodeNum(m.Groups["series"].Value, 0);
                            }
                            else
                            {
                              episodeNum = CorrectEpisodeNum(serEpNum, 0);
                            }
                          }
                        }
                      }
                    }
                    else
                      // fixing mantis bug 1486: XMLTV import doesn't take episode number from TVGuide.xml made by WebEPG 
                    {
                      // example: '5' like WebEPG is creating
                      serEpNum = ConvertHTMLToAnsi(nodeEpisodeNum.Replace(" ", ""));
                      episodeNum = CorrectEpisodeNum(serEpNum, 0);
                    }
                  }

                  if (nodeDate != null)
                  {
                    date = nodeDate;
                  }

                  if (nodeStarRating != null)
                  {
                    starRating = ParseStarRating(nodeStarRating);
                  }

                  if (nodeClassification != null)
                  {
                    classification = nodeClassification;
                  }

                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);

                  #endregion

                  #region create a program for every mapped channel

                  List<Channel> mappedChannels;

                  if (allChannelMappingsByExternalId.ContainsKey(nodeChannel))
                  {
                    mappedChannels = allChannelMappingsByExternalId[nodeChannel];
                    if (mappedChannels != null && mappedChannels.Count > 0)
                    {
                      foreach (Channel chan in mappedChannels)
                      {
                        // get the channel program
                        channelPrograms = dChannelPrograms[chan.IdChannel];

                        if (chan.IdChannel < 0)
                        {
                          continue;
                        }

                        title = title.Replace("\r\n", " ");
                        title = title.Replace("\n\r", " ");
                        title = title.Replace("\r", " ");
                        title = title.Replace("\n", " ");
                        title = title.Replace("  ", " ");

                        description = description.Replace("\r\n", " ");
                        description = description.Replace("\n\r", " ");
                        description = description.Replace("\r", " ");
                        description = description.Replace("\n", " ");
                        description = description.Replace("  ", " ");

                        episodeName = episodeName.Replace("\r\n", " ");
                        episodeName = episodeName.Replace("\n\r", " ");
                        episodeName = episodeName.Replace("\r", " ");
                        episodeName = episodeName.Replace("\n", " ");
                        episodeName = episodeName.Replace("  ", " ");

                        Program prog = new Program(chan.IdChannel, longtodate(startDate), longtodate(stopDate), title,
                                                   description, category, Program.ProgramState.None,
                                                   System.Data.SqlTypes.SqlDateTime.MinValue.Value, seriesNum,
                                                   episodeNum, episodeName, episodePart, starRating, classification, -1);
                        channelPrograms.programs.Add(prog);
                        programIndex++;
                        //prog.Description = ConvertHTMLToAnsi(strDescription);
                        //prog.StartTime = iStart;
                        //prog.EndTime = iStop;
                        //prog.Title = ConvertHTMLToAnsi(strTitle);
                        //prog.Genre = ConvertHTMLToAnsi(strCategory);
                        //prog.Channel = ConvertHTMLToAnsi(strChannelName);
                        //prog.Date = strDate;
                        //prog.Episode = ConvertHTMLToAnsi(strEpisode);
                        //prog.Repeat = ConvertHTMLToAnsi(strRepeat);
                        //prog.SeriesNum = ConvertHTMLToAnsi(strSeriesNum);
                        //prog.EpisodeNum = ConvertHTMLToAnsi(strEpisodeNum);
                        //prog.EpisodePart = ConvertHTMLToAnsi(strEpisodePart);
                        //prog.StarRating = ConvertHTMLToAnsi(strStarRating);
                        //prog.Classification = ConvertHTMLToAnsi(strClasification);
                        _status.Programs++;
                      }
                    }
                  }
                }
                // get the next programme
              } while (xmlReader.ReadToNextSibling("programme"));
              //if (xmlReader != null) xmlReader.Close();

              #endregion

              #region sort & remove invalid programs. Save all valid programs

              Log.Debug("xmltvimport: Sorting TV programs");

              _status.Programs = 0;
              _status.Status = "Sorting TV programs";
              if (showProgress && ShowProgress != null) ShowProgress(_status);
              DateTime dtStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);
              //dtStartDate=dtStartDate.AddDays(-4);

              foreach (ChannelPrograms progChan in Programs)
              {
                // empty, skip it
                if (progChan.programs.Count == 0) continue;

                progChan.programs.Sort();
                progChan.programs.AlreadySorted = true;
                progChan.programs.FixEndTimes();
                progChan.programs.RemoveOverlappingPrograms(); // be sure that we do not have any overlapping

                // get the id of the channel, just get the IdChannel of the first program
                int idChannel = progChan.programs[0].IdChannel;

                if (!deleteBeforeImport)
                {
                  // retrieve all programs for this channel
                  SqlBuilder sb2 = new SqlBuilder(StatementType.Select, typeof (Program));
                  sb2.AddConstraint(Operator.Equals, "idChannel", idChannel);
                  sb2.AddOrderByField(false, "starttime");
                  SqlStatement stmt2 = sb2.GetStatement(true);
                  ProgramList dbPrograms = new ProgramList();
                  ObjectFactory.GetCollection<Program>(stmt2.Execute(), dbPrograms);
                  progChan.programs.RemoveOverlappingPrograms(dbPrograms, true);
                }

                for (int i = 0; i < progChan.programs.Count; ++i)
                {
                  Program prog = progChan.programs[i];
                  // don't import programs which have already ended...
                  if (prog.EndTime <= dtStartDate)
                  {
                    progChan.programs.RemoveAt(i);
                    i--;
                    continue;
                  }

                  DateTime start = prog.StartTime;
                  DateTime end = prog.EndTime;
                  DateTime airDate = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
                  try
                  {
                    airDate = prog.OriginalAirDate;
                    if (airDate > System.Data.SqlTypes.SqlDateTime.MinValue.Value &&
                        airDate < System.Data.SqlTypes.SqlDateTime.MaxValue.Value)
                      prog.OriginalAirDate = airDate;
                  }
                  catch (Exception)
                  {
                    Log.Info("XMLTVImport: Invalid year for OnAirDate - {0}", prog.OriginalAirDate);
                  }

                  if (prog.StartTime < _status.StartTime)
                    _status.StartTime = prog.StartTime;
                  if (prog.EndTime > _status.EndTime)
                    _status.EndTime = prog.EndTime;
                  _status.Programs++;
                  if (showProgress && ShowProgress != null && (_status.Programs % 100) == 0) ShowProgress(_status);
                }
                Log.Info("XMLTVImport: Inserting {0} programs for {1}", progChan.programs.Count.ToString(),
                         progChan.Name);
                layer.InsertPrograms(progChan.programs,
                                     deleteBeforeImport
                                       ? DeleteBeforeImportOption.OverlappingPrograms
                                       : DeleteBeforeImportOption.None, ThreadPriority.BelowNormal);
              }
            }

            #endregion

            //TVDatabase.RemoveOverlappingPrograms();

            //TVDatabase.SupressEvents = false;
            if (programIndex > 0)
            {
              _errorMessage = "File imported successfully";
              result = true;
            }
            else
              _errorMessage = "No programs found";
          }
        }
        else
        {
          _errorMessage = "No xmltv file found";
          _status.Status = _errorMessage;
          Log.Error("xmltv data file was not found");
        }
      }
      catch (Exception ex)
      {
        _errorMessage = String.Format("Invalid XML file:{0}", ex.Message);
        _status.Status = String.Format("invalid XML file:{0}", ex.Message);
        Log.Error("XML tv import error loading {0} err:{1} \n {2}", fileName, ex.Message, ex.StackTrace);

        //TVDatabase.RollbackTransaction();
      }

      Programs.Clear();
      Programs = null;

      _isImporting = false;
      //      TVDatabase.SupressEvents = false;
      if (xmlReader != null)
      {
        xmlReader.Close();
        xmlReader = null;
      }
      return result;
    }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the config file location from app config.
        /// </summary>
        private string GetConfigFileFromAppConfig(FileInfo appConfigFile)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(appConfigFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

                try
                {
                    reader.MoveToContent();

                    if (reader.ReadToDescendant("ConfigurationLocation", Namespaces.OpcUaConfig))
                    {
                        if (reader.ReadToDescendant("FilePath", Namespaces.OpcUaConfig))
                        {
                            reader.MoveToContent();
                            return reader.ReadInnerXml();
                        }
                    }

                    return null;
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
Exemplo n.º 13
0
        internal void DeserializeNetwork(string filePath)
        {
            var tempNodeCollection = new List<Node>();

            NewFile();

            // Create an reader
            using (var reader = new XmlTextReader(filePath))
            {
                reader.MoveToContent();

                var enumString = reader.GetAttribute("GraphFlowDirection");

                if (enumString != null)
                {
                    ImportFlowDirection =
                        (GraphFlowDirections) Enum.Parse(typeof (GraphFlowDirections), enumString, true);
                }


                reader.ReadToDescendant("Nodes");

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:

                            if (reader.Name != null)
                            {
                                var type = Type.GetType(reader.Name);

                                if (type == null)
                                {
                                    try // try to find type in entry assembly
                                    {
                                        var assembly = Assembly.GetEntryAssembly();
                                        type = assembly.GetTypes().FirstOrDefault(t => t.FullName == reader.Name);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex);
                                    }

                                    try // try to find type in ExternalNodeTypes
                                    {
                                        type = ExternalNodeTypes.ToArray()
                                            .FirstOrDefault(t => t.FullName == reader.Name);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex);
                                    }
                                }


                                if (type != null)
                                {
                                    if (type.IsSubclassOf(typeof (Node)))
                                    {
                                        var node = (Node) Activator.CreateInstance(type, this);
                                        node.DeserializeNetwork(reader);

                                        tempNodeCollection.Add(node);
                                    }
                                    else if (type == typeof (Connector))
                                    {
                                        Node startNode = null;
                                        Node endNode = null;

                                        var value = reader.GetAttribute("StartNode");
                                        if (value != null)
                                        {
                                            startNode =
                                                NodeCollection.FirstOrDefault(node => node.Guid == new Guid(value));
                                        }

                                        value = reader.GetAttribute("EndNode");
                                        if (value != null)
                                            endNode = NodeCollection.FirstOrDefault(node => node.Guid == new Guid(value));

                                        value = reader.GetAttribute("StartIndex");
                                        var startIndex = Convert.ToInt32(value);

                                        value = reader.GetAttribute("EndIndex");
                                        var endIndex = Convert.ToInt32(value);


                                        if (startNode != null && endNode != null)
                                        {
                                            var startPort = startNode.OutputPorts[startIndex];
                                            var endPort = endNode.InputPorts[endIndex];

                                            if (startPort != null && endPort != null)
                                            {
                                                var connector = new Connector(this, startPort, endPort);
                                                ConnectorCollection.Add(connector);
                                            }
                                        }
                                    }
                                }
                            }

                            break;
                        case XmlNodeType.Text:

                            break;
                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:

                            break;
                        case XmlNodeType.Comment:

                            break;
                        case XmlNodeType.EndElement:

                            break;
                    }
                }
            }


            foreach (var node in tempNodeCollection)
            {
                node.Show();
            }
        }
Exemplo n.º 14
0
        public override PersonalizationState LoadPersonalizationState(WebPartManager webPartManager, bool ignoreCurrentUser)
        {
            if (null == webPartManager) throw new ArgumentNullException("webPartManager is null");
            DictionaryPersonalizationState state = new DictionaryPersonalizationState(webPartManager);
            string suid = this.GetScreenUniqueIdentifier();

            Cache cache = HttpRuntime.Cache;
            lock (SyncRoot)
            {
                Dictionary<string, PersonalizationDictionary> cachedstates = cache[suid] as Dictionary<string, PersonalizationDictionary>;
                if ((this.IsEnabled && !state.ReadOnly)  || null == cachedstates)
                {
                    string storage = PersonalizationStorage.Instance.Read(XmlPersonalizationProvider.StorageKey, XmlPersonalizationProvider.StorageTemplate);
                    if (!string.IsNullOrEmpty(storage))
                    {
                        using (XmlTextReader reader = new XmlTextReader(new StringReader(storage)))
                        {
                            reader.MoveToContent();
                            if (reader.MoveToAttribute("readOnly"))
                            {
                                bool isReadOnly = false;
                                bool.TryParse(reader.Value, out isReadOnly);
                                state.ReadOnly = isReadOnly;
                                reader.MoveToElement();
                            }
                            if (reader.ReadToDescendant("part"))
                            {
                                int partDepth = reader.Depth;
                                do
                                {
                                    reader.MoveToElement();
                                    reader.MoveToAttribute("id");
                                    string id = reader.Value;
                                    PersonalizationDictionary dictionary = new PersonalizationDictionary();
                                    reader.MoveToContent();
                                    if (reader.ReadToDescendant("property"))
                                    {
                                        int propertyDepth = reader.Depth;
                                        do
                                        {
                                            reader.MoveToElement();
                                            reader.MoveToAttribute("name");
                                            string name = reader.Value;
                                            reader.MoveToAttribute("sensitive");
                                            bool sensitive = bool.Parse(reader.Value);
                                            reader.MoveToAttribute("scope");
                                            PersonalizationScope scope = (PersonalizationScope)int.Parse(reader.Value);
                                            object value = null;
                                            reader.MoveToContent();
                                            if (reader.ReadToDescendant("value"))
                                            {
                                                reader.MoveToAttribute("type");
                                                if (reader.HasValue)
                                                {
                                                    Type type = Type.GetType(reader.Value);
                                                    if (type == null && name == "Configuration")
                                                    {
                                                        type = Type.GetType("LWAS.Infrastructure.Configuration.Configuration, LWAS");
                                                    }
                                                    reader.MoveToContent();
                                                    value = SerializationServices.Deserialize(type, reader);
                                                }
                                            }
                                            dictionary.Add(name, new PersonalizationEntry(value, scope, sensitive));
                                            reader.MoveToElement();
                                            while (propertyDepth < reader.Depth && reader.Read())
                                            {
                                            }
                                        }
                                        while (reader.ReadToNextSibling("property"));
                                    }
                                    state.States.Add(id, dictionary);
                                    reader.MoveToElement();
                                    while (partDepth < reader.Depth && reader.Read())
                                    {
                                    }
                                }
                                while (reader.ReadToNextSibling("part"));
                            }
                        }
                    }

                    string fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageKey);
                    if (!PersonalizationStorage.Instance.Agent.HasKey(fileToMonitor))
                        fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageTemplate);
                    cache.Insert(suid, state.States, new CacheDependency(HttpContext.Current.Server.MapPath(fileToMonitor)));
                }
                else
                    state.States = cachedstates;
            }

            return state;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Decrpyts a security token from an XML EncryptedData 
        /// </summary>
        /// <param name="xmlToken">the XML token to decrypt</param>
        /// <returns>A byte array of the contents of the encrypted token</returns>
        private static byte[] decryptToken(string xmlToken)
        {
            int encryptionAlgorithm;
            int m_keyEncryptionAlgorithm;
            string m_keyHashAlgorithm;
            byte[] thumbprint;
            byte[] securityTokenData;
            byte[] symmetricKeyData;

            XmlReader reader = new XmlTextReader(new StringReader(xmlToken));

            // Find the EncryptionMethod element, grab the Algorithm
            if (!reader.ReadToDescendant(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace))
                throw new ArgumentException("Cannot find token EncryptedMethod.");
            encryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm).GetHashCode();

            // Find the EncryptionMethod element for the key, grab the Algorithm
            if (!reader.ReadToFollowing(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace))
                throw new ArgumentException("Cannot find key EncryptedMethod.");
            m_keyEncryptionAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm).GetHashCode();

            // Find the Digest method for the key identifier
            if (!reader.ReadToFollowing(XmlSignatureStrings.DigestMethod, XmlSignatureStrings.Namespace))
                throw new ArgumentException("Cannot find Digest Method.");
            m_keyHashAlgorithm = reader.GetAttribute(XmlEncryptionStrings.Algorithm);
            // Find the key identifier
            if (!reader.ReadToFollowing(WSSecurityStrings.KeyIdentifier, WSSecurityStrings.Namespace))
                throw new ArgumentException("Cannot find Key Identifier.");
            reader.Read();
            thumbprint = Convert.FromBase64String(reader.ReadContentAsString());

            // Find the encrypted Symmetric Key
            if (!reader.ReadToFollowing(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace))
                throw new ArgumentException("Cannot find symmetric key.");
            reader.Read();
            symmetricKeyData = Convert.FromBase64String(reader.ReadContentAsString());

            // Find the encrypted Security Token
            if (!reader.ReadToFollowing(XmlEncryptionStrings.CipherValue, XmlEncryptionStrings.Namespace))
                throw new ArgumentException("Cannot find encrypted security token.");
            reader.Read();
            securityTokenData = Convert.FromBase64String(reader.ReadContentAsString());

            reader.Close();

            SymmetricAlgorithm alg = null;
            X509Certificate2 certificate = FindCertificate(thumbprint);

            foreach (int i in Aes)
                if (encryptionAlgorithm == i)
                {
                    alg = new RijndaelManaged();
                    break;
                }
            if (null == alg)
                foreach (int i in TripleDes)
                    if (encryptionAlgorithm == i)
                    {
                        alg = new TripleDESCryptoServiceProvider();
                        break;
                    }

            if (null == alg)
                throw new ArgumentException("Could not determine Symmetric Algorithm");
            alg.Key = (certificate.PrivateKey as RSACryptoServiceProvider).Decrypt(symmetricKeyData, true); ;
            int ivSize = alg.BlockSize / 8;
            byte[] iv = new byte[ivSize];
            Buffer.BlockCopy(securityTokenData, 0, iv, 0, iv.Length);
            alg.Padding = PaddingMode.ISO10126;
            alg.Mode = CipherMode.CBC;
            ICryptoTransform decrTransform = alg.CreateDecryptor(alg.Key, iv);
            byte[] plainText = decrTransform.TransformFinalBlock(securityTokenData, iv.Length, securityTokenData.Length - iv.Length);
            decrTransform.Dispose();
            return plainText;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Reads the formatted XML document, supplying information about the DBC file to read.
        /// </summary>
        /// <param name="xmlStream">A stream containing the XML document.</param>
        void readXml(Stream xmlStream)
        {
            //-- Create a new XmlTextReader 
            XmlTextReader xml = new XmlTextReader(xmlStream);

            //-- Move to the content
            xml.MoveToContent();

            xml.ReadToDescendant("field_count");
            int fieldCount = int.Parse(xml.ReadElementContentAsString());
            columns = new DBCDataColumn[fieldCount];

            //-- Move to the 'fields' node
            bool found = false;
            while (xml.Read() && !found)
            {
                if (xml.LocalName == "fields")
                    break;
            }

            int index = 0;
            while (xml.Read())
            {
                if (xml.NodeType == XmlNodeType.Element)
                {
                    // Check if this node is a 'field' element
                    if (xml.LocalName != "field")
                        break;

                    // Try retrieving the column's name
                    string fieldName = null;
                    try { fieldName = xml.GetAttribute("name"); }
                    catch
                    {
                        throw new DBCException("Couldn't parse field attribute 'name' (" + xml.LineNumber + ", " + xml.LinePosition + ").");
                    }

                    // Try parsing the column's type
                    Type fieldType = null;
                    try {  fieldType = parseXMLType(xml.GetAttribute("type")); }
                    catch
                    {
                        throw new DBCException("Couldn't parse field attribute 'type' (" + xml.LineNumber + ", " + xml.LinePosition + ").");
                    }

                    // Check if this column name has already been taken
                    if (doesColumnNameExist(fieldName))
                        throw new DBCException("Ambigious field name '" + fieldName + "' (" + xml.LineNumber + ", " + xml.LinePosition + ").");

                    // Set this column with the associating information
                    columns[index] = new DBCDataColumn(fieldName, fieldType, fieldType == typeof(string));

                    // Increase the column pointer
                    index++;
                }       
            }
        }
Exemplo n.º 17
0
    /// <summary>
    /// Reads all the channels from a tvguide.xml file
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    private List<Channel> readTVGuideChannelsFromFile(String tvguideFilename)
    {
      List<Channel> channels = new List<Channel>();
      XmlTextReader xmlReader = new XmlTextReader(tvguideFilename);

      int iChannel = 0;

      try
      {
        if (xmlReader.ReadToDescendant("tv"))
        {
          // get the first channel
          if (xmlReader.ReadToDescendant("channel"))
          {
            do
            {
              String id = xmlReader.GetAttribute("id");
              if (id == null || id.Length == 0)
              {
                Log.Error("  channel#{0} doesnt contain an id", iChannel);
              }
              else
              {
                // String displayName = null;

                XmlReader xmlChannel = xmlReader.ReadSubtree();
                xmlChannel.ReadStartElement(); // read channel
                // now, xmlChannel is positioned on the first sub-element of <channel>
                List<string> displayNames = new List<string>();

                while (!xmlChannel.EOF)
                {
                  if (xmlChannel.NodeType == XmlNodeType.Element)
                  {
                    switch (xmlChannel.Name)
                    {
                      case "display-name":
                      case "Display-Name":
                        displayNames.Add(xmlChannel.ReadString());
                        //else xmlChannel.Skip();
                        break;
                        // could read more stuff here, like icon...
                      default:
                        // unknown, skip entire node
                        xmlChannel.Skip();
                        break;
                    }
                  }
                  else
                    xmlChannel.Read();
                }
                foreach (string displayName in displayNames)
                {
                  if (displayName != null)
                  {
                    Channel channel = new Channel(false, false, -1, new DateTime(), false, new DateTime(),
                                                  -1, false, id, displayName);
                    channels.Add(channel);
                  }
                }
              }
              iChannel++;
            } while (xmlReader.ReadToNextSibling("channel"));
          }
        }
      }
      catch {}
      finally
      {
        if (xmlReader != null)
        {
          xmlReader.Close();
          xmlReader = null;
        }
      }

      return channels;
    }
 private void CountSongs ()
 {
     using (var xml_reader = new XmlTextReader (data.library_uri)) {
         xml_reader.ReadToDescendant("dict");
         xml_reader.ReadToDescendant("dict");
         xml_reader.ReadToDescendant("dict");
         do {
             data.total_songs++;
         } while (xml_reader.ReadToNextSibling ("dict"));
     }
 }
Exemplo n.º 19
0
        private void okButton_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(packageInputPath.Text))
            {
                MessageBox.Show("Your input directory does not exist. Please select a different one.", "Convert Project", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!Directory.Exists(outputDirectory.Text))
                Directory.CreateDirectory(outputDirectory.Text);

            // Make sure the user knows we're busy...
            System.Threading.Thread.Sleep(100);
            cvWorking.Visible = true;

            modEditor me = new modEditor();
            Dictionary<string, string> details = Classes.ModParser.parsePackageInfo(packageInfoXMLPath.Text);
            me.generateSQL(outputDirectory.Text, true, details);

            // Update a setting.
            string updatesql = "UPDATE settings SET value = \"false\" WHERE key = \"autoGenerateModID\"";
            SQLiteCommand ucomm = new SQLiteCommand(updatesql, me.conn);
            ucomm.ExecuteNonQuery();

            // Create a readme.txt if the text is inline.
            bool readmeTextInline = (readmeTXTPath.Text == "Inline");

            // Parse the XML.
            #region Read the install.xml, if it exists.
            if (File.Exists(installXmlPath.Text))
            {
                XmlTextReader xmldoc = new XmlTextReader(installXmlPath.Text);
                xmldoc.DtdProcessing = DtdProcessing.Ignore;
                string currfile = "";
                string sql = "INSERT INTO instructions(id, before, after, type, file, optional) VALUES(null, @beforeText, @afterText, @type, @fileEdited, @optional)";

                while (xmldoc.Read())
                {
                    if (xmldoc.NodeType.Equals(XmlNodeType.Element))
                    {
                        switch (xmldoc.LocalName)
                        {
                            case "file":
                                currfile = xmldoc.GetAttribute("name");
                                break;

                            case "operation":
                                SQLiteCommand command = new SQLiteCommand(sql, me.conn);
                                command.Parameters.AddWithValue("@fileEdited", currfile);
                                command.Parameters.AddWithValue("@optional", (xmldoc.GetAttribute("error") == "skip"));

                                xmldoc.ReadToDescendant("search");
                                command.Parameters.AddWithValue("@type", xmldoc.GetAttribute("position"));
                                command.Parameters.AddWithValue("@beforeText", xmldoc.ReadElementContentAsString().Replace("\r", "\n").Replace("\n", "\r\n"));

                                xmldoc.ReadToNextSibling("add");
                                command.Parameters.AddWithValue("@afterText", xmldoc.ReadElementContentAsString().Replace("\r", "\n").Replace("\n", "\r\n"));

                                command.ExecuteNonQuery();
                                break;
                        }
                    }
                }
            }
            #endregion

            // Copy over any remaining files.
            Dictionary<string, string> pfiles = new Dictionary<string, string>();
            Directory.CreateDirectory(outputDirectory.Text + "/Package");
            Directory.CreateDirectory(outputDirectory.Text + "/Source");

            pfiles.Add("Package/package-info.xml", packageInfoXMLPath.Text);
            if (!string.IsNullOrEmpty(readmeTXTPath.Text))
                pfiles.Add("Package/readme.txt", readmeTXTPath.Text);
            if (!string.IsNullOrEmpty(installPHPPath.Text))
                pfiles.Add("Package/install.php", installPHPPath.Text);
            if (!string.IsNullOrEmpty(uninstallPHPPath.Text))
                pfiles.Add("Package/uninstall.php", uninstallPHPPath.Text);
            if (!string.IsNullOrEmpty(installDatabasePHPPath.Text))
                pfiles.Add("Package/installDatabase.php", installDatabasePHPPath.Text);
            if (!string.IsNullOrEmpty(uninstallDatabasePHPPath.Text))
                pfiles.Add("Package/uninstallDatabase.php", uninstallDatabasePHPPath.Text);

            foreach (var pair in pfiles)
            {
                if (!File.Exists(pair.Value))
                    continue;

                if (File.Exists(outputDirectory.Text + "/" + pair.Key))
                    File.Delete(outputDirectory.Text + "/" + pair.Key);

                File.Copy(pair.Value, outputDirectory.Text + "/" + pair.Key);
            }

            #region Read the package.xml, if it exists, for any further information.

            if (File.Exists(packageInfoXMLPath.Text))
            {
                XmlDocument l_document = new XmlDocument();
                l_document.Load(packageInfoXMLPath.Text);

                SQLiteCommand sql;
                string sqlquery;
                foreach (XmlNode l_packageNode in l_document.LastChild.ChildNodes)
                {
                    Console.WriteLine("Test node name: " + l_packageNode.Name);
                    if (l_packageNode.Name == "install")
                    {
                        foreach (XmlNode l_operationNode in l_packageNode.ChildNodes)
                        {
                            Console.WriteLine("Test child node name: " + l_operationNode.Name);
                            switch (l_operationNode.Name)
                            {
                                case "readme":
                                    if (readmeTextInline)
                                        File.WriteAllText(outputDirectory.Text + "/Package/readme.txt", l_operationNode.InnerText.Replace("\r", "\n").Replace("\n", "\r\n"));
                                    break;
                                case "require-file":
                                     Console.WriteLine("File name: " + l_operationNode.Attributes["name"].Value);
                                     Console.WriteLine("Destination: " + l_operationNode.Attributes["destination"].Value);
                                     string[] pieces = l_operationNode.Attributes["name"].Value.Split('/');
                                     string lastpiece = pieces[pieces.Length - 1];

                                     if (!Directory.Exists(outputDirectory.Text + "/Source/" + l_operationNode.Attributes["name"].Value.Replace("/" + lastpiece, "")) && l_operationNode.Attributes["name"].Value != lastpiece)
                                         Directory.CreateDirectory(outputDirectory.Text + "/Source/" + l_operationNode.Attributes["name"].Value.Replace("/" + lastpiece, ""));

                                     File.Copy(packageInputPath.Text + "/" + l_operationNode.Attributes["name"].Value, outputDirectory.Text + "/Source/" + l_operationNode.Attributes["name"].Value, true);
                                     Console.WriteLine("Copied file");

                                    // Set up a query.
                                     sqlquery = "INSERT INTO files(id, file_name, destination) VALUES(null, @fileName, @destination)";
                                     sql = new SQLiteCommand(sqlquery, me.conn);

                                     sql.Parameters.AddWithValue("@fileName", l_operationNode.Attributes["name"].Value);
                                     sql.Parameters.AddWithValue("@destination", l_operationNode.Attributes["destination"].Value);

                                     sql.ExecuteNonQuery();

                                     break;
                                case "require-dir":
                                    // Just copy over the dir.
                                     DirectoryCopy(packageInputPath.Text + "/" + l_operationNode.Attributes["name"].Value, outputDirectory.Text + "/Source/" + l_operationNode.Attributes["name"].Value, true);

                                     // Set up a query.
                                     sqlquery = "INSERT INTO files(id, file_name, destination) VALUES(null, @fileName, @destination)";
                                     sql = new SQLiteCommand(sqlquery, me.conn);

                                     sql.Parameters.AddWithValue("@fileName", l_operationNode.Attributes["name"].Value);
                                     sql.Parameters.AddWithValue("@destination", l_operationNode.Attributes["destination"].Value);

                                     sql.ExecuteNonQuery();
                                    break;
                            }
                        }
                    }
                    if (l_packageNode.Name == "uninstall")
                    {
                        foreach (XmlNode l_operationNode in l_packageNode.ChildNodes)
                        {
                            switch (l_operationNode.Name)
                            {
                                case "remove-file":
                                    sqlquery = "INSERT INTO files_delete(id, file_name, type) VALUES(null, @fileName, @type)";
                                    sql = new SQLiteCommand(sqlquery, me.conn);
                                    sql.Parameters.AddWithValue("@fileName", l_operationNode.Attributes["name"].Value);
                                    sql.Parameters.AddWithValue("@type", "file");
                                    sql.ExecuteNonQuery();
                                    break;

                                case "remove-dir":
                                    sqlquery = "INSERT INTO files_delete(id, file_name, type) VALUES(null, @fileName, @type)";
                                    sql = new SQLiteCommand(sqlquery, me.conn);
                                    sql.Parameters.AddWithValue("@fileName", l_operationNode.Attributes["name"].Value);
                                    sql.Parameters.AddWithValue("@type", "dir");
                                    sql.ExecuteNonQuery();
                                    break;
                            }
                        }
                    }
                }
            }
            #endregion

            me.Close();

            DialogResult result = MessageBox.Show("The package has been converted, do you want to load it now?", "Converting Project", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
                ModBuilder.Classes.PackageWorker.bootstrapLoad(outputDirectory.Text);
            Close();
        }
Exemplo n.º 20
0
 private static string GetDefinition(string word, string serviceCode, string langGuid)
 {
     StringBuilder stringBuilder = new StringBuilder();
     try
     {
         OfficeResearch officeResearch = new OfficeResearch();
         officeResearch.Url = url;
         string q = string.Format(_queryXml, word, serviceCode, langGuid);
         string s = officeResearch.Query(q);
         XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(s));
         xmlTextReader.WhitespaceHandling = WhitespaceHandling.Significant;
         if (xmlTextReader.ReadToDescendant("Content"))
         {
             XmlReader xmlReader = xmlTextReader.ReadSubtree();
             while (xmlReader.Read())
             {
                 string name;
                 if ((name = xmlReader.Name) != null)
                 {
                     if (name == "Heading" || name == "Line" || name == "P")
                     {
                         stringBuilder.AppendLine();
                         continue;
                     }
                     if (name == "Char" || name == "Text")
                     {
                         if (xmlReader.NodeType == XmlNodeType.Element)
                         {
                             stringBuilder.Append(" ");
                             continue;
                         }
                         continue;
                     }
                 }
                 if (xmlReader.NodeType == XmlNodeType.Text)
                 {
                     stringBuilder.Append(xmlReader.Value);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
     return stringBuilder.ToString();
 }
		static IEnumerable<TagPrefixInfo> GetRegistrationTags (XmlTextReader reader)
		{
			reader.WhitespaceHandling = WhitespaceHandling.None;
			reader.MoveToContent();
			
			if (reader.Name == "configuration"
			    && reader.ReadToDescendant ("system.web") && reader.NodeType == XmlNodeType.Element
			    && reader.ReadToDescendant ("pages") && reader.NodeType == XmlNodeType.Element
			    && reader.ReadToDescendant ("controls") && reader.NodeType == XmlNodeType.Element
			    && reader.ReadToDescendant ("add") && reader.NodeType == XmlNodeType.Element)
			{
				do {
					if (reader.MoveToAttribute ("tagPrefix")) {
						string prefix = reader.Value;
						
						//assemblies
						if (reader.MoveToAttribute ("namespace")) {
							string _namespace = reader.Value;
							string _assembly = reader.MoveToAttribute ("assembly")? reader.Value : null;
							yield return new TagPrefixInfo (prefix, _namespace, _assembly, null, null);
						}
						
						//user controls
						if (reader.MoveToAttribute ("tagName")) {
							string tagName = reader.Value;
							string src = reader.MoveToAttribute ("src")? reader.Value : null;
							yield return new TagPrefixInfo (prefix, null, null, tagName, src);
						}
					}
				} while (reader.ReadToNextSibling ("add"));
			};
		}
        /// <summary>
        /// Load a previous session from a predefined configuration file
        /// </summary>
        private void LoadSession()
        {
            FileStream fs=null;
            try
            {   //try to open the file and return if the open fails
                fs = new FileStream("config.xml", FileMode.Open);
            }
            catch{
                return;
            }
            try
            {
                XmlTextReader reader = new XmlTextReader(fs);

                reader.ReadToFollowing("Servers");
                reader.ReadToDescendant("Server");
                do
                {   //read connection string for each server and try to add it to the program
                    reader.ReadToDescendant("String");
                    ServerManager newman = new ServerManager(reader.ReadElementString("String"));
                    try
                    {
                        AddServer(newman);
                    }
                    catch { }

                    //add saved rules to the server
                    while (reader.Name == "Rule")
                    {
                        Rule newRule = newman.RuleMan.AddRule(reader.ReadElementString("Rule"));
                        newRule.SetPriority(int.Parse(reader.ReadElementString("Priority")));
                    }

                } while (reader.ReadToFollowing("Server"));
            }
            catch
            {//unfortunately an error in the configuration file may cancel loading any data after that point
             //will figure this out when more familiar with parsing XML files, probably should use DOM, oh well
            }
            finally
            {
                fs.Close();
            }
        }
Exemplo n.º 23
0
        public void Load()
        {
            using (SpreadsheetDocument xlPackage = SpreadsheetDocument.Open(_filename, false))
            {
                WorkbookPart workbook = xlPackage.WorkbookPart;

                _workbook = LoadWorkbookDOM(workbook);

                Dictionary<string, string> allParameters = LoadDefinedFundParameterNames(_workbook);

                Dictionary<string, HashSet<string>> cellsByTable = new Dictionary<string, HashSet<string>>();

                foreach (string k in allParameters.Keys)
                {
                    string range = allParameters[k];

                    string[] rangeParts = range.Split('!');

                    string table = rangeParts[0];
                    string cellinfo = rangeParts[1];

                    if (!cellsByTable.ContainsKey(table))
                    {
                        cellsByTable.Add(table, new HashSet<string>());
                    }

                    HashSet<string> cellsToLookFor = cellsByTable[table];

                    if (cellinfo.Contains(":"))
                    {
                        string[] cells = cellinfo.Split(':');

                        string startcell = cells[0].Replace("$", "");
                        string endcell = cells[1].Replace("$", "");

                        int startcellrowindex = startcell.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        string startcellcol = startcell.Substring(0, startcellrowindex);
                        string startcellrow = startcell.Substring(startcellrowindex);

                        int endcellrowindex = endcell.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        string endcellcol = endcell.Substring(0, endcellrowindex);
                        string endcellrow = endcell.Substring(endcellrowindex);

                        if (startcellrow != endcellrow && startcellcol != endcellcol)
                        {
                            List<string> columns = new List<string>(EnumerateExcelColRange(startcellcol, endcellcol));

                            foreach (string column in columns)
                            {
                                for (int i = Convert.ToInt32(startcellrow); i <= Convert.ToInt32(endcellrow); i++)
                                {
                                    cellsToLookFor.Add(column + i.ToString());
                                }
                            }
                        }
                        else if (startcellrow == endcellrow)
                        {
                            foreach (string s in EnumerateExcelColRange(startcellcol, endcellcol))
                            {
                                cellsToLookFor.Add(s + startcellrow);
                            }

                        }
                        else if (startcellcol == endcellcol)
                        {
                            for (int i = Convert.ToInt32(startcellrow); i <= Convert.ToInt32(endcellrow); i++)
                            {
                                cellsToLookFor.Add(startcellcol + i.ToString());

                            }
                        }
                    }
                    else
                    {
                        cellsToLookFor.Add(cellinfo.Replace("$", ""));
                    }

                }

                const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
                const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

                LoadSheets(workbook, allParameters);

                Dictionary<string, Dictionary<string, string>> allNeededValues = new Dictionary<string, Dictionary<string, string>>();

                Dictionary<int, List<KeyValuePair<string, string>>> thingsThatNeedToBeLoadedFromTheStringTable = new Dictionary<int, List<KeyValuePair<string, string>>>();

                foreach (string sheetname in _sheets.Keys)
                {
                    allNeededValues.Add(sheetname, new Dictionary<string, string>());
                    Dictionary<string, string> currentAllNeededValues = allNeededValues[sheetname];

                    HashSet<string> currentCellsToLookFor = cellsByTable[sheetname];

                    //  Return the value of the specified cell.

                    //  Create a namespace manager, so you can search.
                    //  Add a prefix (d) for the default namespace.
                    NameTable nt = new NameTable();
                    XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
                    nsManager.AddNamespace("d", worksheetSchema);

                    using (XmlTextReader r = new XmlTextReader(_sheets[sheetname].GetStream(FileMode.Open, FileAccess.Read), nt))
                    {
                        while (r.Read())
                        {
                            if (r.NodeType == XmlNodeType.Element && r.Name == "c")
                            {
                                string cellReference = r.GetAttribute("r");
                                if (currentCellsToLookFor.Contains(cellReference))
                                {
                                    string cellType = r.GetAttribute("t");

                                    if (r.ReadToDescendant("v"))
                                    {
                                        string cellValue = r.ReadElementContentAsString();

                                        if (cellType != "s")
                                        {
                                            currentAllNeededValues.Add(cellReference, cellValue);
                                        }
                                        else
                                        {
                                            int stringTableIndex = Convert.ToInt32(cellValue);
                                            if (!thingsThatNeedToBeLoadedFromTheStringTable.ContainsKey(stringTableIndex))
                                            {
                                                thingsThatNeedToBeLoadedFromTheStringTable.Add(stringTableIndex, new List<KeyValuePair<string, string>>());
                                            }
                                            thingsThatNeedToBeLoadedFromTheStringTable[stringTableIndex].Add(new KeyValuePair<string, string>(sheetname, cellReference));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //  Create a namespace manager, so you can search.
                //  Add a prefix (d) for the default namespace.
                NameTable nts = new NameTable();
                XmlNamespaceManager nsManager2 = new XmlNamespaceManager(nts);
                nsManager2.AddNamespace("s", sharedStringSchema);

                using (XmlTextReader r = new XmlTextReader(workbook.SharedStringTablePart.GetStream(FileMode.Open, FileAccess.Read), nts))
                {
                    int currentStringTableIndex = -1;
                    while (r.Read())
                    {
                        if (r.NodeType == XmlNodeType.Element && r.Name == "si")
                        {
                            currentStringTableIndex++;

                            if (thingsThatNeedToBeLoadedFromTheStringTable.ContainsKey(currentStringTableIndex))
                            {
                                if (r.ReadToDescendant("t"))
                                {
                                    string cellValue = r.ReadElementContentAsString();
                                    foreach (KeyValuePair<string, string> tt in thingsThatNeedToBeLoadedFromTheStringTable[currentStringTableIndex])
                                    {
                                        allNeededValues[tt.Key].Add(tt.Value, cellValue);
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (string k in allParameters.Keys)
                {
                    string range = allParameters[k];

                    string[] rangeParts = range.Split('!');

                    string table = rangeParts[0];
                    string cellinfo = rangeParts[1];

                    if (cellinfo.Contains(":"))
                    {
                        string[] cells = cellinfo.Split(':');

                        string startcell = cells[0].Replace("$", "");
                        string endcell = cells[1].Replace("$", "");

                        int startcellrowindex = startcell.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        string startcellcol = startcell.Substring(0, startcellrowindex);
                        string startcellrow = startcell.Substring(startcellrowindex);

                        int endcellrowindex = endcell.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
                        string endcellcol = endcell.Substring(0, endcellrowindex);
                        string endcellrow = endcell.Substring(endcellrowindex);

                        if (startcellrow != endcellrow && startcellcol != endcellcol)
                        {
                            List<string> columns = new List<string>(EnumerateExcelColRange(startcellcol, endcellcol));

                            string[,] data = new string[Convert.ToInt32(endcellrow) - Convert.ToInt32(startcellrow) + 1, columns.Count];

                            foreach (string column in columns)
                            {
                                for (int i = Convert.ToInt32(startcellrow); i <= Convert.ToInt32(endcellrow); i++)
                                {
                                    data[i - Convert.ToInt32(startcellrow), columns.IndexOf(column)] = allNeededValues[table][column + i.ToString()];
                                }
                            }

                            TwoDimensionalParameter p = new TwoDimensionalParameter(data);

                            string nameAndType = k.Substring(5);

                            if (nameAndType.Contains("."))
                            {
                                int indexOfNameTypeSeperator = nameAndType.IndexOf('.');
                                p.Name = nameAndType.Substring(0, indexOfNameTypeSeperator);
                                p.Type = nameAndType.Substring(indexOfNameTypeSeperator + 1);
                            }
                            else
                            {
                                p.Name = nameAndType;
                                p.Type = null;
                            }

                            _parameters.Add(p);
                        }
                        else if (startcellrow == endcellrow)
                        {
                            List<string> data = new List<string>();

                            foreach (string s in EnumerateExcelColRange(startcellcol, endcellcol))
                            {
                                string v = allNeededValues[table][s + startcellrow];
                                data.Add(v);
                            }

                            OneDimensionalParameter p = new OneDimensionalParameter(data);

                            string nameAndType = k.Substring(5);

                            if (nameAndType.Contains("."))
                            {
                                int indexOfNameTypeSeperator = nameAndType.IndexOf('.');
                                p.Name = nameAndType.Substring(0, indexOfNameTypeSeperator);
                                p.Type = nameAndType.Substring(indexOfNameTypeSeperator + 1);
                            }
                            else
                            {
                                p.Name = nameAndType;
                                p.Type = null;
                            }

                            _parameters.Add(p);

                        }
                        else if (startcellcol == endcellcol)
                        {
                            List<string> data = new List<string>();

                            for (int i = Convert.ToInt32(startcellrow); i <= Convert.ToInt32(endcellrow); i++)
                            {
                                string v = allNeededValues[table][startcellcol + i.ToString()];
                                data.Add(v);
                            }

                            OneDimensionalParameter p = new OneDimensionalParameter(data);

                            string nameAndType = k.Substring(5);

                            if (nameAndType.Contains("."))
                            {
                                int indexOfNameTypeSeperator = nameAndType.IndexOf('.');
                                p.Name = nameAndType.Substring(0, indexOfNameTypeSeperator);
                                p.Type = nameAndType.Substring(indexOfNameTypeSeperator + 1);
                            }
                            else
                            {
                                p.Name = nameAndType;
                                p.Type = null;
                            }

                            _parameters.Add(p);
                        }
                    }
                    else
                    {
                        NonDimensionalParameter p = new NonDimensionalParameter();

                        string nameAndType = k.Substring(5);

                        if (nameAndType.Contains("."))
                        {
                            int indexOfNameTypeSeperator = nameAndType.IndexOf('.');
                            p.Name = nameAndType.Substring(0, indexOfNameTypeSeperator);
                            p.Type = nameAndType.Substring(indexOfNameTypeSeperator + 1);
                        }
                        else
                        {
                            p.Name = nameAndType;
                            p.Type = null;
                        }

                        p.Value = allNeededValues[table][cellinfo.Replace("$", "")];

                        _parameters.Add(p);
                    }
                }
            }
        }
Exemplo n.º 24
0
        private void _loadConfig(string sectionName)
        {
            if (File.Exists(FilePath))
            {
                try
                {
                    using (XmlTextReader xtrReader = new XmlTextReader(FilePath))
                    {
                        xtrReader.ReadToFollowing(sectionName);

                        while (xtrReader.ReadToFollowing("setting"))
                        {
                            string sAttributeName = xtrReader.GetAttribute("name");
                            xtrReader.ReadToDescendant("value");
                            string sValue = xtrReader.ReadElementContentAsString();
                            Config.Add(sAttributeName, sValue);
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemplo n.º 25
0
        public GLFontData LoadGLFont(string a_szFontDataFile)
        {
            // safty checks:
            if (a_szFontDataFile == null)
            {
                return null;
            }
            else if (a_szFontDataFile == "")
            {
                return null;
            }

            // next we see if this string has been gend already:
            GLFontData oFontData;
            if (m_dicGLFonts.TryGetValue(a_szFontDataFile, out oFontData))
            {
                oFontData.m_uiUseCount++;
                return oFontData;
            }
            oFontData = new GLFontData();

            // We have not loaded the font before so, set up new one:
            oFontData.m_szDataFile = a_szFontDataFile;      // Set Data File path.
            oFontData.m_uiUseCount = 1;

            // Create some Working Vars and Buffers:
            string szTextureFile = "";
            string szBuffer;
            char cBuffer = ' ';

            // first load in XML file.
            XmlTextReader oXMLReader = new XmlTextReader(a_szFontDataFile);

            try
            {
                // Get Texture path:
                if (oXMLReader.ReadToNextSibling("Font")) // works on windows.
                {
                    szTextureFile = oXMLReader.GetAttribute("texture");
                }
                else if (oXMLReader.ReadToDescendant("Font")) // works on linux!
                {
                    szTextureFile = oXMLReader.GetAttribute("texture");
                }
                else
                {
#if LOG4NET_ENABLED
                    logger.Error("Couldn't find texture path for " + a_szFontDataFile);
#endif
                }

                // Move to first Charecter element
                oXMLReader.ReadToDescendant("Character");

                // Loop through all Char elements and get out UV coords for each charcter, save them to the Dic.
                do
                {
                    /// <summary>
                    /// All of the System.Globalization stuff is due ot the fact that the default float.TryParse behaves differently on different computers. thanks microsoft.
                    /// </summary>

                    GLFontData.UVCoords oUVCoords = new GLFontData.UVCoords();

                    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

                    float minX = 0.0f, minY = 0.0f, maxX = 0.0f, maxY = 0.0f;

                    szBuffer = oXMLReader.GetAttribute("Umin");
                    bool r1 = float.TryParse(szBuffer, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out minX);

                    //bool r1 = float.TryParse(szBuffer, out minX);

                    szBuffer = oXMLReader.GetAttribute("Umax");
                    bool r2 = float.TryParse(szBuffer, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out maxX);

                    //bool r2 = float.TryParse(szBuffer, out maxX);


                    szBuffer = oXMLReader.GetAttribute("Vmin");
                    bool r3 = float.TryParse(szBuffer, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out minY);

                    //bool r3 = float.TryParse(szBuffer, out minY);


                    szBuffer = oXMLReader.GetAttribute("Vmax");
                    bool r4 = float.TryParse(szBuffer, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out maxY);

                    //bool r4 = float.TryParse(szBuffer, out maxY);

                    oUVCoords.m_v2UVMin.X = minX;
                    oUVCoords.m_v2UVMax.X = maxX;
                    oUVCoords.m_v2UVMin.Y = minY;
                    oUVCoords.m_v2UVMax.Y = maxY;


                    szBuffer = oXMLReader.GetAttribute("Char");
                    foreach (char c in szBuffer)
                    {
                        cBuffer = c;
                    }
                    oFontData.m_dicCharMap.Add(cBuffer, oUVCoords);

                    if (r1 == false || r2 == false || r3 == false || r4 == false)
                    {
#if LOG4NET_ENABLED
                        logger.Info("ResourceManager.cs Char: " + szBuffer + " Coordinates: " + oUVCoords.m_v2UVMin.X + "/" + oUVCoords.m_v2UVMin.Y + "," + oUVCoords.m_v2UVMax.X + "/" + oUVCoords.m_v2UVMax.Y +
                                    "|" + r1 + " " + r2 + " " + r3 + " " + r4);
#endif
                    }

                } while (oXMLReader.ReadToNextSibling("Character"));  // Move to Next Charcter Element

#if LOG4NET_ENABLED
                logger.Info("Loaded GLFont Data File " + a_szFontDataFile);
#endif
            }
            catch (XmlException e)
            {
                // XML Error occured, catch and log.
#if LOG4NET_ENABLED
                logger.Error("Error: faild to load Font Data file " + a_szFontDataFile);
                logger.Error("Font Exception: " + e.Message);
                logger.Info("You May have an unsupported Charcter in thoe font data file, inclundg <, >, &");
#endif
            }
            finally
            {
                // Close the XMl file.
                oXMLReader.Close();
            }

            // load font texture.
            oFontData.m_uiTextureID = Helpers.ResourceManager.Instance.LoadTexture(szTextureFile);

            // Add to list of loaded fonts:
            if (!m_dicGLFonts.ContainsKey(oFontData.m_szDataFile)){
                m_dicGLFonts.Add(oFontData.m_szDataFile, oFontData);
            }

            return oFontData;
        }
Exemplo n.º 26
0
        /* Read all el 2a7dees al nabawaya and fill the treeview */
        private void LoadHadeethTree()
        {
            /* Check first if the tree was already loaded*/
            if (trvHadeeth.Nodes.Count > 0) return;

            XmlTextReader xmlReader;
            TreeNode rNode, bNode;

            for (int i = 0; i < 6; i++) {

                /* Check if the file exists first*/
                if (!File.Exists(hadeeth_xml[i])) continue;
                xmlReader = new XmlTextReader(hadeeth_xml[i]);
                xmlReader.ReadToFollowing("kotob");
                rNode = new TreeNode(xmlReader.GetAttribute(0));

                xmlReader.ReadToFollowing("katab");
                do {
                    xmlReader.MoveToFirstAttribute();
                    bNode = new TreeNode(xmlReader.ReadContentAsString());
                    xmlReader.MoveToElement();
                    if (xmlReader.ReadToDescendant("bab")) {
                        /* iterate through el babs in el katab if there are any */
                        do {
                            xmlReader.MoveToAttribute(0);
                            bNode.Nodes.Add(xmlReader.ReadContentAsString());
                        } while (xmlReader.ReadToNextSibling("bab"));
                    }
                    rNode.Nodes.Add(bNode);
                } while (xmlReader.ReadToFollowing("katab"));

                trvHadeeth.Nodes.Add(rNode);

            }
        }
        /// <summary>
        /// Exports the security configuration for an application identified by a file or url.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The security configuration.</returns>
        public SecuredApplication ReadConfiguration(string filePath)
        {
            if (filePath == null) throw new ArgumentNullException("filePath");

            string configFilePath = filePath;
            string exeFilePath = null;

            // check for valid file.
            if (!File.Exists(filePath))
            {
                throw ServiceResultException.Create(
                    StatusCodes.BadNotReadable,
                    "Cannot find the executable or configuration file: {0}",
                    filePath);
            }

            // find the configuration file for the executable.
            if (filePath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
            {
                exeFilePath = filePath;

                try
                {
                    FileInfo file = new FileInfo(filePath);
                    string sectionName = file.Name;
                    sectionName = sectionName.Substring(0, sectionName.Length - file.Extension.Length);

                    System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(filePath);

                    configFilePath = ApplicationConfiguration.GetFilePathFromAppConfig(sectionName);

                    if (configFilePath == null)
                    {
                        configFilePath = filePath + ".config";
                    }
                }
                catch (Exception e)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadNotReadable,
                        e,
                        "Cannot find the configuration file for the executable: {0}",
                        filePath);
                }
                
                if (!File.Exists(configFilePath))
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadNotReadable,
                        "Cannot find the configuration file: {0}",
                        configFilePath);
                }
            }

            SecuredApplication application = null;
            ApplicationConfiguration applicationConfiguration = null;
            
            try
            {
                XmlTextReader reader = new XmlTextReader(File.Open(configFilePath, FileMode.Open, FileAccess.Read));

                try
                {
                    reader.MoveToContent();

                    // find the SecuredApplication element in the file.
                    if (reader.ReadToDescendant("SecuredApplication", Namespaces.OpcUaSecurity))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(SecuredApplication));
                        application = serializer.ReadObject(reader, false) as SecuredApplication;

                        application.ConfigurationFile = configFilePath;
                        application.ExecutableFile = exeFilePath;
                    }

                    // load the application configuration.
                    else
                    {
                        reader.Close();
                        reader = new XmlTextReader(File.Open(configFilePath, FileMode.Open, FileAccess.Read));
                        DataContractSerializer serializer = new DataContractSerializer(typeof(ApplicationConfiguration));
                        applicationConfiguration = serializer.ReadObject(reader, false) as ApplicationConfiguration;
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                throw ServiceResultException.Create(
                    StatusCodes.BadNotReadable,
                    e,
                    "Cannot load the configuration file: {0}",
                    filePath);
            }

            // check if security info store on disk.
            if (application != null)
            {
                return application;
            }
            
            application = new SecuredApplication();

            // copy application info.
            application.ApplicationName = applicationConfiguration.ApplicationName;
            application.ApplicationUri = applicationConfiguration.ApplicationUri;
            application.ProductName = applicationConfiguration.ProductUri;
            application.ApplicationType = (ApplicationType)(int)applicationConfiguration.ApplicationType;
            application.ConfigurationFile = configFilePath;
            application.ExecutableFile = exeFilePath;
            application.ConfigurationMode = "http://opcfoundation.org/UASDK/ConfigurationTool";
            application.LastExportTime = DateTime.UtcNow;

            // copy the security settings.
            if (applicationConfiguration.SecurityConfiguration != null)
            {
                application.ApplicationCertificate = SecuredApplication.ToCertificateIdentifier(applicationConfiguration.SecurityConfiguration.ApplicationCertificate);
                
                if (applicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates != null)
                {
                    application.IssuerCertificateStore = SecuredApplication.ToCertificateStoreIdentifier(applicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates);

                    if (applicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates.TrustedCertificates != null)
                    {
                        application.IssuerCertificates = SecuredApplication.ToCertificateList(applicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates.TrustedCertificates);
                    }
                }

                if (applicationConfiguration.SecurityConfiguration.TrustedPeerCertificates != null)
                {
                    application.TrustedCertificateStore = SecuredApplication.ToCertificateStoreIdentifier(applicationConfiguration.SecurityConfiguration.TrustedPeerCertificates);

                    if (applicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.TrustedCertificates != null)
                    {
                        application.TrustedCertificates = SecuredApplication.ToCertificateList(applicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.TrustedCertificates);
                    }
                }

                if (applicationConfiguration.SecurityConfiguration.RejectedCertificateStore != null)
                {
                    application.RejectedCertificatesStore = SecuredApplication.ToCertificateStoreIdentifier(applicationConfiguration.SecurityConfiguration.RejectedCertificateStore);
                }
            }

            ServerBaseConfiguration serverConfiguration = null;

            if (applicationConfiguration.ServerConfiguration != null)
            {
                serverConfiguration = applicationConfiguration.ServerConfiguration;
            }

            else if (applicationConfiguration.DiscoveryServerConfiguration != null)
            {
                serverConfiguration = applicationConfiguration.DiscoveryServerConfiguration;
            }

            if (serverConfiguration != null)
            {
                application.BaseAddresses = SecuredApplication.ToListOfBaseAddresses(serverConfiguration);
                application.SecurityProfiles = SecuredApplication.ToListOfSecurityProfiles(serverConfiguration.SecurityPolicies);
            }

            // return exported setttings.
            return application;
        }
Exemplo n.º 28
0
        private void LoadTINfromLandXML(string fileName)
        {
            if (!(String.Compare(Path.GetExtension(fileName), ".xml", true) == 0))
             {
            throw new ArgumentException("Filename must have xml extension.");
             }

             memoryUsed = GC.GetTotalMemory(true);
             Stopwatch stopwatch = new Stopwatch();
             List<string> trianglesAsStrings;
             setupStopWatches();

             scratchUIntPair = new UInt64pair();

             System.Console.WriteLine("Load XML document took:");
             stopwatch.Reset(); stopwatch.Start();
             LoadTimeStopwatch.Reset(); LoadTimeStopwatch.Start();
             using (XmlTextReader reader = new XmlTextReader(fileName))
             {
            stopwatch.Stop();  consoleOutStopwatch(stopwatch);
            System.Console.WriteLine("Seeking Pnts collection took:");
            stopwatch.Reset();    stopwatch.Start();
            reader.MoveToContent();
            reader.ReadToDescendant("Surface");
            string astr = reader.GetAttribute("name");

            // Read Points
            reader.ReadToDescendant("Pnts");
            stopwatch.Stop();  consoleOutStopwatch(stopwatch);

            System.Console.WriteLine("Loading All Points took:");
            stopwatch.Reset();    stopwatch.Start();
            reader.Read();
            while (!(reader.Name.Equals("Pnts") && reader.NodeType.Equals(XmlNodeType.EndElement)))
            {
               UInt64 id;
               if (reader.NodeType.Equals(XmlNodeType.Element))
               {
                  UInt64.TryParse(reader.GetAttribute("id"), out id);
                  reader.Read();
                  if (reader.NodeType.Equals(XmlNodeType.Text))
                  {
                     scratchPoint = new ptsDTMpoint(reader.Value, id);
                     if (allPoints == null)
                     {
                        createAllpointsCollection();

                        myBoundingBox = new ptsBoundingBox2d(scratchPoint.x, scratchPoint.y, scratchPoint.x, scratchPoint.y);
                     }
                     allPoints.Add(id, scratchPoint);
                     myBoundingBox.expandByPoint(scratchPoint.x, scratchPoint.y, scratchPoint.z);
                  }
               }
               reader.Read();
            }

            // Read Triangles, but only as strings
            stopwatch.Stop();  consoleOutStopwatch(stopwatch);
            System.Console.WriteLine(allPoints.Count.ToString() + " Points Total.");

            System.Console.WriteLine("Loading Triangle Reference Strings took:");
            stopwatch.Reset();    stopwatch.Start();
            trianglesAsStrings = new List<string>();
            if (!(reader.Name.Equals("Faces")))
            {
               reader.ReadToFollowing("Faces");
            }
            reader.Read();
            while (!(reader.Name.Equals("Faces") && reader.NodeType.Equals(XmlNodeType.EndElement)))
            {
               if (reader.NodeType.Equals(XmlNodeType.Text))
               {
                  trianglesAsStrings.Add(reader.Value);
               }
               reader.Read();
            }
            reader.Close();
            stopwatch.Stop();  consoleOutStopwatch(stopwatch);

            System.Console.WriteLine("Generating Triangle Collection took:");
            stopwatch.Reset();    stopwatch.Start();
             }

             // assemble the allTriangles collection
             //allTriangles = new List<ptsDTMtriangle>(trianglesAsStrings.Count);
             allTrianglesBag = new ConcurrentBag<ptsDTMtriangle>();
             Parallel.ForEach(trianglesAsStrings, refString =>
            {
               allTrianglesBag.Add(new ptsDTMtriangle(allPoints, refString));
            }
            );
             allTriangles = allTrianglesBag.OrderBy(triangle => triangle.point1.x).ToList();
             trianglesAsStrings = null; allTrianglesBag = null;
             GC.Collect(); GC.WaitForPendingFinalizers();
             memoryUsed = GC.GetTotalMemory(true) - memoryUsed;
             LoadTimeStopwatch.Stop();

             stopwatch.Stop();
             System.Console.WriteLine(allTriangles.Count().ToString() + " Total Triangles.");
             consoleOutStopwatch(stopwatch);

             //
             //System.Console.WriteLine("Indexing Triangles for adjacency took:");
             //stopwatch.Reset(); stopwatch.Start();
             //generateTriangleLineIndex();  start here
             //stopwatch.Stop(); consoleOutStopwatch(stopwatch);
        }
Exemplo n.º 29
0
		// true if the resx file or any file referenced
		// by the resx is newer than the .resources file
		//
		// Code taken from monodevelop
		// main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs
		bool IsResgenRequired (string resx_filename, string resources_filename)
		{
			if (IsFileNewerThan (resx_filename, resources_filename)) {
				Log.LogMessage (MessageImportance.Low,
						"Resource file '{0}' is newer than the source file '{1}', skipping.",
						resources_filename, resx_filename);
				return true;
			}

			if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
				return true;

			// resx file, check for files referenced from there
			XmlTextReader xr = null;
			try {
				// look for
				// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
				//   <value>... filename;.. </value>
				// </data>
				xr = new XmlTextReader (resx_filename);
				string basepath = Path.GetDirectoryName (resx_filename);
				while (xr.Read ()) {
					if (xr.NodeType != XmlNodeType.Element ||
						String.Compare (xr.LocalName, "data") != 0)
						continue;

					string type = xr.GetAttribute ("type");
					if (String.IsNullOrEmpty (type))
						continue;

					if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
						continue;

					xr.ReadToDescendant ("value");
					if (xr.NodeType != XmlNodeType.Element)
						continue;

					string value = xr.ReadElementContentAsString ();

					string [] parts = value.Split (';');
					if (parts.Length > 0) {
						string referenced_filename = MSBuildUtils.FromMSBuildPath (
								Path.Combine (basepath, parts [0]).Trim ());
						if (File.Exists (referenced_filename) &&
							IsFileNewerThan (referenced_filename, resources_filename))
							return true;
					}
				}
			} catch (XmlException) {
				// Ignore xml errors, let resgen handle it
				return true;
			} finally {
				if (xr != null)
					xr.Close ();
			}

			return false;
		}
Exemplo n.º 30
0
		private void ParseSemanticDomainFile()
		{
			XmlTextReader reader = null;
			try
			{
				reader = new XmlTextReader(_semanticDomainQuestionsFileName);
				reader.MoveToContent();
				if (!reader.IsStartElement("semantic-domain-questions"))
				{
					//what are we going to do when the file is bad?
					Debug.Fail("Bad file format, expected semantic-domain-questions element");
				}
				//string ws = reader.GetAttribute("lang"); got it from the configuration file

				// should verify that this writing system is in optionslist
				_semanticDomainWritingSystem =
					BasilProject.Project.WritingSystems[WritingSystemIdForNamesAndQuestions];
				string semanticDomainType = reader.GetAttribute("semantic-domain-type");
				// should verify that domain type matches type of optionList in semantic domain field

				reader.ReadToDescendant("semantic-domain");
				while (reader.IsStartElement("semantic-domain"))
				{
					string domainKey = reader.GetAttribute("id");
					List<string> questions = new List<string>();
					XmlReader questionReader = reader.ReadSubtree();
					questionReader.MoveToContent();
					questionReader.ReadToFollowing("question");
					while (questionReader.IsStartElement("question"))
					{
						questions.Add(questionReader.ReadElementString("question").Trim());
					}
					_domainKeys.Add(domainKey);
					if (questions.Count == 0)
					{
						questions.Add(string.Empty);
					}
					_domainQuestions.Add(domainKey, questions);
					reader.ReadToFollowing("semantic-domain");
				}
			}
			catch (XmlException)
			{
				// log this;
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
			}
		}