Calendar webPart的源代码 (原创)

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Xml;
using SPDB.Business;
using System.Globalization;
using System.Threading;


namespace WebPartLibrary1
{
 /// <summary>
 /// Description for WebPart1.
 /// </summary>
 [DefaultProperty("Text"),ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>"),XmlRoot(Namespace="WebPartLibrary1")]

 public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart
 {

        private System.Web.UI.WebControls.Calendar _calendar;
  private System.Web.UI.WebControls.Image _imageTop;
  private System.Web.UI.WebControls.Image _imageTitle;
  private System.Web.UI.WebControls.Image _imageDownBlack;
  private System.Web.UI.WebControls.Image _imageMore;
  
  private System.Threading.Thread thread;
  private CultureInfo oldCulture;

  #region property

  private const string defaultListName = "事件";
  private const string defaultDetailUrl = "";
  private string _eventListName = defaultListName;
  private string _eventDetailUrl = defaultDetailUrl;

  [Browsable(true),
  Category("定制"),
  DefaultValue(defaultListName),
  WebPartStorage(Storage.Shared),
  FriendlyName("事件列表标题"),
  Description("事件列表标题.")]
  public string EventListName
  {
   get
   {
    return _eventListName;
   }

   set
   {
    _eventListName = value;
   }
  }
  
  [Browsable(true),
  Category("定制"),
  DefaultValue(defaultDetailUrl),
  WebPartStorage(Storage.Shared),
  FriendlyName("网站地址"),
  Description("网站地址.")]
  public string EventDetailUrl
  {
   get
   {
    return _eventDetailUrl;
   }

   set
   {
    _eventDetailUrl = value;

    if (!_eventDetailUrl.EndsWith("/"))
     _eventDetailUrl += "/";
   }
  }

  private const bool defaultNewWindow = true;
  private bool _NewWindow = defaultNewWindow;

  [Browsable(true),
  Category("定制"),
  DefaultValue(defaultNewWindow),
  WebPartStorage(Storage.Shared),
  FriendlyName("是否打开新窗口"),
  Description("超链接是否打开新窗口")]
  public bool NewWindow
  {
   get
   {
    return _NewWindow;
   }
  
   set
   {
    _NewWindow = value;
   }
  }


  private const string defaultStyleServer = "" ;
  private string _StyleServer=defaultStyleServer;

  [Browsable(true),
  Category("定制"),
  DefaultValue(defaultStyleServer),
  WebPartStorage(Storage.Shared),
  FriendlyName("标题风格URL"),
  Description("标题风格所在网站的URL")]
  public string StyleServer
  {
   get
   {
    return _StyleServer;
   }
  
   set
   {
    _StyleServer = value;

    if (_StyleServer!="" && _StyleServer.IndexOf("/",7)>0)
     _StyleServer = _StyleServer.Substring(0,_StyleServer.IndexOf("/",7));
   }
  }

  private const string defaultStyleName = "" ;
  private string _StyleName=defaultStyleName;

  [Browsable(true),
  Category("定制"),
  DefaultValue(defaultStyleName),
  WebPartStorage(Storage.Shared),
  FriendlyName("标题风格名"),
  Description("标题风格名")]
  public string StyleName
  {
   get
   {
    return _StyleName;
   }
  
   set
   {
    _StyleName = value;
   }
  }

  #endregion

  #region ToolPart

  /// <summary>
  /// This method gets the custom tool parts for this Web Part by overriding the
  /// GetToolParts method of the WebPart base class. You must implement
  /// custom tool parts in a separate class that derives from
  /// Microsoft.SharePoint.WebPartPages.ToolPart.
  /// </summary>
  ///<returns>An array of references to ToolPart objects.</returns>
  public override ToolPart[] GetToolParts()
  {
   ToolPart[] toolparts = new ToolPart[2];
   CustomPropertyToolPart custom = new CustomPropertyToolPart();
   WebPartToolPart wptp = new WebPartToolPart();
   custom.Expand("定制");
   toolparts[0] = custom;
   toolparts[1] = wptp;
   return toolparts;
  }
  
  #endregion

  #region CreateChildControls

  /// <summary>
  /// Add calendar to this webpart.
  /// </summary>
  protected override void CreateChildControls()
  {
            #region Style

   //Top
   _imageTop = new System.Web.UI.WebControls.Image();
   _imageTop.ImageUrl = "E:/SPS/WebPartLibrary1/img/top.gif";
   _imageTop.Width = 300;

   #region meno

   //DownBlack
   _imageDownBlack = new System.Web.UI.WebControls.Image();
   _imageDownBlack.ImageUrl = "E:/SPS/WebPartLibrary1/img/downblack.bmp";
   _imageDownBlack.Height = 30;
   _imageDownBlack.Width = 230;

   //Top
   _imageMore = new System.Web.UI.WebControls.Image();
   _imageMore.ImageUrl = "E:/SPS/WebPartLibrary1/img/more.gif";
   _imageMore.Height = 30;
   _imageMore.Width = 70;
   #endregion

   //Title    "~/img/calender.gif"    "../img/calender.gif"
   _imageTitle = new System.Web.UI.WebControls.Image();
   _imageTitle.ImageUrl = "E:/SPS/WebPartLibrary1/img/calender.gif";
   _imageTitle.Height= 40;
   _imageTitle.Width = 300;
           
   //Calendar
   _calendar = new System.Web.UI.WebControls.Calendar();

   _calendar.Width = 300;
   _calendar.Height = 200;
   _calendar.BorderWidth = 0;

   _calendar.SelectedDate = System.DateTime.Today;
   
   //星期的显示格式
   _calendar.DayNameFormat = DayNameFormat.Full;
   _calendar.FirstDayOfWeek = System.Web.UI.WebControls.FirstDayOfWeek.Default;
   
   //边界
   _calendar.DayStyle.BorderWidth = 0;
   _calendar.EnableViewState = true;
   
   //其他月份
   _calendar.OtherMonthDayStyle.ForeColor = Color.FromArgb(219,242,244);
   _calendar.OtherMonthDayStyle.BackColor = Color.FromArgb(219,242,244);
           
   //字体
   _calendar.Font.Name = "Arial";
   _calendar.ForeColor = Color.Green;
   
   //日期样式
   _calendar.DayStyle.ForeColor = Color.Black;
   _calendar.DayStyle.BackColor = Color.FromArgb(219,242,244);
   
   //标题部分
   _calendar.TitleStyle.HorizontalAlign = HorizontalAlign.Right;
   _calendar.TitleStyle.BackColor = Color.FromArgb(219,242,244);
   
   //星期头部分
   _calendar.DayHeaderStyle.BorderStyle = BorderStyle.Double;
   _calendar.DayHeaderStyle.BackColor = Color.FromArgb(124,135,141);
   _calendar.DayHeaderStyle.ForeColor = Color.White;
   _calendar.DayHeaderStyle.BorderColor = Color.FromArgb(219,242,244);
   _calendar.DayHeaderStyle.BorderWidth = 4;
   _calendar.DayHeaderStyle.Height = 1;
   
   //显示上/下月
   _calendar.ShowNextPrevMonth = true;
   
   #endregion
   
   #region Event

   //事件
            _calendar.DayRender += new System.Web.UI.WebControls.DayRenderEventHandler(Calendar_DayRender);
   _calendar.PreRender += new System.EventHandler(Calendar_PreRender);

   #endregion

   Controls.Add(_imageTop);
   Controls.Add(_imageTitle);
   Controls.Add(_calendar);
   Controls.Add(_imageDownBlack);
   Controls.Add(_imageMore);
  }

  #endregion

  #region RenderWebPart

  /// <summary>
  /// Render this Web Part to the output parameter specified.
  /// </summary>
  /// <param name="output"> The HTML writer to write out to </param>
  protected override void RenderWebPart(HtmlTextWriter output)
  {
   try
   {
    string titleStr="";
    if(_StyleServer!="" && _StyleName!="")
     titleStr=SPDB.Business.SPDBCommon.GetTitleStr(_StyleServer,_StyleName);

    if (titleStr!="")
    {
     titleStr = titleStr.Replace("#Title#",this.Title);
     titleStr = titleStr.Replace("#MoreUrl#",this.DetailLink);
     titleStr = titleStr.Replace("#Description#",this.Description);
     titleStr = titleStr.Replace("#AreaDescription#","");
     titleStr = titleStr.Replace("#Detail#","");
    }
    
    output.Write(titleStr);
                RenderChildren(output);
   }
   catch (Exception ex)
   {
    output.Write(ex.Message);
   }
   finally
   {
    output.Flush();
   }
  }

  #endregion

  #region Event Calendar_DayRender & Calendar_PreRender

  private void Calendar_DayRender(object sender, DayRenderEventArgs e)
  {
   thread.CurrentCulture = this.oldCulture;
           
   //Get each day's events and set it to Tooltips.
   GetEventSetTooltip(sender,e);
  }
  
  //Change Date Style is "日", "一", "二", "三", "四", "五", "六"

  private void Calendar_PreRender(object sender, EventArgs e)
  {
   thread = System.Threading.Thread.CurrentThread;
   oldCulture = thread.CurrentCulture;
   CultureInfo newci = (CultureInfo)oldCulture.Clone();
   newci.DateTimeFormat.DayNames = new string[] { "日", "一", "二", "三", "四", "五", "六" };
   newci.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Sunday;
   thread.CurrentCulture = newci;
  }

  #endregion

  #region GetEventSetTooltip

  private void GetEventSetTooltip (object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
  {
   e.Cell.Text = e.Day.DayNumberText;

   SPSite site=null;
   SPWeb mySite=null;

   try
   {
    string serverStr="",areaStr;

    if (EventDetailUrl!="")
    {
     int i = EventDetailUrl.IndexOf("/",7);
     serverStr = EventDetailUrl.Substring(0,i);
     areaStr = EventDetailUrl.Substring(serverStr.Length);

     site = new SPSite(serverStr);
     mySite = site.OpenWeb(areaStr);
    }
    else
    {
     site = SPControl.GetContextSite(Context);
     mySite = site.OpenWeb();
    }

    // Start to search the events of current day.
    SPList list = mySite.Lists[EventListName];

    string detailUrl = serverStr + list.DefaultViewUrl;

    SPQuery query = new SPQuery();
    query.Query = String.Format("<Where>"
     + "<Or>"
     + "<And>"
     + "<Or>"
     + "<And>"
     + "<Leq>"
     + "<FieldRef Name=\"EventDate\"></FieldRef>"
     + "<Value Type=\"DateTime\">"
     + "{0}"
     + "</Value>"
     + "</Leq>"
     + "<Geq>"
     + "<FieldRef Name=\"EndDate\"></FieldRef>"
     + "<Value Type=\"DateTime\">"
     + "{0}"
     + "</Value>"
     + "</Geq>"
     + "</And>"
     + "<And>"
     + "<Eq>"
     + "<FieldRef Name=\"EventDate\"></FieldRef>"
     + "<Value Type=\"DateTime\">"
     + "{0}"
     + "</Value>"
     + "</Eq>"
     + "<IsNull>"
     + "<FieldRef Name=\"EndDate\"></FieldRef>"
     + "</IsNull>"
     + "</And>"
     + "</Or>"
     + "<Eq>"
     + "<FieldRef Name=\"fRecurrence\"></FieldRef>"
     + "<Value Type=\"Integer\">0</Value>"
     + "</Eq>"
     + "</And>"
     + "<And>"
     + "<And>"
     + "<Leq>"
     + "<FieldRef Name=\"EventDate\"></FieldRef>"
     + "<Value Type=\"DateTime\">"
     + "{0}"
     + "</Value>"
     + "</Leq>"
     + "<Geq>"
     + "<FieldRef Name=\"EndDate\"></FieldRef>"
     + "<Value Type=\"DateTime\">"
     + "{0}"
     + "</Value>"
     + "</Geq>"
     + "</And>"
     + "<Neq>"
     + "<FieldRef Name=\"fRecurrence\"></FieldRef>"
     + "<Value Type=\"Integer\">0</Value>"
     + "</Neq>"
     + "</And>"
     + "</Or>"
     + "</Where>", e.Day.Date);

    SPListItemCollection items = list.GetItems(query);

    String strTooltip = "";
    foreach (SPListItem item in items)
    {
     if (SPDBCommon.ObjToStr(item["fRecurrence"]) == "0")
     {
      strTooltip += SPDBCommon.ObjToStr(item["Title"]) + "("
       + SPDBCommon.FormatDateTime(item["EventDate"]) + " ~ "
       + SPDBCommon.FormatDateTime(item["EndDate"]) + ")"
       + "\n";
     }
     else
     {
      if (IsDateOverlaped(e.Day.Date, (DateTime)item["EventDate"], SPDBCommon.ObjToStr(item["RecurrenceData"])))
      {
       strTooltip += SPDBCommon.ObjToStr(item["Title"]) + "("
        + SPDBCommon.FormatDateTime(item["EventDate"]) + " ~ "
        + SPDBCommon.FormatDateTime(item["EndDate"]) + ")"
        + "\n";
      }
     }
    }

    if (strTooltip != "")
    {
     //判断是否是当前月
     if(!e.Day.IsOtherMonth)
     {
      e.Cell.Font.Underline = true;
     }
     else{
      e.Cell.Font.Size = -1;
      e.Cell.Enabled = false;
     }
     e.Cell.ToolTip = strTooltip;
     e.Cell.Text = "<a href='" + detailUrl + "?CalendarDate=" + SPDBCommon.FormatDateTime(e.Day.Date)+"'";
     if (NewWindow)
      e.Cell.Text += " target=_blank";
     e.Cell.Text += ">" + e.Day.DayNumberText + "</a>";
    }
   }
   catch (System.Exception ex)
   {
    e.Cell.ToolTip += ex.Message;
   }
   finally
   {
    site.Close();
    mySite.Close();
   }
  }

  #endregion
  
  #region IsDateOverlaped

  /// <summary>
  /// If fRecurrence == -1, then check if current day is Overlaped with the event.
  /// </summary>
  /// <param name="dtCurrent">current day</param>
  /// <param name="dtStart">the day when the event start</param>
  /// <param name="strXML">the event description.</param>
  /// <returns>true if the current day is overlaped with the event</returns>
  private bool IsDateOverlaped(DateTime dtCurrent, DateTime dtStart, string strXML)
  {
   string sFirstDayOfWeek;
   double dFrequency;
   TimeSpan TS = new TimeSpan(dtCurrent.Ticks - dtStart.Ticks);
   object[] arrWeekday = {
           new object[] {"su", DayOfWeek.Sunday},
           new object[] {"mo", DayOfWeek.Monday},
           new object[] {"tu", DayOfWeek.Tuesday},
           new object[] {"we", DayOfWeek.Wednesday},
           new object[] {"th", DayOfWeek.Thursday},
           new object[] {"fr", DayOfWeek.Friday},
           new object[] {"sa", DayOfWeek.Saturday}
          };
   

   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.LoadXml(strXML);

   sFirstDayOfWeek = xmlDoc.SelectSingleNode("/recurrence/rule/firstDayOfWeek").InnerText;

   XmlNode repeatChildNode = xmlDoc.SelectSingleNode("/recurrence/rule/repeat").FirstChild;

   switch (repeatChildNode.Name)
   {
    case "daily":
     dFrequency = Convert.ToDouble(repeatChildNode.Attributes["dayFrequency"].InnerText);
     if (TS.TotalDays % dFrequency == 0)
      return true;
     break;
    case "weekly":
     foreach(object[] oWeekday in arrWeekday)
     {
      if (dtCurrent.DayOfWeek != (DayOfWeek)oWeekday[1])
       continue;
      if (repeatChildNode.Attributes.GetNamedItem(oWeekday[0].ToString()) == null)
       continue;
      if (repeatChildNode.Attributes[oWeekday[0].ToString()].InnerText == "TRUE")
      {
       dFrequency = Convert.ToDouble(repeatChildNode.Attributes["weekFrequency"].InnerText);
       if (Convert.ToInt32(TS.TotalDays/7) % dFrequency == 0)
        return true;
      }
     }
     break;
    case "monthly":
     if (dtCurrent.Day.ToString() != repeatChildNode.Attributes["day"].InnerText)
      return false;
     dFrequency = Convert.ToDouble(repeatChildNode.Attributes["monthFrequency"].InnerText);
     if (DateAndTime.DateDiff(DateInterval.Month,dtStart, dtCurrent, Microsoft.VisualBasic.FirstDayOfWeek.Monday, Microsoft.VisualBasic.FirstWeekOfYear.System) % dFrequency == 0)
      return true;
     break;
    case "monthlyByDay":
     if (GetWeekdayOfMonth(dtCurrent).IndexOf(repeatChildNode.Attributes["weekdayOfMonth"].InnerText) == -1)
      return false;

     foreach(object[] oWeekday in arrWeekday)
     {
      if (dtCurrent.DayOfWeek != (DayOfWeek)oWeekday[1])
       continue;
      if (repeatChildNode.Attributes.GetNamedItem(oWeekday[0].ToString()) == null)
       continue;
      if (repeatChildNode.Attributes[oWeekday[0].ToString()].InnerText == "TRUE")
      {
       dFrequency = Convert.ToDouble(repeatChildNode.Attributes["monthFrequency"].InnerText);
       if (DateAndTime.DateDiff(DateInterval.Month,dtStart, dtCurrent, Microsoft.VisualBasic.FirstDayOfWeek.Monday, Microsoft.VisualBasic.FirstWeekOfYear.System) % dFrequency == 0)
        return true;
      }
     }
     break;
    case "yearly":
     if (dtCurrent.Month != dtStart.Month || dtCurrent.Day != dtStart.Day)
      return false;
     dFrequency = Convert.ToDouble(repeatChildNode.Attributes["yearFrequency"].InnerText);
     if ((dtCurrent.Year - dtStart.Year) % dFrequency == 0)
      return true;
     break;
   }

   return false;
  }

  #endregion

  #region GetWeekdayOfMonth

  /// <summary>
  /// Get the weekday number of the month.
  /// </summary>
  /// <param name="dtCurrent"></param>
  /// <returns></returns>
  private string GetWeekdayOfMonth(DateTime dtCurrent)
  {
   DateTime dtFirstDayOfMonth = new DateTime(dtCurrent.Year, dtCurrent.Month, 1);
   TimeSpan TS = new TimeSpan(dtCurrent.Ticks - dtFirstDayOfMonth.Ticks);

   DateTime dtLastDayOfMonth = dtFirstDayOfMonth.AddMonths(1).AddDays(-1);
   TimeSpan tsLast = new TimeSpan(dtLastDayOfMonth.Ticks - dtCurrent.Ticks);

   string sRet = "";

   switch (Convert.ToInt16(TS.TotalDays/7))
   {
    case 0:
     sRet += "first";
     break;
    case 1:
     sRet += "second";
     break;
    case 2:
     sRet += "third";
     break;
    case 3:
     sRet += "fourth";
     break;
   }

   // Maybe the last week also is the fourth week.
   if (Convert.ToInt16(tsLast.TotalDays/7) == 0)
    sRet += ";last";

   return sRet;
  }

  #endregion

 }
}

------------------------------------------------------------------

using System;
using Microsoft.SharePoint;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Xml;
using Microsoft.SharePoint.Utilities;

namespace SPDB.Business
{
 /// <summary>
 /// Summary description for SPDBCommon.
 /// </summary>
 public class SPDBCommon
 {
  public SPDBCommon()
  {
   //
   // TODO: Add constructor logic here
   //
  }


  public static void WriteLog(string sLogFile, string sLogMessage)
  {
   try
   {
    StreamWriter w = File.AppendText(sLogFile);

    w.Write("\r\nLog Entry : ");
    Console.Write("\r\nLog Entry : ");
    w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
     DateTime.Now.ToLongDateString());
    Console.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
     DateTime.Now.ToLongDateString());
    w.WriteLine("  {0}", sLogMessage);
    Console.WriteLine("  {0}", sLogMessage);
    // Update the underlying file.
    w.Flush();

    // Close the writer and underlying file.
    w.Close();

   }
   catch(Exception e)
   {
    Console.Write(e.Message );
   }
  }

  /// <summary>
  /// Check if the news file is already uploaded.
  /// </summary>
  /// <param name="strFile"></param>
  /// <returns></returns>
  public static bool IsFileUploaded(string strFile)
  {
   string sTemp = "NoDocID";

   string sDocID = strFile.Substring(0, strFile.LastIndexOf("."));
   sDocID = sDocID.Substring(sDocID.LastIndexOf("_") + 1);

   if (sDocID == "") return false;

   string sConnectionString = ConfigurationSettings.AppSettings.Get("SPDB.WorldNewsExterior.SQLConnectionString");
   
   string strSQL = "SELECT ext8 FROM CMS_DOCMAIN WHERE doc_id = " + sDocID;

   SqlConnection newsConn = new SqlConnection(sConnectionString);

   SqlCommand selectCMD = new SqlCommand(strSQL, newsConn);
   selectCMD.CommandTimeout = 5;

   newsConn.Open();

   SqlDataReader reader = reader = selectCMD.ExecuteReader();

   if (reader.Read())
   {
    sTemp = reader.GetString(0);
   }

   newsConn.Close();

   // If already uploaded or NoDocID in this database, then not need upload, so return true;
   if (sTemp == "Uploaded" || sTemp == "NoDocID")
   {
    return true;
   }

   return false;
  }

  /// <summary>
  /// Convert object to string, return "" if object is null.
  /// </summary>
  /// <param name="oItem">input object param</param>
  /// <returns></returns>
  public static string ObjToStr(object oItem)
  {
   if (oItem == null)
   {
    return "";
   }
   else
   {
    return oItem.ToString();
   }
  }

  /// <summary>
  /// Convert date object to string.
  /// </summary>
  /// <param name="oItem">input date object param</param>
  /// <returns></returns>
  public static string FormatDateTime(object oItem)
  {
   if (oItem == null)
   {
    return "";
   }
   else
   {
    DateTime dtItem = (DateTime)oItem;
    return dtItem.Year + "-" + dtItem.Month + "-" + dtItem.Day;
   }
  }

  /// <summary>
  /// Get the world news file name. This logic come from outter news system of ChuangYang company.
  /// </summary>
  /// <param name="sDate"></param>
  /// <param name="sChID"></param>
  /// <param name="sDocID"></param>
  /// <returns></returns>
  public static string GetWorldNewsFileName(string sDate, string sChID, string sDocID)
  {
   DateTime dtTemp = DateTime.Parse(sDate);

   return FormatNumberString(dtTemp.Year.ToString(), 4)
    + FormatNumberString(dtTemp.Month.ToString(), 2)
    + "/"
    + FormatNumberString(dtTemp.Month.ToString(),2)
    + FormatNumberString(dtTemp.Day.ToString(),2)
    + "_"
    + sChID
    + "_"
    + sDocID
    + ".aspx";
  }

  /// <summary>
  /// Add the "0" char at the begin of the string.
  /// </summary>
  /// <param name="sNumber"></param>
  /// <param name="iLen"></param>
  /// <returns></returns>
  public static string FormatNumberString(string sNumber, int iLen)
  {
   return ((string)("0000000000" + sNumber)).Substring(10 + sNumber.Length - iLen);
  }

  /// <summary>
  /// Set file uploaded flag.
  /// </summary>
  /// <param name="strFile"></param>
  public static void SetFileUploaded(string strFile)
  {
   string sDocID = strFile.Substring(0, strFile.LastIndexOf("."));
   sDocID = sDocID.Substring(sDocID.LastIndexOf("_") + 1);

   if (sDocID == "") return;

   string sConnectionString = ConfigurationSettings.AppSettings.Get("SPDB.WorldNewsExterior.SQLConnectionString");
   
   string strSQL = "UPDATE CMS_DOCMAIN SET ext8 = 'Uploaded' WHERE doc_id = " + sDocID;

   SqlConnection newsConn = new SqlConnection(sConnectionString);

   SqlCommand updateCMD = new SqlCommand(strSQL, newsConn);
   updateCMD.CommandTimeout = 5;
   newsConn.Open();

   int intRows = updateCMD.ExecuteNonQuery();

   // Copy the record to table CMSNEWS of internal sql server.
   updateCMD.CommandText = "SELECT * FROM CMSNEWS WHERE doc_id = " + sDocID;
   SqlDataReader dbReader = updateCMD.ExecuteReader();
   
   string sInternalConnectionString = ConfigurationSettings.AppSettings.Get("SPDB.WorldNews.SQLConnectionString");
   
   if (dbReader.Read())
   {
    strSQL = "SELECT type_id, typecode, typename, CHID, DIST_TIME, AUDIT_STATUS,"
     + " doc_id, doc_title, doc_dt_lastmodified, doc_dt_new, ext8, doc_level, doc_hot"
     + " FROM CMSNEWS WHERE doc_id = " + sDocID;

    SqlDataAdapter dbAdapter = new SqlDataAdapter(strSQL, sInternalConnectionString);
    SqlCommandBuilder dbCMDBuilder = new SqlCommandBuilder(dbAdapter);
    DataTable dtNews = new DataTable();

    dbAdapter.Fill(dtNews);

    DataRow drNews;
    if (dtNews.Rows.Count == 0)
    {
     drNews = dtNews.NewRow();
    }
    else
    {
     drNews = dtNews.Rows[0];
    }
    drNews["type_id"] = dbReader.GetValue(0);
    drNews["typecode"] = dbReader.GetValue(1);
    drNews["typename"] = dbReader.GetValue(2);
    drNews["CHID"] = dbReader.GetValue(3);
    drNews["DIST_TIME"] = dbReader.GetValue(4);
    drNews["AUDIT_STATUS"] = dbReader.GetValue(5);
    drNews["doc_id"] = dbReader.GetValue(6);
    drNews["doc_title"] = dbReader.GetValue(7);
    drNews["doc_dt_lastmodified"] = dbReader.GetValue(8);
    drNews["doc_dt_new"] = dbReader.GetValue(9);
    drNews["ext8"] = dbReader.GetValue(10);
    drNews["doc_level"] = dbReader.GetValue(11);
    drNews["doc_hot"] = dbReader.GetValue(12);

    if (dtNews.Rows.Count == 0)
    {
     dtNews.Rows.Add(drNews);
    }

    dbAdapter.Update(dtNews);
   }

   newsConn.Close();

  }

  /// <summary>
  /// Create Xml for WorldNews webpart.
  /// </summary>
  public static void CreateWorldNewsXml()
  {
   try
   {
    string destPath = ConfigurationSettings.AppSettings.Get("destWorldNewsXmlPath");
    if (destPath!="")
    {
     StreamWriter sw = File.CreateText(destPath + "\\WorldNews.xml");

     string strTemp = "";
     string strSQL = "SELECT TOP 100 * FROM CMSNEWS WHERE ext8 = 'Uploaded' ORDER BY dist_time DESC, type_id";
     //string strSQL = ConfigurationSettings.AppSettings.Get("strSQL_GetWorldNews");

     SqlConnection newsConn = new SqlConnection(ConfigurationSettings.AppSettings.Get("SPDB.WorldNewsExterior.SQLConnectionString"));

     SqlCommand selectCMD = new SqlCommand(strSQL, newsConn);
     SqlDataAdapter custDA = new SqlDataAdapter();
     custDA.SelectCommand = selectCMD;

     newsConn.Open();

     DataSet custDS = new DataSet();
     custDA.Fill(custDS, "WorldNews");
   
     sw.Write("<WorldNews>\n");
   
     foreach (DataRow row in custDS.Tables["WorldNews"].Rows)
     {
      strTemp = GetWorldNewsFileName(row["doc_dt_new"].ToString(),
       row["chid"].ToString(),
       row["doc_id"].ToString());

      sw.Write ("<News Title=\"" + SPEncode.HtmlEncode(row["doc_title"].ToString()) + "\" Page=\"" + strTemp + "\" doc_dt_new=\"" + row["doc_dt_new"].ToString() + "\"/>\n");
     }

     sw.Write("</WorldNews>\n");
     sw.Close();

     newsConn.Close();
    }
    else
    {
     throw(new Exception("No destWorldNewsXmlPath Configuration!"));
    }
   }
   catch(Exception e)
   {
    throw(e);
   }
  }

  
  public static string GetTitleStr(string styleServer, string styleName)
  {
   string titleStr="";
   SPSite sites = new SPSite(styleServer);
   SPWeb mysite = sites.OpenWeb("/sites/siteconfig");
 
   SPListItemCollection items = mysite.Lists["stylelibrary"].Items;

   string styleUrl;
   foreach (SPListItem item in items)
   {
    if (item["BaseName"].ToString()==styleName)
    {
     if (item.File.Exists)
     {
      styleUrl =styleServer + item.File.ServerRelativeUrl;
      System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(styleUrl);
      System.Net.ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
      request.Credentials = credentials;
      System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
      System.IO.Stream stream = response.GetResponseStream();

      System.IO.StreamReader reader = new System.IO.StreamReader(stream,System.Text.Encoding.UTF8);

      titleStr = reader.ReadToEnd();
      int start = titleStr.IndexOf("<!-- Begin Panel Layout -->");
      int end = titleStr.IndexOf("<!-- End Panel Layout -->");
      if (start>0 && end > start)
       titleStr = titleStr.Substring(start,end-start);
     }
    }
   }
   return titleStr;
  }
 }
}

posted @ 2005-12-18 16:12  RicoRui  阅读(1621)  评论(0编辑  收藏  举报