示例#1
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);
        }
示例#2
0
文件: CML.cs 项目: SSheldon/Chemistry
 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));
 }
 /// <summary>
 /// Parses the input stream and return the associated project type. The stream should point to a project file (csproj or vbproj)
 /// </summary>
 /// <param name="st">The stream</param>
 /// <returns>the project type</returns>
 public static string GetProjectType(Stream st)
 {
     XmlTextReader rd = new XmlTextReader(st);
     using (rd)
     {
         rd.ReadStartElement("Project");
         rd.ReadToNextSibling("PropertyGroup");
         rd.ReadStartElement("PropertyGroup");
         rd.ReadToNextSibling("OutputType");
         return rd.ReadString();
     }
 }
示例#4
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();
     }
 }
示例#5
0
文件: Form3.cs 项目: Rex-Hays/GNIDA2
 private void Form3_Load(object sender, EventArgs e)
 {
     XmlTextReader reader = new XmlTextReader(flrt.DName);
     reader.ReadToFollowing("Name");
     textBox4.Text = (string)reader.ReadElementContentAs(typeof(string), null);
     reader.ReadToNextSibling("Mask");
     textBox4.Text += (string)reader.ReadElementContentAs(typeof(string), null);
     textBox2.Text = Func.FName;
     Funcs.ReadXml(flrt.DName);
     dataGridView1.DataSource = Funcs;
     dataGridView1.DataMember = "function";
 }
示例#6
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"));
 }
示例#7
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;
    }
