.net中一些所封装的类(Control)

using System;
using System.IO;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Collections;
using System.Web.UI.WebControls;
using Microsoft.Web.UI.WebControls;
using System.Drawing;
using System.Text;
using OWC;

namespace JSL.MVC.Page
{
///

1<summary>   
2/// Controls 的摘要说明。   
3/// </summary>

public class Controls
{
private Controls()
{
}
#region string
public static string Encrypto(string Source)
{
System.Security.Cryptography.HashAlgorithm HashCryptoService;
HashCryptoService = new System.Security.Cryptography.SHA1Managed();

byte[] bytIn = System.Text.UTF8Encoding.UTF8.GetBytes(Source);
byte[] bytOut = HashCryptoService.ComputeHash(bytIn);
return Convert.ToBase64String(bytOut);
}
#endregion

#region BaseDataList
public void BindBaseList(System.Web.UI.WebControls.BaseDataList bdl_object,DataSet ds, string tbName)
{
bdl_object.DataSource=ds.Tables[tbName];
bdl_object.DataBind();
}

public void BindBaseList(System.Web.UI.WebControls.BaseDataList bdl_object,DataTable dt)
{
bdl_object.DataSource=dt;
bdl_object.DataBind();
}
#endregion

#region DropDownList
public static void CreateDropDownList(DropDownList ddl_object, DataTable dt, string s_text,string s_value)
{
ddl_object.DataSource = dt;
ddl_object.DataTextField = s_text;
ddl_object.DataValueField = s_value;
ddl_object.DataBind();
}

public static void CreateDropDownList(DropDownList ddl_object, DataSet ds, string s_text,string s_value)
{
ddl_object.DataSource = ds;
ddl_object.DataTextField = s_text;
ddl_object.DataValueField = s_value;
ddl_object.DataBind();
}

public static void CreateDropDownList(DropDownList ddl_object, string s_text, string s_value)
{
ListItem li = new ListItem(s_text, s_value);
ddl_object.Items.Add(li);
}

public static void CreateDropDownList(DropDownList ddl_object, string[] s_text, string[] s_value)
{
for (int i = 0; i < s_text.Length; i++)
{
ListItem li = new ListItem(s_text[i],s_value[i]);
ddl_object.Items.Add(li);
}
}

public static void CopyDropDownList(DropDownList ddl_source, DropDownList ddl_target)
{
ddl_target.Items.Clear();
ddl_target.DataTextField = ddl_source.DataTextField;
ddl_target.DataTextFormatString = ddl_source.DataTextFormatString;
ddl_target.DataValueField = ddl_source.DataValueField;
for (int i = 0; i < ddl_source.Items.Count; i++)
{
ddl_target.Items.Add(ddl_source.Items[i]);
}
}

public static void SetDropDownListValue(DropDownList ddl_object, string s_value)
{
foreach(ListItem li in ddl_object.Items)
{
if (li.Value == s_value)
{
ddl_object.SelectedValue = s_value;
break;
}
else
{
ddl_object.SelectedValue = null;
}
}
}

public static void SetDropDownListValue(DropDownList[] ddl_object,string[] s_value)
{
int i = 0;
foreach(DropDownList ddl in ddl_object)
{
SetDropDownListValue(ddl,s_value[i++]);
}
}
#endregion

#region TextBox
protected static void CopyTextBox(TextBox tb_source, TextBox tb_target)
{
tb_target.Text = tb_source.Text;
}

protected static void SetTextBoxValue(TextBox tb_object, string s_value)
{
tb_object.Text = s_value;
}

protected static void SetTextBoxValue(TextBox[] tb_object,string[] s_value)
{
int i = 0;
foreach(TextBox dt in tb_object)
{
SetTextBoxValue(dt,s_value[i++]);
}
}
#endregion

#region TreeView
///

1<summary>   
2/// 创建树形结构   
3/// </summary>

///

1<param name="dt"/>

要传入的数据表
///

1<param name="treenodecollection"/>

树结点容器集合
///

1<param name="MapNodeData"/>

结点主键
///

1<param name="MapText"/>

显示内容
///

1<param name="MapNavigateURL"/>

导航路径
///

1<param name="ImageURL"/>

图片地址
///

1<param name="ParentName"/>

结点父键
///

1<param name="RelationOperation"/>

结点过滤关系运算符
///

1<param name="ParentValue"/>

运算比较值
///

1<param name="ParentValueType"/>

比较值类型
///

1<param name="SortExpression"/>

排序方式
///

1<param name="bcheckbox"/>

选择框显示与否
///

1<param name="MapStatus"/>

选择框的内容
///

1<param name="MapTarget"/>

用于树保存时的分层标记
public static void CreateViewTree(DataTable dt, TreeNodeCollection treenodecollection,
string MapNodeData, string MapText, string MapNavigateURL, string ParentName,
string RelationOperation, string ParentValue, string ParentValueType,string SortExpression,
bool bcheckbox, string MapStatus, string MapTarget)
{
if (ParentValueType == "'") ParentValue = ParentValueType + ParentValue + ParentValueType;

string str = ParentName + RelationOperation + ParentValue;
DataRow[] drs = dt.Select( ParentName + RelationOperation + ParentValue, SortExpression);
foreach(DataRow dr in drs)
{
TreeNode treenode = new TreeNode();
treenode.Text = dr[MapText].ToString();
try
{
treenode.NavigateUrl = dr[MapNavigateURL].ToString();
}
catch{treenode.NavigateUrl = "";}
treenode.CheckBox = bcheckbox;
if (MapTarget != "" && MapTarget != null) treenode.TreeNodeXsltSrc = dr[MapTarget].ToString();
if (treenode.CheckBox)
{
bool bcheck ;
try
{
bcheck = (dr[MapStatus].ToString() == "1");
}
catch{bcheck = false;}
treenode.Checked =bcheck ;
}
string treenodenodedata = treenode.NodeData = dr[MapNodeData].ToString();
treenodecollection.Add(treenode);
if (ParentValueType == "'") treenodenodedata =ParentValueType+ treenodenodedata + ParentValueType;

DataRow[] tmpdrs = dt.Select(ParentName + RelationOperation + treenodenodedata, SortExpression);
if ( tmpdrs.Length > 0)
{
CreateViewTree(dt,treenode.Nodes,MapNodeData,MapText,MapNavigateURL,ParentName,RelationOperation,treenode.NodeData,ParentValueType,SortExpression,bcheckbox,MapStatus,MapTarget);
}
}
}
#endregion

#region Session
public static bool CheckSession(string CheckSession,System.Web.UI.Page WebPage)
{
bool b=false;
foreach(string sTmp in WebPage.Session.Keys)
{
if (sTmp.Equals(CheckSession))
{
b = true;
break;
}
}
return b;
}

public static void CheckSession(string CheckSession,System.Web.UI.Page WebPage,string ErrorPage)
{
bool b=false;
foreach(string sTmp in WebPage.Session.Keys)
{
if (sTmp.Equals(CheckSession))
{
b = true;
break;
}
}

if (!b) WebPage.Response.Redirect(ErrorPage);
}
#endregion

#region Reponse
public static void ResponsePage(System.Web.UI.Page WebPage,string sUrl,string sChoose)
{
try
{
switch(sChoose)
{
case "1":
WebPage.Response.Write("

1<script>window.location.href='"+sUrl+"';</script>

");
break;
case "2":
WebPage.Server.Transfer(sUrl );
break;
case "3":
WebPage.Response.Redirect(sUrl);
break;
case "debug":
WebPage.Response.Write("

1<script>alert('"+sUrl+"')</script>

");
break;
default :
WebPage.Response.Write(sUrl);
break;
}
}
catch
{
WebPage.Response.Write("Error URL:"+sUrl );
}
}
#endregion

#region Server To Client JAVASCRIPT
public void javaScript(string alert ,System.Web.UI.Page WebPage)
{
WebPage.RegisterStartupScript("script","

1<script language="javascript">alert('"+alert+"');</script>

");
}
#endregion

#region Split DataGrid
public static string[] SplitPage(System.Web.UI.Page CurPage,DataGrid dgSplit,DataTable dtSplit,int iRowsSplitPage )
{
string PAGE_OBJECT = "page"+dgSplit.ID;
string sPage = "1";
int iCurPage = 1;
if (CurPage.Request.QueryString[PAGE_OBJECT]!=null) sPage = CurPage.Request.QueryString[PAGE_OBJECT].ToString();
try { iCurPage = Int32.Parse(sPage); }
catch { iCurPage = 1; }

int start = (int)((iCurPage - 1) * iRowsSplitPage);
if (start < 0) start = 0;
int to = (int)(iCurPage * iRowsSplitPage);

DataView dv = dtSplit.DefaultView;
int iResults = dv.Count;
int a1=0;
int iPageCount = Math.DivRem(iResults,iRowsSplitPage,out a1);
if (a1>0) iPageCount++;
if (iCurPage > iPageCount || iCurPage<= 0) iCurPage = 1;
if (iCurPage == iPageCount) to = dv.Count;

DataTable dt = dv.Table.Clone();
DataRow dr;
for(int i=start;i

  1<iresults;i++) '="" (k="0)" +="&lt;a href='?" +page_object+"="+ 1.ToString() + " -="" ;="" =="0);" dataview="" dataview(dt);="" dgsplit.databind();="" dgsplit.datasource="dvResult;" dgsplit.visible="!(dvResult.Count" dr="dt.NewRow();" dr[k]="dv.Table.Rows[i][k];" dt.acceptchanges();="" dt.rows.add(dr);="" dvresult="new" else="" for(int="" i;="" iendpage="iPageCount;" if="" if(i<to)="" int="" k="0;k&lt;dv.Table.Columns.Count;k++)" string="" strnav="" {="" }="">首 页 ";   
  2if (iCurPage&gt;1)   
  3{   
  4strNav += "<a href='?"+PAGE_OBJECT+"="+ (iCurPage - 1).ToString() + "'>上 页</a> ";   
  5}   
  6else   
  7{   
  8strNav += " 上 页 ";   
  9}   
 10if (iCurPage&gt;11)   
 11{   
 12strNav += "<a href='?"+PAGE_OBJECT+"=1'>1</a> ...";   
 13}   
 14if (iPageCount &gt; iCurPage + 10) iEndPage = iCurPage + 10;   
 15for (int i = iCurPage - 10; i &lt; iEndPage + 1; i++)   
 16{   
 17if(i&gt;=1)   
 18{   
 19if (i==iCurPage)   
 20{   
 21strNav +="<font color="#990000"><strong>"+ i.ToString() + "</strong></font> ";   
 22}   
 23else   
 24{   
 25strNav += "<a href='?"+PAGE_OBJECT+"="+ i.ToString() + "'>"+ i.ToString() +"</a> ";   
 26}   
 27}   
 28} 
 29
 30if ((iCurPage+10) &lt; iPageCount)   
 31strNav += "... <a href='?"+PAGE_OBJECT+"="+ iPageCount.ToString() + "'>"+ iPageCount.ToString() + "</a>";   
 32if (iCurPage &lt; iPageCount)   
 33{   
 34strNav += " <a href='?"+PAGE_OBJECT+"="+ (iCurPage+1).ToString() + "'>下 页</a> ";   
 35}   
 36else   
 37{   
 38strNav += " 下 页 ";   
 39}   
 40strNav += " <a href='?"+PAGE_OBJECT+"="+ (iPageCount).ToString() + "'>末 页</a> "; 
 41
 42  
 43string[] strNavResult = new string[2];   
 44strNavResult[0] = strNav;   
 45strNavResult[1] = "[共"+ iResults.ToString() +"条][第"+ (start+1).ToString() +"-"+ to.ToString() +"条][共"+ iPageCount.ToString() +"页]" ; 
 46
 47return strNavResult;   
 48}   
 49#endregion 
 50
 51#region DataGrid To Excel   
 52public static void DataGrid2Excel(DataGrid dg, string filename)   
 53{   
 54OWC.SpreadsheetClass xlsheet = new SpreadsheetClass();   
 55int ihead = 0;   
 56foreach(DataGridColumn dgc in dg.Columns)   
 57{   
 58xlsheet.ActiveSheet.Cells[1, ihead + 1] = dgc.HeaderText;   
 59// xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[1, i + 1]).Font.Bold = true;   
 60// xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[1, i + 1]).Font.Color = "red";   
 61ihead++;   
 62} 
 63
 64int icols = dg.Items[0].Cells.Count;   
 65for (int j = 0; j &lt; dg.Items.Count; j++)   
 66{   
 67for (int i = 0; i &lt; icols; i++)   
 68{   
 69xlsheet.ActiveSheet.Cells[j + 2, i + 1] = dg.Items[j].Cells[i].Text.Replace(" "," ");   
 70}   
 71} 
 72
 73try   
 74{   
 75//System.Web.HttpContext.Current.Server.MapPath   
 76xlsheet.ActiveSheet.Export(filename, OWC.SheetExportActionEnum.ssExportActionOpenInExcel);   
 77}   
 78catch   
 79{   
 80return;   
 81}   
 82}   
 83#endregion 
 84
 85#region HostName   
 86public static string GetHostName()   
 87{   
 88return System.Net.Dns.GetHostName();   
 89} 
 90
 91public static System.Net.IPHostEntry GetHostByName(string hostname)   
 92{   
 93return System.Net.Dns.GetHostByName(hostname);   
 94} 
 95
 96#endregion 
 97
 98#region Process   
 99private void KillProcess(string processName)   
100{   
101System.Diagnostics.Process myproc= new System.Diagnostics.Process();   
102//得到所有打开的进程   
103try   
104{   
105foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))   
106{   
107if(!thisproc.CloseMainWindow())   
108{   
109thisproc.Kill();   
110}   
111}   
112}   
113catch(Exception Exc)   
114{   
115;   
116}   
117}   
118#endregion 
119
120#region Execel   
121/// <summary>   
122/// Class to export a number of web controls to Excel.   
123/// Pass BuildExcelTable your control, then call ExportToBrowser() to write down to the browser.   
124/// This will open a new instance of Excel.   
125/// If you want to open the Excel file in the current browser window, comment out the Response.AddHEader line.   
126/// </summary>   
127public class ExcelWriter   
128{   
129protected string m_szExcelHtnml;   
130private string szFileName;   
131private bool bStripBreaks; 
132
133public void BuildExcelTable(object DG)   
134{   
135//Header Styles   
136StringWriter sw = new StringWriter();   
137HtmlTextWriter ht = new HtmlTextWriter(sw);   
138  
139string sObjectTypeName = DG.GetType().Name.ToString();   
140switch (sObjectTypeName)   
141{   
142case "DataGrid":   
143((DataGrid)DG).ShowHeader = true;   
144((DataGrid)DG).RenderControl(ht);   
145break;   
146case "DataList":   
147((DataList)DG).RenderControl(ht);   
148break;   
149case "TextBox":   
150((TextBox)DG).RenderControl(ht);   
151break;   
152case "Label":   
153ht.Write(((Label)DG).Text);   
154break;   
155case "TableRow":   
156ht.Write("<table>");   
157((TableRow)DG).RenderControl(ht);   
158ht.Write("</table>");   
159break;   
160case "Table":   
161((Table)DG).RenderControl(ht);   
162break;   
163default:   
164break;   
165}   
166  
167m_szExcelHtnml += sw.ToString();   
168  
169} 
170
171public void ExportToBrowser()   
172{   
173if(szFileName == "" || szFileName == null)   
174{   
175szFileName = "ExcelFile.xls";   
176} 
177
178if(bStripBreaks)   
179{   
180m_szExcelHtnml = m_szExcelHtnml.Replace("<br/>", " ");   
181m_szExcelHtnml = m_szExcelHtnml.Replace("<br/>", " ");   
182}   
183HttpContext.Current.Response.Clear();   
184HttpContext.Current.Response.ClearHeaders();   
185HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + szFileName);   
186HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";   
187HttpContext.Current.Response.Write(m_szExcelHtnml);   
188HttpContext.Current.Response.Flush();   
189HttpContext.Current.Response.End();   
190} 
191
192public string FileName   
193{   
194get   
195{   
196return szFileName;   
197}   
198set   
199{   
200szFileName = value;   
201}   
202} 
203
204public bool StripBreakTags   
205{   
206get   
207{   
208return bStripBreaks;   
209}   
210set   
211{   
212bStripBreaks = value;   
213}   
214}   
215}   
216#endregion 
217
218#region PDF   
219public class PDFGenerator   
220{   
221static float pageWidth = 594.0f;   
222static float pageDepth = 828.0f;   
223static float pageMargin = 30.0f;   
224static float fontSize = 20.0f;   
225static float leadSize = 10.0f;   
226static StreamWriter pPDF=new StreamWriter("E:\\\myPDF.pdf");   
227static MemoryStream mPDF= new MemoryStream();   
228static void ConvertToByteAndAddtoStream(string strMsg)   
229{   
230Byte[] buffer=null;   
231buffer=ASCIIEncoding.ASCII.GetBytes(strMsg);   
232mPDF.Write(buffer,0,buffer.Length);   
233buffer=null;   
234}   
235  
236static string xRefFormatting(long xValue)   
237{   
238string strMsg =xValue.ToString();   
239int iLen=strMsg.Length;   
240if (iLen&lt;10)   
241{   
242StringBuilder s=new StringBuilder();   
243int i=10-iLen;   
244s.Append('0',i);   
245strMsg=s.ToString() + strMsg;   
246}   
247return strMsg;   
248}   
249  
250static void Main(string[] args)   
251{   
252ArrayList xRefs=new ArrayList();   
253//Byte[] buffer=null;   
254float yPos =0f;   
255long streamStart=0;   
256long streamEnd=0;   
257long streamLen =0;   
258string strPDFMessage=null;   
259//PDF文档头信息   
260strPDFMessage="%PDF-1.1\n";   
261ConvertToByteAndAddtoStream(strPDFMessage);   
262  
263xRefs.Add(mPDF.Length);   
264strPDFMessage="1 0 obj\n";   
265ConvertToByteAndAddtoStream(strPDFMessage);   
266strPDFMessage="&lt;&lt; /Length 2 0 R &gt;&gt;\n";   
267ConvertToByteAndAddtoStream(strPDFMessage);   
268strPDFMessage="stream\n";   
269ConvertToByteAndAddtoStream(strPDFMessage);   
270////////PDF文档描述   
271streamStart=mPDF.Length;   
272//字体   
273strPDFMessage="BT\n/F0 " + fontSize +" Tf\n";   
274ConvertToByteAndAddtoStream(strPDFMessage);   
275//PDF文档实体高度   
276yPos = pageDepth - pageMargin;   
277strPDFMessage=pageMargin + " " + yPos +" Td\n" ;   
278ConvertToByteAndAddtoStream(strPDFMessage);   
279strPDFMessage= leadSize+" TL\n" ;   
280ConvertToByteAndAddtoStream(strPDFMessage);   
281  
282//实体内容   
283strPDFMessage= "( http://www.wenhui.org)Tj\n " ;   
284ConvertToByteAndAddtoStream(strPDFMessage);   
285strPDFMessage= "ET\n";   
286ConvertToByteAndAddtoStream(strPDFMessage);   
287streamEnd=mPDF.Length;   
288  
289streamLen=streamEnd-streamStart;   
290strPDFMessage= "endstream\nendobj\n";   
291ConvertToByteAndAddtoStream(strPDFMessage);   
292//PDF文档的版本信息   
293xRefs.Add(mPDF.Length);   
294strPDFMessage="2 0 obj\n"+ streamLen + "\nendobj\n";   
295ConvertToByteAndAddtoStream(strPDFMessage);   
296  
297xRefs.Add(mPDF.Length);   
298strPDFMessage="3 0 obj\n&lt;&gt;\nendobj\n";   
299ConvertToByteAndAddtoStream(strPDFMessage);   
300  
301xRefs.Add(mPDF.Length);   
302strPDFMessage="4 0 obj\n&lt;&gt; &gt;&gt;\n";   
303ConvertToByteAndAddtoStream(strPDFMessage);   
304strPDFMessage="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ]\n&gt;&gt;\nendobj\n";   
305ConvertToByteAndAddtoStream(strPDFMessage);   
306  
307xRefs.Add(mPDF.Length);   
308strPDFMessage="5 0 obj\n&lt;&gt;\nendobj\n";   
309ConvertToByteAndAddtoStream(strPDFMessage);   
310  
311xRefs.Add(mPDF.Length);   
312strPDFMessage="6 0 obj\n&lt;&gt;\nendobj\n";   
313ConvertToByteAndAddtoStream(strPDFMessage);   
314  
315streamStart=mPDF.Length;   
316strPDFMessage="xref\n0 7\n0000000000 65535 f \n";   
317for(int i=0;i<xrefs.count;i++) (xrefs.count+1)+"\n="" +="" 0="" 00000="" 6="" \n";="" converttobyteandaddtostream(strpdfmessage);="" n="" r\n="" root="" strpdfmessage="trailer\n&lt;&lt;\n/Size " strpdfmessage+="xRefFormatting((long)" xrefs[i])+"="" {="" }="">&gt;\n";   
318ConvertToByteAndAddtoStream(strPDFMessage);   
319  
320strPDFMessage="startxref\n" + streamStart+"\n%%EOF\n";   
321ConvertToByteAndAddtoStream(strPDFMessage);   
322mPDF.WriteTo(pPDF.BaseStream);   
323  
324mPDF.Close();   
325pPDF.Close();   
326}   
327} 
328
329#endregion 
330
331#region Up Load Fille   
332public static string UpFile(System.Web.UI.HtmlControls.HtmlInputFile infile, string savefilepath, string savefilename, string choose)   
333{   
334string filename = infile.PostedFile.FileName;   
335if (infile.PostedFile!=null &amp;&amp; infile.Value != "" )   
336{   
337int i;   
338switch (choose)   
339{   
340case ".":   
341i = filename.LastIndexOf(".");   
342savefilename += filename.Substring(i);   
343break;   
344default:   
345i = filename.LastIndexOf("/");   
346if (i &lt;= 0) i = filename.LastIndexOf("\\\");   
347savefilename += choose + filename.Substring(i + 1);   
348break;   
349}   
350if (savefilepath.EndsWith("/") || savefilepath.EndsWith("\\\"))   
351filename = savefilepath + savefilename;   
352else   
353filename = savefilepath + "/" + savefilename;   
354savefilepath = System.Web.HttpContext.Current.Server.MapPath(filename);   
355infile.PostedFile.SaveAs(savefilepath);   
356return filename;   
357}   
358else   
359{   
360return null;   
361}   
362}   
363#endregion   
364}   
365}</xrefs.count;i++)></iresults;i++)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus