熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

ASP.NET(C#)

2013-11-13 10:14:38  來源: .NET編程 
    一個生成不重復隨機數的方法
    //生成不重復隨機數算法
    private int GetRandomNum(int iint lengthint upint down)
    {
    int iFirst=;
    Random ro=new Random(i*length*unchecked((int)DateTimeNowTicks))
    iFirst=roNext(updown)
    return iFirst;
    }
    發表於 @ : PM | 評論 (
    ASPNET多文件上傳方法
    前台代碼
    <script language=Javascript>
    function addFile()
    {
    var str = <INPUT type=file size= NAME=File><br>
    documentgetElementById(MyFileinsertAdjacentHTML(beforeEndstr)
    }
    </script>
    <form id=form method=post runat=server enctype=multipart/formdata>
    <div align=center>
    <h>多文件上傳</h>
    <P id=MyFile><INPUT type=file size= NAME=File><br></P>
    <P>
    <input type=button value=增加(Add) onclick=addFile()> <input onclick=thisformreset() type=button value=重置(ReSet)>
    <asp:Button Runat=server Text=開始上傳 ID=UploadButton>
    </asp:Button>
    </P>
    <P>
    <asp:Label id=strStatus runat=server FontNames=宋體 FontBold=True FontSize=pt Width=px
    BorderStyle=None BorderColor=White></asp:Label>
    </P>
    </div>
    </form>
    後台代碼
    protected SystemWebUIWebControlsButton UploadButton;
    protected SystemWebUIWebControlsLabel strStatus;
    private void Page_Load(object sender SystemEventArgs e)
    {
    /// 在此處放置用戶代碼以初始化頁面
    if (thisIsPostBack) thisSaveImages()
    }
    private Boolean SaveImages()
    {
    ///遍歷File表單元素
    HttpFileCollection files = HttpContextCurrentRequestFiles;
    /// 狀態信息
    SystemTextStringBuilder strMsg = new SystemTextStringBuilder()
    strMsgAppend(上傳的文件分別是<hr color=red>
    try
    {
    for(int iFile = ; iFile < filesCount; iFile++)
    {
    ///檢查文件擴展名字
    HttpPostedFile postedFile = files[iFile];
    string fileNamefileExtensionfile_id;
    //取出精確到毫秒的時間做文件的名稱
    int year = SystemDateTimeNowYear;
    int month = SystemDateTimeNowMonth;
    int day = SystemDateTimeNowDay;
    int hour = SystemDateTimeNowHour;
    int minute = SystemDateTimeNowMinute;
    int second = SystemDateTimeNowSecond;
    int millisecond = SystemDateTimeNowMillisecond;
    string my_file_id = yearToString() + monthToString() + dayToString() + hourToString() + minuteToString() + secondToString() + millisecondToString()+iFileToString()
    fileName = SystemIOPathGetFileName(postedFileFileName)
    fileExtension = SystemIOPathGetExtension(fileName)
    file_id = my_file_id+fileExtension;
    if (fileName !=
    {
    fileExtension = SystemIOPathGetExtension(fileName)
    strMsgAppend(上傳的文件類型 + postedFileContentTypeToString() + <br>
    strMsgAppend(客戶端文件地址 + postedFileFileName + <br>
    strMsgAppend(上傳文件的文件名 + file_id + <br>
    strMsgAppend(上傳文件的擴展名 + fileExtension + <br><hr>
    postedFileSaveAs(SystemWebHttpContextCurrentRequestMapPath(images/) + file_id)
    }
    }
    strStatusText = strMsgToString()
    return true;
    }
    catch(SystemException Ex)
    {
    strStatusText = ExMessage;
    return false;
    }
    }
    發表於 @ : PM | 評論 (
    郵件系統使用的上傳附件方法
    前台HTML代碼
    <form id=mail method=post runat=server>
    <table border= cellpadding= cellspacing= bordercolor=#
    width=% id=AutoNumber height=>
    <tr>
    <td width=% height=><INPUT id=myFile type=file size= name=myFile
    runat=server>
    <asp:button id=Upload runat=server Text=上傳附件></asp:button></td>
    </tr>
    <tr>
    <td width=% height=>
    共計
    <asp:textbox id=P_size runat=server Width=px></asp:textbox>KB
    <asp:dropdownlist id=dlistBound runat=server></asp:dropdownlist>
    <asp:button id=btnDel runat=server Text=刪除附件></asp:button></td>
    </tr>
    </table>
    </form>
    後台CS代碼
    public class Upload_Mail : SystemWebUIPage
    {
    protected SystemWebUIWebControlsButton Upload;
    protected SystemWebUIWebControlsDropDownList dlistBound;
    protected SystemWebUIWebControlsTextBox P_size;
    protected SystemWebUIWebControlsButton btnDel;
    protected SystemWebUIHtmlControlsHtmlInputFile myFile;
    private void Page_Load(object sender SystemEventArgs e)
    {
    if (!IsPostBack)
    {
    //沒有附件的狀態
    dlistBoundItemsClear()
    ArrayList arr = new ArrayList()
    arrAdd(沒有附件
    dlistBoundDataSource = arr ;
    dlistBoundDataBind()
    P_sizeText = ;
    }
    }
    private void Upload_Click(object sender SystemEventArgs e)
    {
    if(myFilePostedFile !=null)
    {
    HttpFileCollection files = HttpContextCurrentRequestFiles;
    HttpPostedFile postedFile = files[];
    string fileName = SystemIOPathGetFileName(postedFileFileName)
    string path = RequestPhysicalApplicationPath+@UploadMail\+ fileName;
    postedFileSaveAs(path)
    //數組對上存附件進行實時綁定
    if((string)Session[udMail]==null)
    {
    Session[udMail] = fileName;
    }
    else
    {
    Session[udMail] = (string)Session[udMail]+|+fileName;
    }
    string[] udMail = Session[udMail]ToString()Split(|
    ArrayList list = new ArrayList(udMail)
    listReverse()
    udMail=(string[])listToArray(typeof(string))
    dlistBoundItemsClear()
    long dirsize=;
    for(int i = ;i<udMailLength;i++)
    {
    string IndexItem = udMail[i];
    string VauleItem = RequestPhysicalApplicationPath+@UploadMail\+udMail[i];
    dlistBoundItemsAdd(new ListItem(IndexItemVauleItem))
    SystemIOFileInfo mysize = new SystemIOFileInfo(@VauleItem)
    dirsize += SystemConvertToInt(mysizeLength/)+;
    }
    P_sizeText = dirsizeToString()
    }
    }
    private void btnDel_Click(object sender SystemEventArgs e)
    {
    string trueDelfile = dlistBoundSelectedValueToString()
    string Delfile = dlistBoundSelectedItemToString()
    usageIODeletePath(trueDelfile)
    if(Session[udMail] != null)
    {
    int index = Session[udMail]ToString()IndexOf(|
    if(index ==
    {
    Session[udMail] = null;
    dlistBoundItemsClear()
    dlistBoundItemsAdd(沒有附件
    P_sizeText = ;
    }
    else
    {
    string[] udMail = Session[udMail]ToString()Split(|
    ArrayList values = new ArrayList(udMail)
    valuesRemove(Delfile)
    string s = null;
    for(int i=;i<valuesCount;i++)
    {
    if(valuesCount!=
    {
    s += values[i]ToString()+|;
    }
    }
    if(s!=||s!=null)
    {
    s = sTrimEnd(|
    }
    Session[udMail] = s;
    string[] uMail = Session[udMail]ToString()Split(|
    ArrayList list = new ArrayList(uMail)
    listReverse()
    uMail=(string[])listToArray(typeof(string))
    dlistBoundItemsClear()
    long dirsize=;
    for(int i = ;i<uMailLength;i++)
    {
    string IndexItem = uMail[i];
    string VauleItem = RequestPhysicalApplicationPath+@UploadMail\+uMail[i];
    dlistBoundItemsAdd(new ListItem(IndexItemVauleItem))
    SystemIOFileInfo mysize = new SystemIOFileInfo(@VauleItem)
    dirsize += SystemConvertToInt(mysizeLength/)+;
    }
    P_sizeText = dirsizeToString()
    }
    }
    }
    Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 該調用是 ASPNET Web 窗體設計器所必需的
    //
    InitializeComponent()
    baseOnInit(e)
    }
    /**//// <summary>
    /// 設計器支持所需的方法 不要使用代碼編輯器修改
    /// 此方法的內容
    /// </summary>
    private void InitializeComponent()
    {
    thisUploadClick += new SystemEventHandler(thisUpload_Click)
    thisbtnDelClick += new SystemEventHandler(thisbtnDel_Click)
    thisLoad += new SystemEventHandler(thisPage_Load)
    }
    #endregion
    }
    發表於 @ : PM | 評論 (
    上傳圖片並且生成可以控制大小圖片清晰度的方法
    private void Upload_Click(object sender SystemEventArgs e)
    {
    if(myFilePostedFile !=null)
    {
    // 檢查文件擴展名字
    HttpFileCollection files = HttpContextCurrentRequestFiles;
    HttpPostedFile postedFile = files[];
    string fileNamefileExtensionfile_idfile_path;
    //取出精確到毫秒的時間做文件的名稱
    int year = SystemDateTimeNowYear;
    int month = SystemDateTimeNowMonth;
    int day = SystemDateTimeNowDay;
    int hour = SystemDateTimeNowHour;
    int minute = SystemDateTimeNowMinute;
    int second = SystemDateTimeNowSecond;
    int millisecond = SystemDateTimeNowMillisecond;
    string my_file_id = yearToString() + monthToString() + dayToString() + hourToString() + minuteToString() + secondToString() + millisecondToString()
    //獲得文件類型
    fileName = SystemIOPathGetFileName(postedFileFileName)
    fileExtension = SystemIOPathGetExtension(fileName)
    //重新命名文件防止重復
    file_id = topnews_+my_file_id+fileExtension;
    file_path = images/article_images/+file_id;
    //文件上傳到服務器的根目錄
    postedFileSaveAs(RequestPhysicalApplicationPath+@images\article_images\+ file_id)
    //處理圖片大小
    int widthheightlevel;
    width=;
    height=;
    level=;//從
    GetThumbnailImage(widthheightlevelfile_id)
    }
    }
    //生成縮略圖函數
    public void GetThumbnailImage(int widthint heightint levelstring file_id)
    {
    string newfile= RequestPhysicalApplicationPath+images/article_images/+top_+ file_id;
    SystemDrawingImage oldimage = SystemDrawingImageFromFile(RequestPhysicalApplicationPath+images/article_images/+ file_id)
    SystemDrawingImage thumbnailImage = oldimageGetThumbnailImage(width heightnew SystemDrawingImageGetThumbnailImageAbort(ThumbnailCallback) IntPtrZero)
    Bitmap output=new Bitmap(thumbnailImage)
    //處理JPG質量的函數
    ImageCodecInfo[] codecs=ImageCodecInfoGetImageEncoders()
    ImageCodecInfo ici=null;
    foreach(ImageCodecInfo codec in codecs){if(codecMimeType==image/jpeg)ici=codec;}
    EncoderParameters ep=new EncoderParameters()
    epParam[]=new EncoderParameter(EncoderQuality(long)level)
    outputSave(newfileiciep)
    //釋放所有使用對象
    epDispose()
    outputDispose()
    oldimageDispose()
    thumbnailImageDispose()
    //刪除源圖片
    string file_path = images/article_images/+top_+file_id;
    usageIODeletePath(RequestPhysicalApplicationPath+images/article_images/+ file_id)
    ResponseWrite(<script >parentFormA_Simgvalue =+file_path+;locationreplace(Upload_Imgaspx)</script>
    }
    bool ThumbnailCallback()
    {
    return false;
    }
    發表於 @ : PM | 評論 (
    生成高清晰度的縮略圖[方法]
    public void pic_zero(string sourcepathstring aimpathint scale)
    {
    string originalFilename =sourcepath;
    //生成的高質量圖片名稱
    string strGoodFile =aimpath;
    //從文件取得圖片對象
    SystemDrawingImage image = SystemDrawingImageFromFile(originalFilename)
    int iImgWidth = imageWidth;
    int iImgHeight = imageHeight;
    int iScale = (iImgWidth / scale)>(iImgHeight/scale) ? (iImgWidth / scale) : (iImgHeight / scale)
    //取得圖片大小
    SystemDrawingSize size = new Size(imageWidth / iScale imageHeight / iScale)
    //新建一個bmp圖片
    SystemDrawingImage bitmap = new SystemDrawingBitmap(sizeWidthsizeHeight)
    //新建一個畫板
    SystemDrawingGraphics g = SystemDrawingGraphicsFromImage(bitmap)
    //設置高質量插值法
    gInterpolationMode = SystemDrawingDrawingDInterpolationModeHigh;
    //設置高質量低速度呈現平滑程度
    gSmoothingMode = SystemDrawingDrawingDSmoothingModeHighQuality;
    //清空一下畫布
    gClear(ColorBlue)
    //在指定位置畫圖
    gDrawImage(image new SystemDrawingRectangle( bitmapWidth bitmapHeight)
    new SystemDrawingRectangle( imageWidthimageHeight)
    SystemDrawingGraphicsUnitPixel)
    //保存高清晰度的縮略圖
    bitmapSave(strGoodFile SystemDrawingImagingImageFormatJpeg)
    gDispose()
    }
    發表於 @ : PM | 評論 (
    比較完美的圖片驗證碼
    需要引用的名字空間
    using SystemIO;
    using SystemDrawingImaging;
    using SystemDrawingDrawingD;
    public class ValidationCodeImg : SystemWebUIPage
    {
    private void Page_Load(object sender SystemEventArgs e)
    {
    thisCreateCheckCodeImage(GenerateCheckCode())
    }
    private string GenerateCheckCode()
    {
    int number;
    char code;
    string checkCode = StringEmpty;
    SystemRandom random = new Random()
    for(int i=; i<; i++)
    {
    number = randomNext()
    if(number % ==
    code = (char)( + (char)(number % ))
    else
    code = (char)( + (char)(number % ))
    checkCode += codeToString()
    }
    ResponseCookiesAdd(new HttpCookie(CheckCode checkCode))
    return checkCode;
    }
    private void CreateCheckCodeImage(string checkCode)
    {
    if(checkCode == null || checkCodeTrim() == StringEmpty)
    return;
    SystemDrawingBitmap image = new SystemDrawingBitmap((int)MathCeiling((checkCodeLength * ))
    Graphics g = GraphicsFromImage(image)
    try
    {
    //生成隨機生成器
    Random random = new Random()
    //清空圖片背景色
    gClear(ColorWhite)
    //畫圖片的背景噪音線
    for(int i=; i<; i++)
    {
    int x = randomNext(imageWidth)
    int x = randomNext(imageWidth)
    int y = randomNext(imageHeight)
    int y = randomNext(imageHeight)
    gDrawLine(new Pen(ColorSilver) x y x y
    }
    Font font = new SystemDrawingFont(Tahoma (SystemDrawingFontStyleBold | SystemDrawingFontStyleItalic))
    SystemDrawingDrawingDLinearGradientBrush brush = new SystemDrawingDrawingDLinearGradientBrush(new Rectangle( imageWidth imageHeight) ColorBlack ColorBlack f true)
    gDrawString(checkCode font brush
    //畫圖片的前景噪音點
    for(int i=; i<; i++)
    {
    int x = randomNext(imageWidth)
    int y = randomNext(imageHeight)
    imageSetPixel(x y ColorFromArgb(randomNext()))
    }
    //畫圖片的邊框線
    gDrawRectangle(new Pen(ColorSilver) imageWidth imageHeight
    SystemIOMemoryStream ms = new SystemIOMemoryStream()
    imageSave(ms SystemDrawingImagingImageFormatGif)
    ResponseClearContent()
    ResponseContentType = image/Gif;
    ResponseBinaryWrite(msToArray())
    }
    finally
    {
    gDispose()
    imageDispose()
    }
    }
    發表於 @ : PM | 評論 (
    IE訂單的打印處理辦法
    在一個商城項目應用中我需要把客戶在網上下的訂單使用IE打印出來
    首先必須控制訂單不能出現IE的頁眉頁腳(需要使用ScriptX)
    <OBJECT id=factory codeBase=
    classid=clsid:edebdbffdd viewastext>
    </OBJECT>
    <SCRIPT defer>
    function println() {
    factoryprintingheader =
    factoryprintingfooter =
    factoryprintingPrint(true)
    factoryprintingleftMargin =
    factoryprintingtopMargin =
    factoryprintingrightMargin =
    factoryprintingbottomMargin =
    windowprint()
    }
    </SCRIPT>
    然後主要是控制訂單數據輸出用什麼辦法顯示出來為了靈活的控制輸出效果我這裡使用的是循環讀入數據(定購的商品)的辦法(下面的代碼是我使用的)
    public string myOrder(string B_No)
    {
    nnOpen()
    string strFirstMenu =null;
    string strSql = select Items_TypeItems_NameItems_UnitItems_CountItems_Price from [OrderItems] where Order_No = +B_No+ order by ID desc;
    SqlDataAdapter da = new SqlDataAdapter(strSqlnn)
    DataSet ds = new DataSet()
    daFill(dsmyOrder
    int count = dsTables[]RowsCount;
    string Items_TypeItems_NameItems_PriceItems_CountItems_UnitItems_TotalPrice;
    Double Items_AllTotalPrice = ;
    int Items_TotalCount = ;
    string begin = <table id =\inc\style=\BORDERCOLLAPSE: collapse\ borderColor=\#\ height=\\ cellSpacing=\\ cellPadding=\\ width=\%\ border=\\><tr><td align=\center\ width=\%\ height=\\>商品編號</td><td align=\center\ width=\%\ height=\\>商品名稱</td><td align=\center\ width=\%\ height=\\>單位</td><td align=\center\ width=\%\ height=\\>數量</td><td align=\center\ width=\%\ height=\\>單價(元)</td><td align=\center\ width=\%\ height=\\>金額(元)</td></tr>;
    for(int rb = ; rb < count;rb++)
    {
    Items_Type = dsTables[]Rows[rb][]ToString()
    Items_Name = dsTables[]Rows[rb][]ToString()
    Items_Unit = dsTables[]Rows[rb][]ToString()
    Items_Count = dsTables[]Rows[rb][]ToString()
    Items_Price = DoubleParse(dsTables[]Rows[rb][]ToString())ToString(
    Items_TotalPrice = (DoubleParse(Items_Price)*DoubleParse(Items_Count))ToString(
    Items_AllTotalPrice += DoubleParse(Items_TotalPrice)
    Items_TotalCount += IntParse(Items_Count)
    strFirstMenu += <tr><td width=\%\ height=\\> +Items_Type+</td><td width=\%\ height=\\>+Items_Name+</td><td width=\%\ height=\\>+Items_Unit+</td><td width=\%\ height=\\>+Items_Count+</td><td width=\%\ height=\\>+Items_Price+</td><td width=\%\ height=\\>+Items_TotalPrice+</td></tr>;
    }
    string FirstMenu = begin+strFirstMenu+</table>;
    nnClose()
    return FirstMenu;
    }


    發表於 @ : PM | 評論 (
    URL傳輸參數加密解密
    最近做一個論壇入口時要實現帳號和密碼不在IE地址欄出現而做的
    indexaspxcs (加密處理)
    Byte[] Iv={ };
    Byte[] byKey={ };
    public string Encrypt(string strText)
    {
    try
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider()
    Byte[] inputByteArray = EncodingUTFGetBytes(strText)
    MemoryStream ms = new MemoryStream()
    CryptoStream cs = new CryptoStream(ms desCreateEncryptor(byKey Iv CryptoStreamModeWrite)
    csWrite(inputByteArray inputByteArrayLength)
    csFlushFinalBlock()
    return ConvertToBaseString(msToArray())
    }
    catch(Exception ex)
    {
    return exMessage;
    }
    }
    private void btnLogin_Click(object sender SystemWebUIImageClickEventArgs e)
    {
    DateTime nowTime = DateTimeNow;
    string postUser = txtUserTextToString()
    string postPass = txtPasswordTextToString()
    ResponseRedirect(Loginaspx?clubID=+Encrypt(postUser++postPass++nowTimeToString()))
    }
    loginaspxcs (解密處理)
    //隨機選個字節既為密鑰也為初始向量
    Byte[] byKey={ };
    Byte[] Iv={ };
    public string Decrypt(string strText)
    {
    Byte[] inputByteArray = new byte[strTextLength];
    try
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider()
    inputByteArray = ConvertFromBaseString(strText)
    MemoryStream ms = new MemoryStream()
    CryptoStream cs = new CryptoStream(ms desCreateDecryptor(byKey Iv CryptoStreamModeWrite)
    csWrite(inputByteArray inputByteArrayLength)
    csFlushFinalBlock()
    SystemTextEncoding encoding = SystemTextEncodingUTF;
    return encodingGetString(msToArray())
    }
    catch(Exception ex)
    {
    return exMessage;
    }
    }
    private void Page_Load(object sender SystemEventArgs e)
    {
    if(RequestParams[clubID]!=null)
    {
    string originalValue = RequestParams[clubID];
    originalValue = originalValueReplace( +
    //+號通過url傳遞變成了空格
    string decryptResult = Decrypt(originalValue)
    //DecryptString(string)解密字符串
    string delimStr = ;
    char[] delimiterArray = delimStrToCharArray()
    string [] userInfoArray = null;
    userInfoArray = decryptResultSplit(delimiterArray)
    string userName = userInfoArray[];
    User userToLogin = new User()
    userToLoginUsername = userInfoArray[];
    userToLoginPassword = userInfoArray[];
    ……
    }
    }


From:http://tw.wingwit.com/Article/program/net/201311/13020.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.