示例#8
0
        private void LoadIdentity(IdentityEnum Identity)
        {
            switch (Identity) {
                case IdentityEnum.Quran:

                    if (!isIdentityLoaded[0]) {
                        XmlTextReader xmlReader;

                        /* Read the list of all the available fonts */
                        FontFamily[] ff = FontFamily.Families;
                        for (int i = 0; i < ff.Length; i++) {
                            cmbFontName.Items.Add((string)ff[i].Name);
                        }
                        cmbFontName.Text = Properties.Settings.Default.FontName;
                        cmbFontSize.Text = Properties.Settings.Default.FontSize;

                        /* Read and Load Extensions */
                        xmlReader = new XmlTextReader(PATH_APP_DATA + "extensions.xml");
                        tafseerStruct rstruct;
                        xmlReader.ReadToFollowing("extension");
                        do {
                            ToolStripItem rItem;
                            rstruct = new tafseerStruct();
                            rstruct.dir = xmlReader.GetAttribute("dir");
                            rstruct.id = xmlReader.GetAttribute("id");
                            xmlReader.ReadToFollowing("title");
                            rstruct.title = xmlReader.ReadElementString();
                            xmlReader.ReadToFollowing("location");
                            rstruct.location = xmlReader.ReadElementString();

                            rItem = mextension.Items.Add(rstruct.title);
                            rItem.Tag = rstruct;
                            rItem.Click += new EventHandler(rItem_Click);

                        } while (xmlReader.ReadToFollowing("extension"));
                        xmlReader.Close();

                        /* Read all the available recitors */
                        xmlReader = new XmlTextReader(PATH_APP_DATA + "recitations.xml");
                        xmlReader.ReadToFollowing("recitation");
                        do {
                            dctReciters.Add(xmlReader.GetAttribute("name"),
                                            xmlReader.GetAttribute("url"));
                            cmbrecitors.Items.Add(xmlReader.GetAttribute("name"));
                        } while (xmlReader.ReadToNextSibling("recitation"));
                        xmlReader.Close();
                        cmbrecitors.SelectedIndex = Properties.Settings.Default.quranReciter;

                        /* Read all the sowar names from the xml file */
                        xmlReader = new XmlTextReader(PATH_APP_DATA + "quran.xml");
                        xmlReader.ReadToFollowing("SOURA");
                        do {
                            cmbSoura.Items.Add(xmlReader.GetAttribute("id") + "."
                                            + xmlReader.GetAttribute("name"));
                        } while (xmlReader.ReadToNextSibling("SOURA"));
                        xmlReader.Close();

                        /* Load the quran to the viewer */
                        qv.LoadXmlFile(PATH_APP_DATA + "quran.xml");
                        qv.LoadQuranParts(PATH_APP_DATA + "quran_parts.xml");

                        /* Read other UI elements settings for the quran identity*/
                        cntright.Panel2Collapsed = Properties.Settings.Default.SearchState;
                        chkSearch.Checked = !cntright.Panel2Collapsed;
                        pnla.SelectedText = Properties.Settings.Default.pnlaSelected;
                        pnlb.SelectedText = Properties.Settings.Default.pnlbSelected;
                        QuranVolume.Position = Properties.Settings.Default.VolumeLevel;

                        xmlpnla = new XmlDocument(); xmlpnlb = new XmlDocument();
                        if (!wc.Contains(GettafseerFromTitle(pnla.SelectedText).id))
                            xmlpnla.Load(GettafseerFromTitle(pnla.SelectedText).location);
                        if (!wc.Contains(GettafseerFromTitle(pnlb.SelectedText).id))
                            xmlpnlb.Load(GettafseerFromTitle(pnlb.SelectedText).location);

                        if (Properties.Settings.Default.ViewMode == 0) {
                            qv.ViewMode = qViewer.ViewModeFlags.SingleLine;
                            chkSingleline.Checked = true;
                        }
                        else {
                            qv.ViewMode = qViewer.ViewModeFlags.MultiLine;
                            chkMultiline.Checked = true;
                        }
                        cmbSoura.SelectedIndex = Properties.Settings.Default.CurrentSoura;
                        qv.SelectedIndex = Properties.Settings.Default.CurrentAya;
                        qv.ScrollPosition = Properties.Settings.Default.CurrentScrollValue;

                    }
                    spcHadeeth.Visible = false;
                    spcQuran.Visible = true;
                    pnlQuranTools.Show();
                    pnlHadeethTools.Hide();
                    isIdentityLoaded[0] = true;

                    break;
                case IdentityEnum.Hadeeth:

                    string hadeethSelected = Properties.Settings.Default.hadeethSelected;
                    StringCollection hadeethSearchHistory = Properties.Settings.Default.hadeethSearchHistory;

                    if (!isIdentityLoaded[1]) { /* Identity is loaded for the first time */
                        LoadHadeethTree();

                        if (hadeethSearchHistory != null)
                            foreach (string rItem in hadeethSearchHistory)
                                cmbhdtSearch.Items.Add(rItem);

                        cmbhdtSearchScope.Items.Add("جميع الكتب");
                        cmbhdtSearchScope.SelectedIndex = 0;
                        for (int i = 0; i < 6; i++)
                            cmbhdtSearchScope.Items.Add(trvHadeeth.Nodes[i].Text);

                        trvHadeeth.SelectedNode = NodeFromIndex(trvHadeeth ,hadeethSelected);
                        trvHadeeth.Select();

                    }
                    spcHadeeth.Visible = true;
                    spcQuran.Visible = false;
                    pnlQuranTools.Hide();
                    pnlHadeethTools.Show();
                    isIdentityLoaded[1] = true;
                    break;

            }
        }
