Click here to Skip to main content
15,895,746 members
Articles / Web Development / HTML

Mambo CMS Article Control

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
23 Oct 2011CPOL13 min read 26.5K   1.7K   9  
The code implements a system to create articles using MS-Word for use in the Mambo CMS. The majority of the code is a C# project that reads and parses HTML text created using MS Word. The support projects are a VBA macro for creating the needed HTML and an export/import system for getting localhost
//
// Text2Mambo - convert HTML to mambo CMS
// Copyright (C) 2009-2011 John Janssen
// http://www.travelisfun.org 
//
// This program is free software; you can redistribute it and/or modify
// it any way you want as long as the above copyright statement is maintained.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Runtime;
using System.Diagnostics;
using Microsoft.Win32;
using MySql.Data;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
using Text2Mambo.Tools;
using TIFTools;

namespace Text2Mambo.Controls
{
  public partial class UCTextImport : MyUserControl
  {
    private bool mamboConnectionOpened = false;
    private bool formIsLoading = false;
    private RecentFileList recentFileList = new RecentFileList();

    private static TextImportParameters parameters;

    public static String SelectedUserId
    {
      get { return parameters.SelectedUserId; }
      set { parameters.SelectedUserId = value; }
    }
    public static String SelectedSectionId
    {
      get { return parameters.SelectedSectionId; }
      set { parameters.SelectedSectionId = value; }
    }
    public static String SelectedCategoryId
    {
      get { return parameters.SelectedCategoryId; }
      set { parameters.SelectedCategoryId = value; }
    }

    public UCTextImport()
    {
      mamboConnectionOpened = MainForm.OpenConnection();
      parameters = TextImportParameters.GetInstance();
      InitializeComponent();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public override String ToString()
    {
      return "Text import";
    }
    /// <summary>
    /// Called when the containing form is destroyed.
    /// </summary>
    public override void Closing()
    {
      WriteRegistry();
      if (mamboConnectionOpened)
        MainForm.CloseConnection();
    }
    /// <summary>
    /// Store application data in the registry.
    /// </summary>
    private void WriteRegistry()
    {
      if (!formIsLoading)
      {
        try
        {
          if (UserList.SelectedIndex != -1)
          {
            ListBoxItem item = (ListBoxItem)UserList.Items[UserList.SelectedIndex];
            parameters.SelectedUserId = (String)item.Param;
          }
          if (comboBoxCategoryList.SelectedItem != null)
          {
            ListBoxItem item = (ListBoxItem)comboBoxCategoryList.SelectedItem;
            parameters.SelectedCategoryId = ((String[])item.Param)[0];
          }
          if (comboBoxSectionList.SelectedItem != null)
          {
            ListBoxItem item = (ListBoxItem)comboBoxSectionList.SelectedItem;
            parameters.SelectedSectionId = ((String[])item.Param)[0];
          }
          // store the parameter structure
          parameters.WriteRegistry(ProgramSettings.RegistryPath);

          // store the recent file list.
          recentFileList.Store(ProgramSettings.RegistryPath);
        }
        catch (Exception ex)
        {
          MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      }
    }
    /// <summary>
    /// retrieve application data from the registry.
    /// </summary>
    private void ReadRegistry()
    {
      try
      {
        RegistryKey key = Registry.CurrentUser.OpenSubKey(ProgramSettings.RegistryPath);
        if (key != null)
        {
          parameters.ReadRegistry(ProgramSettings.RegistryPath);

          FillUserList(parameters.SelectedUserId);
          FillSectionList(parameters.SelectedSectionId);
          UpdateCatList(parameters.SelectedSectionId, parameters.SelectedCategoryId);

          // Loading the recent file list into the combobox
          recentFileList.Load(ProgramSettings.RegistryPath);
          String[] ll = recentFileList.Get();
          foreach (String t in ll)
          {
            comboboxInputfile.Items.Add(t);
          }
          if (ll.Length > 0)
          {
            comboboxInputfile.Text = ll[0];
          }
          buttonProcessFile.Enabled = File.Exists(comboboxInputfile.Text);
          buttonEditInput.Enabled = File.Exists(comboboxInputfile.Text);
        }
      }
      catch (IOException t)
      {
        Text2Mambo.Tools.Show.ShowMessage(t.Message);
      }
    }
     /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void UCTextImport_Load(object sender, EventArgs e)
    {
      formIsLoading = true;

      BackColor = ProgramSettings.TabPageBackColor;
      ResizeToParent();

      buttonProcessFile.Enabled = false;
      buttonEditInput.Enabled = false;

      ReadRegistry();
      formIsLoading = false;
      propertyGrid1.SelectedObject = parameters;

      //checkBoxImageFolder_CheckedChanged(null, null);
      buttonViewOutputLog.Enabled = File.Exists(MainForm.OutputFile);

      String folder = Path.GetDirectoryName(MainForm.OutputFile);
      try
      {
        Directory.CreateDirectory(folder);

        fileSystemWatcher.Path = folder;
        fileSystemWatcher.Filter = Path.GetFileName(MainForm.OutputFile);
        fileSystemWatcher.EnableRaisingEvents = true;
      }
      catch (Exception ex)
      {
        MessageBox.Show("Something wrong: " + ex.Message);
        throw;
      }

      listView.MultiSelect = false;
      listView.ShowItemToolTips = true;
      listView.FullRowSelect = true;

      toolTip1.SetToolTip(buttonUpdateContentList, "Display the list off context items from Mambo.");

      toolTip1.SetToolTip(buttonProcessFile, "Start processing the selected HTML file.");

      toolTip1.SetToolTip(UserList, "The list of users known in Mambo. Select one that should be connectd to articles when no author is supplied.");
      toolTip1.SetToolTip(comboBoxSectionList, "The sections known to Mambo.");
      toolTip1.SetToolTip(comboBoxCategoryList, "The categories that are known in mMambo that belong to the selected secion.");

      toolTip1.SetToolTip(buttonCheckImageParagraph, "Wraps all the images \"<img />\" within all the text in the Mambo context with a <p class=Image> .. </p> wrapper.");
      toolTip1.SetToolTip(buttonUndoWrapImages, "This is the reverse of what the \"Wrap images in paragraph\" button does.");
      toolTip1.SetToolTip(buttonFixOrder, "Fixes the order off articles based on the created date.");
      toolTip1.SetToolTip(buttonViewOutputLog, "While processing a document, Text2Mambo creates an output log, this button while open that document.");
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="lst"></param>
    /// <param name="table"></param>
    private static void SetListViewColumns(ListView lst, String table)
    {
      DataTable data = new DataTable();
      DataSet dataset = new DataSet();

      MySqlDataAdapter da = MamboConnection.CreateDataAdapter("SELECT * FROM " + table);
      MySqlCommandBuilder cb = new MySqlCommandBuilder(da);

      da.Fill(dataset, 0, 1, table);
      lst.Columns.Clear();
      for (int i = 0; i < data.Columns.Count; i++)
      {
        lst.Columns.Insert(lst.Columns.Count, data.Columns[i].ColumnName, 100);
      }
      cb.Dispose();
      da.Dispose();
      dataset.Dispose();
      data.Dispose();
    }
    /// <summary>
    /// Update the listView with data from the mos_content table.
    /// </summary>
    public void UpdateContentList()
    {
      this.Cursor = Cursors.WaitCursor;
      MySqlCommand myCommand = null;
      try
      {
        myCommand = MamboConnection.CreateCmd("select `id`,`title`,`introtext`,`fulltext`,`modified`,`publish_up`,`publish_down` from #__content");
        myCommand.CommandTimeout = 20;

        MySqlDataReader reader = myCommand.ExecuteReader();

        listView.Items.Clear();
        listView.Columns.Clear();
        listView.Columns.Insert(listView.Columns.Count, "id", 100);
        listView.Columns.Insert(listView.Columns.Count, "title", 150);
        listView.Columns.Insert(listView.Columns.Count, "introtext", 200);
        listView.Columns.Insert(listView.Columns.Count, "fulltext", 200);
        listView.Columns.Insert(listView.Columns.Count, "modified", 200);
        listView.Columns.Insert(listView.Columns.Count, "publish_up", 150);
        listView.Columns.Insert(listView.Columns.Count, "publish_down", 150);

        String st;
        while (reader.Read())
        {
          ListViewItem item = listView.Items.Insert(listView.Items.Count, reader.GetString("id"));
          item.SubItems.Add(reader.GetString("title"));
          item.SubItems.Add(reader.GetString("introtext"));
          item.SubItems.Add(reader.GetString("fulltext"));

          st = GetMySqlDateTime(reader.GetMySqlDateTime("modified"), true);
          item.SubItems.Add(st);

          st = GetMySqlDateTime(reader.GetMySqlDateTime("publish_up"), true);
          item.SubItems.Add(st);

          st = GetMySqlDateTime(reader.GetMySqlDateTime("publish_down"), true);
          item.SubItems.Add(st);
        }
        reader.Close();
      }
      finally
      {
        this.Cursor = Cursors.Default;
        if (myCommand != null)
          myCommand.Dispose();
      }
    }
    /// <summary>
    /// Convert a MySqlDateTime value into a standard date time string.
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="longDate"></param>
    /// <returns></returns>
    private String GetMySqlDateTime(MySqlDateTime dt, bool longDate)
    {
      if (dt.IsValidDateTime)
      {
        String st;
        DateTime sdt = dt.GetDateTime();
        if (longDate)
        {
          st = sdt.ToString("yyyy-MM-dd H:mm:ss");
        }
        else
        {
          st = sdt.ToString("yyyy-MM-dd");
        }
        return st;
      }
      return longDate ? "0000-00-00 00:00:00" : "0000-00-00";
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonBrowse_Click(object sender, EventArgs e)
    {
      openFileDialog.Filter = "Input files files (*.txt,*.htm,*.html)|*.txt;*.htm;*.html|All files (*.*)|*.*";
      if (String.IsNullOrEmpty(comboboxInputfile.Text))
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      else
        openFileDialog.InitialDirectory = Path.GetDirectoryName(comboboxInputfile.Text);
      openFileDialog.CheckFileExists = true;
      openFileDialog.CheckPathExists = true;
      openFileDialog.Multiselect = false;
      openFileDialog.ReadOnlyChecked = true;
      openFileDialog.FileName = comboboxInputfile.Text;

      if (openFileDialog.ShowDialog(this) == DialogResult.OK)
      {
        try
        {
          comboboxInputfile.Text = openFileDialog.FileName;
          recentFileList.Add(comboboxInputfile.Text);
          WriteRegistry();
          buttonProcessFile.Enabled = true;
          buttonEditInput.Enabled = true;
        }
        catch (Exception ex)
        {
          Text2Mambo.Tools.Show.ShowMessage("Error: Could not read file from disk. Original error: " + ex.Message);
        }
      }
    }
    /// <summary>
    /// Clear the lists.
    /// </summary>
    public void Clear()
    {
      UserList.Items.Clear();
      comboBoxSectionList.ClearAll();
    }
    /// <summary>
    /// Fill the user combobox with the data from the mambo database.
    /// </summary>
    /// <param name="selectid"></param>
    public void FillUserList(String selectid)
    {
      UserList.Items.Clear();

      if (!MamboConnection.IsOpen)
        return;

      String mySelectQuery = "SELECT `id`,`name` FROM #__users where block=0 and " +
            "(locate('Administrator', usertype) > 0 or locate('Publisher', usertype) > 0)";
      MySqlCommand myCommand = MamboConnection.CreateCmd(mySelectQuery);
      myCommand.CommandTimeout = 20;
      MySqlDataReader reader = myCommand.ExecuteReader();

      UserList.Sorted = true;
      UserList.SelectionMode = SelectionMode.One;
      try
      {
        while (reader.Read())
        {
          ListBoxItem item = new ListBoxItem(reader.GetString("name"), reader.GetString("id"));
          int itemIndex = UserList.Items.Add(item, false);
          if (reader.GetString("id") == selectid)
          {
            UserList.SetItemChecked(itemIndex, true);
          }
        }
      }
      finally
      {
        reader.Close();
        myCommand.Dispose();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    public void FillSectionList(String sectionId)
    {
      comboBoxSectionList.ClearAll();

      if (!MamboConnection.IsOpen)
        return;

      String qry = "select `title`,`id`,`name` from #__sections where published=1";
      MySqlCommand cmd = MamboConnection.CreateCmd(qry);
      cmd.CommandTimeout = 20;
      MySqlDataReader reader = cmd.ExecuteReader();

      comboBoxSectionList.Sorted = true;
      Object SelectedItem = null;
      while (reader.Read())
      {
        String[] param = new String[] { reader.GetString("id"), reader.GetString("name") };
        ListBoxItem item = new ListBoxItem(reader.GetString("title"), param);
        comboBoxSectionList.Items.Add(item);
        if (param[0] == sectionId)
        {
          SelectedItem = item;
        }
      }
      reader.Close();

      if (SelectedItem != null)
      {
        // this must be outside of the SQL read loop otherwise recursive call.
        comboBoxSectionList.SelectedItem = SelectedItem;
      }
      cmd.Dispose();
    }
    /// <summary>
    /// Validate the input before starting a parse.
    /// </summary>
    /// <returns></returns>
    private bool CheckValidSelection()
    {
      errorProvider.Clear();

      if (SelectedUserId.Length == 0)
      {
        errorProvider.SetError(UserList, "Select the user that is linked to the automatic content items.");
        return false;
      }
      if (SelectedSectionId.Length == 0)
      {
        errorProvider.SetError(comboBoxSectionList, "Select the section that is linked to the automatic contents items.");
        return false;
      }
      if (SelectedCategoryId.Length == 0)
      {
        errorProvider.SetError(comboBoxCategoryList, "Select the category that is linked to the automatic contents items.");
        return false;
      }
      return true;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="filePath"></param>
    private void UpdateMRUFileList(String filePath)
    {
      recentFileList.Add(filePath);
      comboboxInputfile.Items.Add(comboboxInputfile.Text);
    }
    private delegate void ResetOfList();
    private void ResetList()
    {
      listView.Columns.Clear();
      listView.Items.Clear();
      listView.Columns.Add("Header h2", 300);
    }
    private delegate void SetupString(String s);
    private void SetInputFilename(String filename)
    {
      comboboxInputfile.Text = filename;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="filepath"></param>
    public void ReadAndProcessInputFile(String filepath)
    {
      if (!ProgramSettings.NoUserInterface)
      {
        SetupString sus = new SetupString(SetInputFilename);
        this.Invoke(sus, new Object[] { filepath }); // thread safe

        ResetOfList rl = new ResetOfList(ResetList);
        this.Invoke(rl); // thread safe.
      }

      _SESSION.Reset();

      parameters.listViewCallback = ListViewUpdate;
      parameters.Filename = filepath;
      HTMLProcessor source = new HTMLProcessor(parameters);      
      source.Open();
    }
    private delegate void AddStrings(String[] list);
    private void UpdateListBox(String[] list)
    {
      ListViewItem index = listView.Items.Add(list[0]);
      for (int i = 1; i < list.Length; i++)
      {
        index.SubItems.Add(list[i]);
      }
      listView.EnsureVisible(index.Index);
      listView.Update();
    }
    /// <summary>
    /// The ListViewCallBack for use by the HTMLProcessor.
    /// </summary>
    /// <param name="list"></param>
    private void ListViewUpdate(String[] list)
    {
      if (!ProgramSettings.NoUserInterface)
      {
        AddStrings ad = new AddStrings(UpdateListBox);
        this.Invoke(ad, new Object[] { list });
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonProcessFile_Click(object sender, EventArgs e)
    {
      try
      {
        MainForm.Instance.Cursor = Cursors.WaitCursor;

        // STore the data and copy selected data into the parameters structure.
        WriteRegistry();

        if (!CheckValidSelection())
          return;

        UpdateMRUFileList(comboboxInputfile.Text);
        ReadAndProcessInputFile(comboboxInputfile.Text);
      }
      finally
      {
        MainForm.Instance.Cursor = Cursors.Default;
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonFixOrder_Click(object sender, EventArgs e)
    {
      try
      {
        //MainForm.OpenConnection();
        if (MamboConnection.IsOpen)
        {
          int order = 1;
          //String secid = parameters.SelectedSectionId.value;
          //String catid = parameters.SelectedCategoryId.value;
          String qry = String.Format("select id,created from #__content where state=1 and sectionid='{0}' and catid='{1}' order by `created`",
            parameters.SelectedSectionId,
            parameters.SelectedCategoryId);

          MySqlCommand cmd = MamboConnection.CreateCmd(qry);
          cmd.ExecuteNonQuery();

          ArrayList list = new ArrayList();
          MySqlDataReader reader = cmd.ExecuteReader();
          bool hasrows = reader.HasRows;
          if (hasrows)
          {
            while (reader.Read())
            {
              Pair<String> p = new Pair<String>(reader.GetString("id"), order.ToString());
              list.Add(p);
              order++;
            }
            reader.Close();
            foreach (Pair<String> p in list)
            {
              qry = "update #__content set ordering='" + p.y + "' where id='" + p.x + "'";
              cmd = MamboConnection.CreateCmd(qry);
              cmd.ExecuteNonQuery();
            }
          }
          else
            reader.Close();

          reader.Dispose();
          cmd.Dispose();
        }
      }
      catch (Exception ex)
      {
        Text2Mambo.Tools.Show.ShowMessage("Command failed : " + ex.Message);
      }
      finally
      {
        // MainForm.CloseConnection();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void comboboxInputfile_SelectedIndexChanged(object sender, EventArgs e)
    {
      buttonProcessFile.Enabled = File.Exists(comboboxInputfile.Text);
      buttonEditInput.Enabled = File.Exists(comboboxInputfile.Text);

      recentFileList.Add(comboboxInputfile.Text);
      WriteRegistry();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void comboboxInputfile_TextChanged(object sender, EventArgs e)
    {
      buttonProcessFile.Enabled = File.Exists(comboboxInputfile.Text);
      buttonEditInput.Enabled = File.Exists(comboboxInputfile.Text);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="txt"></param>
    /// <param name="startIndex"></param>
    /// <param name="whiteSpace"></param>
    /// <returns></returns>
    private static int skipBack(String txt, int startIndex, char[] whiteSpace)
    {
      while (startIndex != -1 && Array.IndexOf(whiteSpace, txt[startIndex]) != -1)
        startIndex--;
      return startIndex;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="txt"></param>
    /// <param name="startIndex"></param>
    /// <param name="findChar"></param>
    /// <returns></returns>
    private static int findBack(String txt, int startIndex, char[] findChar)
    {
      while (startIndex != -1 && Array.IndexOf(findChar, txt[startIndex]) == -1)
        startIndex--;
      return startIndex;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="txt"></param>
    /// <param name="startIndex"></param>
    /// <param name="whiteSpace"></param>
    /// <returns></returns>
    private static int skipForward(String txt, int startIndex, char[] whiteSpace)
    {
      while (startIndex != txt.Length && Array.IndexOf(whiteSpace, txt[startIndex]) != -1)
        startIndex++;
      return startIndex == txt.Length ? -1 : startIndex;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="txt"></param>
    /// <param name="startIndex"></param>
    /// <param name="findChar"></param>
    /// <returns></returns>
    private static int findForward(String txt, int startIndex, char[] findChar)
    {
      while (startIndex != txt.Length && Array.IndexOf(findChar, txt[startIndex]) == -1)
        startIndex++;
      return startIndex == txt.Length ? -1 : startIndex;
    }

    readonly static String[] imageParagraphWrap = { "<p class=Image>", "</p>" };
    /// <summary>
    /// This method finds all <!-- <img /> --> image tags in txt and surrounds them
    /// with a <!-- <p class=Image>  ... </p> --> wrapper.
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static bool ParseTextForImageParagraph(ref String txt)
    {
      int pos = txt.IndexOf("<img");
      bool modified = false;
      while (pos != -1)
      {
        if (pos < 3) // there can't be a paragraph tag in front
        {
          txt = txt.Insert(pos, imageParagraphWrap[0]);

          pos = txt.IndexOf("<img", pos); // find the start tag again.
          pos = txt.IndexOf(">", pos);   // find the endtag of the <img tag
          txt = txt.Insert(pos + 1, imageParagraphWrap[1]);   // insert the paragraph close tag.
          modified = true;
        }
        else
        {
          String beforeTag = "";
          String afterTag = "";
          int end = skipBack(txt, pos - 1, new char[] { ' ', '\t', '\r', '\n' });
          int start;
          if (end != -1 && txt[end] == '>')
          {
            start = findBack(txt, end, new char[] { '<' });
            if (start != -1)
              beforeTag = txt.Substring(start, end - start + 1);
          }

          start = skipForward(txt, txt.IndexOf('>', pos) + 1, new char[] { ' ', '\t', '\r', '\n' });
          if (start != -1 && txt[start] == '<')
          {
            end = findForward(txt, start, new char[] { '>' });
            if (end != -1)
              afterTag = txt.Substring(start, end - start + 1);
          }
          if (beforeTag.Length < 2 ||
              beforeTag.Substring(0, 2) != "<p" ||
              afterTag != "</p>")
          {
            txt = txt.Insert(pos, imageParagraphWrap[0]);

            pos = txt.IndexOf("<img", pos); // find the start tag again.
            pos = txt.IndexOf(">", pos);   // find the endtag of the <img tag
            txt = txt.Insert(pos + 1, imageParagraphWrap[1]);   // insert the paragraph close tag.
            modified = true;
          }

          pos++;
        }
        pos = txt.IndexOf("<img", pos);
      }
      return modified;
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static bool UnwrapImages(ref String txt)
    {
      int pos = txt.IndexOf(imageParagraphWrap[0]);
      bool modified = false;
      while (pos != -1)
      {
        txt = txt.Remove(pos, imageParagraphWrap[0].Length);
        pos = txt.IndexOf(imageParagraphWrap[1], pos);
        if (pos != -1)
          txt = txt.Remove(pos, imageParagraphWrap[1].Length);
        pos = txt.IndexOf(imageParagraphWrap[0], pos);
        modified = true;
      }
      return modified;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonViewOutputLog_Click(object sender, EventArgs e)
    {
      if (File.Exists(MainForm.OutputFile))
        Process.Start(MainForm.OutputFile);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
    {
      buttonViewOutputLog.Enabled = File.Exists(MainForm.OutputFile);
    }
    /// <summary>
    /// 
    /// </summary>
    public void UpdateCatList()
    {
      if (comboBoxSectionList.SelectedIndex != -1)
      {
        ListBoxItem lbi = (ListBoxItem)comboBoxSectionList.Items[comboBoxSectionList.SelectedIndex];
        SelectedSectionId = ((String[])lbi.Param)[0];
        UpdateCatList(SelectedSectionId, SelectedCategoryId);
      }
      else
      {
        comboBoxSectionList.Items.Clear();
        comboBoxCategoryList.Items.Clear();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="SectionId"></param>
    /// <param name="CatId"></param>
    public void UpdateCatList(String SectionId, String CatId)
    {
      comboBoxCategoryList.ClearAll();
      if (SectionId.Length == 0)
        return;

      if (!MamboConnection.IsOpen)
        return;

      MySqlCommand myCommand = null;
      try
      {
        String sql = String.Format("SELECT `id`,`title`,`name` FROM #__categories WHERE section='{0}' and published=1", SectionId.Trim());
        myCommand = MamboConnection.CreateCmd(sql);
        myCommand.CommandTimeout = 20;
        MySqlDataReader reader = myCommand.ExecuteReader();

        comboBoxCategoryList.Sorted = true;
        Object SelectedItem = null;
        while (reader.Read())
        {
          String[] param = new String[] { reader.GetString("id"), reader.GetString("name") };
          ListBoxItem item = new ListBoxItem(reader.GetString("title"), param);
          comboBoxCategoryList.Items.Add(item);
          if (param[0] == CatId)
          {
            SelectedItem = item;
          }
        }

        reader.Close();
        if (SelectedItem != null)
          comboBoxCategoryList.SelectedItem = SelectedItem;

        if (comboBoxCategoryList.Items.Count > 0 && comboBoxCategoryList.SelectedIndex < 0)
        {
          comboBoxCategoryList.SelectedIndex = 0;
        }
      }
      finally
      {
        if (myCommand != null)
          myCommand.Dispose();
        //MainForm.CloseConnection();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void comboBoxCategoryList_SelectedIndexChanged(object sender, EventArgs e)
    {
      ListBoxItem item = (ListBoxItem)comboBoxCategoryList.SelectedItem;
      SelectedCategoryId = ((String[])item.Param)[0];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void comboBoxSectionList_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (formIsLoading)
        return;

      ListBoxItem item = (ListBoxItem)comboBoxSectionList.SelectedItem;
      SelectedSectionId = ((String[])item.Param)[0];
      UpdateCatList(SelectedSectionId, String.Empty);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void UserList_ItemCheck(object sender, ItemCheckEventArgs e)
    {
      if (UserList.CheckedItems.Count > 0)
      {
        for (int index = 0; index < UserList.Items.Count; index++)
        {
          if (index != e.Index)
          {
            UserList.SetItemCheckState(index, CheckState.Unchecked);
          }
        }
      }
      if (e.CurrentValue == CheckState.Unchecked)
      {
        ListBoxItem item = (ListBoxItem)UserList.Items[e.Index];
        SelectedUserId = (String)item.Param;
      }
      else
      {
        SelectedUserId = "";
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonUpdateContentList_Click(object sender, EventArgs e)
    {
      if (!MamboConnection.IsOpen)
        return;

      UpdateContentList();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonEditInput_Click(object sender, EventArgs e)
    {
      if (File.Exists(comboboxInputfile.Text))
      {
        Process.Start(comboboxInputfile.Text);
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonCheckImageParagraph_Click(object sender, EventArgs e)
    {   
      if (MessageBox.Show("Are you sure you want to wrap all the <img /> tags in all the Mambo context with a <p class=Image> .. </p> wrapper? \xA\xD" +
        "This can not be undone!", 
        "Make sure that you know what you are doing!", 
        MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
      {
        return;
      }

      List<String> updateStrings = new List<String>();

      try
      {
        if (!MamboConnection.IsOpen)
          return;

        String qry = "select `id`, `title`, `introtext`, `fulltext` from #__content";
        MySqlDataReader reader = MamboConnection.ExecuteReader(qry);
        if (reader.HasRows)
        {
          while (reader.Read())
          {
            String id = reader.GetString("id");
            // String title = reader.GetString("title");
            String introtext = reader.GetString("introtext");
            String fulltext = reader.GetString("fulltext");
            if (UCTextImport.ParseTextForImageParagraph(ref introtext) ||
                UCTextImport.ParseTextForImageParagraph(ref fulltext))
            {
              FieldValueList fvl = new FieldValueList();
              //fvl.Add("id", id);
              fvl.Add("introtext", introtext);
              fvl.Add("fulltext", fulltext);
              String update = fvl.GetUpdate("#__content", "where `id`='" + id + "'");
              updateStrings.Add(update);
            }
          }
          reader.Close();
          reader.Dispose();

          foreach (String s in updateStrings)
          {
            try
            {
              MamboConnection.ExecuteNonQuery(s, true);
            }
            catch (Exception ex)
            {
              Text2Mambo.Tools.Show.ShowMessage("Failed to update the database: " + ex.Message);
            }
          }
        }
      }
      finally
      {
        MainForm.CloseConnection();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void buttonUndoWrapImages_Click(object sender, EventArgs e)
    {
      if (MessageBox.Show("Are you sure you want to reove all the <img /> tags wrapping?",
        "Make sure that you know what you are doing!",
        MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
      {
        return;
      }

      List<String> updateStrings = new List<String>();

      try
      {
        if (!MamboConnection.IsOpen)
          return;

        String qry = "select `id`, `title`, `introtext`, `fulltext` from #__content";
        MySqlDataReader reader = MamboConnection.ExecuteReader(qry);
        if (reader.HasRows)
        {
          while (reader.Read())
          {
            String id = reader.GetString("id");
            // String title = reader.GetString("title");
            String introtext = reader.GetString("introtext");
            String fulltext = reader.GetString("fulltext");
            if (UCTextImport.UnwrapImages(ref introtext) ||
                UCTextImport.UnwrapImages(ref fulltext))
            {
              FieldValueList fvl = new FieldValueList();
              //fvl.Add("id", id);
              fvl.Add("introtext", introtext);
              fvl.Add("fulltext", fulltext);
              String update = fvl.GetUpdate("#__content", "where `id`='" + id + "'");
              updateStrings.Add(update);
            }
          }
          reader.Close();
          reader.Dispose();

          foreach (String s in updateStrings)
          {
            try
            {
              MamboConnection.ExecuteNonQuery(s, true);
            }
            catch (Exception ex)
            {
              Text2Mambo.Tools.Show.ShowMessage("Failed to update the database: " + ex.Message);
            }
          }
        }
      }
      finally
      {
        MainForm.CloseConnection();
      }
    }

    
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
South Africa South Africa
Started in 1988 programming in Pascal, making a 68000 emulator on a DOS platform. Then from Pascal to Clipper, to C++ and now using C#. I've been programming for all walks of businesses; opticians, opthomologist, carbage collectors, reinforcement steel producers, retail chains, and more.
I'm now travelling through Africa with a home-build expedition truck.

Comments and Discussions