示例#9
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);

            }
        }
        public override SceneFileResult Import(string importFile)
        {
            MogitorsRoot mogRoot = MogitorsRoot.Instance;
            MogitorsSystem system = MogitorsSystem.Instance;

            if (importFile == "")
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = "";
                dlg.DefaultExt = ".mogscene";
                dlg.Filter = "Mogitor Scene File (.mogscene)|*.mogscene";
                Nullable<bool> result = dlg.ShowDialog();
                if (result != true)
                {
                    return SceneFileResult.Cancel;
                }
                importFile = dlg.FileName;
            }

            string filePath = system.ExtractFilePath(importFile);
            string fileName = system.ExtractFileName(importFile);

            XmlTextReader textReader = new XmlTextReader(importFile);

            system.UpdateLoadProgress(5, "Loading scene objects");

            if (!textReader.ReadToFollowing("MogitorScene"))
                return SceneFileResult.ErrParse;

            // Check version
            string fileVersion = textReader.GetAttribute("Version");
            if (fileVersion != null)
            {
                if (int.Parse(fileVersion) != 1)
                    return SceneFileResult.ErrParse;
            }

            // Read project options
            if (textReader.ReadToFollowing("ProjectOptions") == true)
            {
                system.UpdateLoadProgress(15, "Parsing project options");
                mogRoot.LoadProjectOptions(textReader);

                mogRoot.ProjectOptions.ProjectDir = filePath;
                mogRoot.ProjectOptions.ProjectName = fileName;

                mogRoot.PrepareProjectResources();
            }

            //// Moves the reader back to the "MogitorScene" element node.
            //textReader.MoveToElement();

            system.UpdateLoadProgress(30, "Creating scene objects");

            // Load objects
            Mogre.NameValuePairList param = new Mogre.NameValuePairList();
            while (textReader.ReadToNextSibling("Object"))
            {
                string objectType = textReader.GetAttribute("Type");
                if (objectType == "")
                    continue;

                param.Clear();
                while (textReader.MoveToNextAttribute())
                {
                    param.Insert(textReader.Name, textReader.Value);
                }

                BaseEditor result = MogitorsRoot.Instance.CreateEditorObject(null, objectType, param, false, false);
            }

            mogRoot.AfterLoadScene();

            return SceneFileResult.Ok;
        }
示例#11
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;
        }
        private bool HandleImportDialog (ItunesImportDialog dialog, ImportDialogHandler code)
        {
            try {
                if (dialog.Run () == (int)ResponseType.Ok) {
                    if(code != null) {
                        code (dialog);
                    }
                    data.get_ratings = dialog.Ratings;
                    data.get_stats = dialog.Stats;
                    data.get_playlists = dialog.Playliststs;
                } else {
                    return false;
                }
            } finally {
                dialog.Destroy ();
                dialog.Dispose ();
            }

            if (String.IsNullOrEmpty (data.library_uri)) {
                return false;
            }

            // Make sure the library version is supported (version 1.1)
            string message = null;
            bool prompt = false;
            using (var xml_reader = new XmlTextReader (data.library_uri))
            {
                xml_reader.ReadToFollowing ("key");
                do {
                    xml_reader.Read ();
                    string key = xml_reader.ReadContentAsString ();
                    if (key == "Major Version" || key == "Minor Version") {
                        xml_reader.Read ();
                        xml_reader.Read ();
                        if(xml_reader.ReadContentAsString () != "1") {
                            message = Catalog.GetString (
                                "Banshee is not familiar with this version of the iTunes library format." +
                                " Importing may or may not work as expected, or at all. Would you like to attempt to import anyway?");
                            prompt = true;
                            break;
                        }
                    }
                } while (xml_reader.ReadToNextSibling ("key"));
            }

            if (prompt) {
                bool proceed = false;
                using (var message_dialog = new MessageDialog (null, 0, MessageType.Question, ButtonsType.YesNo, message)) {
                    if (message_dialog.Run () == (int)ResponseType.Yes) {
                        proceed = true;
                    }
                    message_dialog.Destroy ();
                }
                if (!proceed) {
                    LogError (data.library_uri, "Unsupported version");
                    return false;
                }
            }

            return true;
        }
 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"));
     }
 }
示例#14
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();
        }
示例#15
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;
        }
示例#16
0
文件: Row.cs 项目: beursken/Crawler
        public void Load(XmlTextReader reader)
        {
            reader.Read();

            do
            {
                _cols[XmlConvert.ToInt32(reader.GetAttribute("id"))].Load(reader);
            }
            while (reader.ReadToNextSibling("Col"));
        }
		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"));
			};
		}
示例#18
0
        public DUT_Str read(string path)
        {
            string temp;
            DUT_Str dut = new DUT_Str();
            dut.RawCountX = new List<string>();
            dut.NoiseX = new List<string>();
            dut.StdDevX = new List<string>();
            dut.RawCountY = new List<string>();
            dut.NoiseY = new List<string>();
            dut.StdDevY = new List<string>();
            dut.IDAC = new List<string>();
            dut.IDACGain = new List<string>();
            dut.Global_IDAC = new List<string>();
            dut.Local_IDAC = new List<string>();
            dut.SignalX = new List<string>();
            dut.SNRX = new List<string>();

            XmlTextReader reader;
            try
            {
                reader = new XmlTextReader(path);

                reader.MoveToContent();
                reader.ReadStartElement("Trackpad");

                    reader.ReadStartElement("Serial_Number");
                    temp = reader.ReadString();
                    dut.SerailNumber = temp;
                    dut.PartType = temp.Substring(0, 8);
                    //Console.WriteLine("The Serial_Number is: {0}", temp);
                    reader.ReadEndElement();

                    reader.ReadStartElement("Test_Station");
                    temp = reader.ReadString();
                    dut.TestStation = temp;
                    //Console.WriteLine("The Test_Station is: {0}", temp);
                    reader.ReadEndElement();

                    reader.ReadStartElement("Error_Code");
                    temp = reader.ReadString();
                    dut.ErrorCode = temp;
                    //Console.WriteLine("The Error_Code is: {0}", temp);
                    reader.ReadEndElement();

                    reader.ReadStartElement("Test_Time");
                    temp = reader.ReadString().Substring(0, 19);
                    dut.TestTime = temp;
                    //Console.WriteLine("The Test_Time is: {0}", temp);
                    reader.ReadEndElement();

                    reader.ReadStartElement("IDD_Value");
                    temp = reader.ReadString();
                    dut.IDDValue = temp;
                    //Console.WriteLine("The IDD_Value is: {0}", temp);
                    reader.ReadEndElement();

                    reader.ReadStartElement("Firmware_Revision");
                    temp = reader.ReadString();
                    dut.FwRev = temp;
                    //Console.WriteLine("The Firmware_Revision is: {0}", temp);
                    reader.ReadEndElement();

                    //reader.ReadStartElement("IDD_Sleep1_Value");
                    //temp = reader.ReadString();
                    //dut.IDDValueSleep1 = temp;
                    ////Console.WriteLine("The IDD_Value is: {0}", temp);
                    //reader.ReadEndElement();

                    //reader.ReadStartElement("IDD_Deep_Sleep_Value");
                    //temp = reader.ReadString();
                    //dut.IDDValueDeepSleep = temp;
                    ////Console.WriteLine("The Firmware_Revision is: {0}", temp);
                    //reader.ReadEndElement();

                    reader.ReadStartElement("Raw_Count_Averages");
                    int i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.RawCountX.Add(temp);
                        //Console.WriteLine("Raw_Count_Averages" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("Raw_Count_Noise");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.NoiseX.Add(temp);
                        //Console.WriteLine("Raw_Count_Noise" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("IDAC_Value");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.IDAC.Add(temp);
                        //Console.WriteLine("IDAC_Value" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("IDAC_Gain_Value");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.IDACGain.Add(temp);
                        //Console.WriteLine("IDAC_Value" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("Local_IDAC_Value");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.Local_IDAC.Add(temp);
                        //Console.WriteLine("IDAC_Value" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("Signal_Data");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.SignalX.Add(temp);
                        //Console.WriteLine("IDAC_Value" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                    reader.ReadStartElement("SNR_Data");
                    i = 1;
                    while (reader.ReadToNextSibling("D" + i.ToString()))
                    {
                        temp = reader.ReadString();
                        dut.SNRX.Add(temp);
                        //Console.WriteLine("IDAC_Value" + i.ToString() + ": {0}", temp);
                        i++;
                    }
                    reader.ReadEndElement();

                reader.ReadEndElement();

                reader.Close();
            }
            catch
            { }

            return dut;
        }
示例#19
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;
    }
示例#20
0
        InputFileStore( string xmlFile )
        {
            System.IO.FileStream fs = null;
            XmlTextReader xmlReader = null;

            CheckXmlFileSignature( xmlFile );

            try
            {
                fs = new System.IO.FileStream( xmlFile, System.IO.FileMode.Open );
                xmlReader = new XmlTextReader( fs );

                if ( !xmlReader.ReadToFollowing( "Settings" ) )
                    throw new Exception( "Settings xml not found" );
                mSettings = Settings.LoadFromXml( xmlReader );

                if ( !xmlReader.ReadToFollowing( "Image" ) )
                    return;

                do
                {
                    if ( !xmlReader.ReadToFollowing( "SubImage" ) )
                        return;

                    do
                    {
                        string filename = "";
                        long lastModified = 0;

                        do
                        {
                            string lowerName = xmlReader.Name.ToLower();

                            switch ( lowerName )
                            {
                                case "name":
                                    filename = xmlReader.Value;
                                    break;
                                case "lastmodified":
                                    long.TryParse( xmlReader.Value, out lastModified );
                                    break;
                            }

                        } while ( xmlReader.MoveToNextAttribute() );

                        if ( filename.Length > 0 && lastModified > 0 )
                            mModificationTimes.Add( filename, new DateTime( lastModified ) );
                    } while ( xmlReader.ReadToNextSibling( "SubImage" ) );
                }
                while ( xmlReader.ReadToFollowing( "Image" ) );
            }
            catch ( System.Exception )
            {
            }
            finally
            {
                if ( xmlReader != null )
                    xmlReader.Close();
                if ( fs != null )
                    fs.Close();
            }
        }
示例#21
0
文件: ImexUtils.cs 项目: nhannd/Xian
        /// <summary>
        /// Reads the specified set of XML source files, yielding each item as an <see cref="IImportItem"/>.
        /// </summary>
        /// <param name="sourceFiles"></param>
        /// <returns></returns>
        private static IEnumerable<IImportItem> ReadSourceFiles(IEnumerable<string> sourceFiles)
        {
            foreach (string sourceFile in sourceFiles)
            {
                using (StreamReader reader = File.OpenText(sourceFile))
                {
                    XmlTextReader xmlReader = new XmlTextReader(reader);
                    xmlReader.WhitespaceHandling = WhitespaceHandling.None;

                    // advance to root tag
                    if (xmlReader.ReadToFollowing(RootTag))
                    {
                        // advance to first child
                        while (xmlReader.Read() && xmlReader.NodeType != XmlNodeType.Element) ;

                        // if child nodes exist, read them
                        if (xmlReader.NodeType == XmlNodeType.Element)
                        {
                            string itemTag = xmlReader.Name;
                            for (bool more = true; more; more = xmlReader.ReadToNextSibling(itemTag))
                            {
                                yield return new ImportItem(xmlReader.ReadSubtree());
                            }
                        }
                    }
                    xmlReader.Close();
                }
            }
        }
示例#22
0
文件: Map.cs 项目: beursken/Crawler
        public bool Load(string fileName)
        {
            fileName = fileName.ToLower().Trim();
            if (!fileName.EndsWith(".xml"))
            {
                fileName += ".xml";
            }
            if (System.IO.File.Exists(fileName))
            {
                XmlTextReader reader = new XmlTextReader(fileName);
                reader.MoveToContent();
                try
                {

                    Setup(XmlConvert.ToInt32(reader.GetAttribute("height")), XmlConvert.ToInt32(reader.GetAttribute("width")));
                    reader.Read();

                    do
                    {
                        int y = XmlConvert.ToInt32(reader.GetAttribute("id"));
                        _rows[y].Load(reader);
                    }
                    while (reader.ReadToNextSibling("Row"));

                    _filename = fileName;
                    return true;
                }
                //catch { }
                finally { reader.Close(); }
            }
            return false;
        }