Tuesday 29 October 2013

Convert Type to SqlDataType and SqlDataType to Type C#

Leave a Comment
Type conversion basically involve casting and convert from one type to another. You can try the Type conversion by following this web site.

Today i want to share code to convert from Type to SqlDataType. This method can be used for example to add parameters to SqlCommand based on DataTable column DataType, see example below :

SqlCommand dbComm = new SqlCommand("<sql statement>",<sql connection>);

dbComm.Parameters.Add("<parameter name>", < sql Data Type>]).Value  = "test";




what about if you have DataTable and you want to automatically loop into column of datatable and and automatically assign Sql Data Type based on Column DataType of data table ..?There is nothing method or casting that available to do this, but after i googling about converting / casting DataType to SqlDataType, the result seem like impossible to done in .net .
Based on the above link. I have do my workaround  method to convert from Type to SqlDataType and SqlDataType to Type

Type to SqlDataType

        private static Dictionary<Type, SqlDbType> typeReference; 

        public static void loadDictionary()
        {
            typeReference = new Dictionary<Type, SqlDbType>();
            typeReference.Add(typeof(string), SqlDbType.NVarChar);
            typeReference.Add(typeof(Guid), SqlDbType.UniqueIdentifier);
            typeReference.Add(typeof(long), SqlDbType.BigInt);
            typeReference.Add(typeof(byte[]), SqlDbType.Binary);
            typeReference.Add(typeof(bool), SqlDbType.Bit);
            typeReference.Add(typeof(DateTime), SqlDbType.DateTime);
            typeReference.Add(typeof(decimal), SqlDbType.Decimal);
            typeReference.Add(typeof(double), SqlDbType.Float);
            typeReference.Add(typeof(int), SqlDbType.Int);
            typeReference.Add(typeof(float), SqlDbType.Real);
            typeReference.Add(typeof(short), SqlDbType.SmallInt);
            typeReference.Add(typeof(byte), SqlDbType.TinyInt);
            typeReference.Add(typeof(object), SqlDbType.Udt);
            typeReference.Add(typeof(DataTable), SqlDbType.Structured);
            typeReference.Add(typeof(DateTimeOffset), SqlDbType.DateTimeOffset);           
           
        }



Call method

SqlCommand dbCommand = new SqlCommand("Select * from <tableName> where id=@id",<sql connection>);

dbCommand.Parameters.Add("@id", typeReference[<DataType to pass>]).Value  = "12345";




SqlDataType to Type

 public static Type GetClrType(SqlDbType sqlDataType)
        {
            switch (sqlDataType)
            {
                case SqlDbType.BigInt:
                    return typeof(long?);

                case SqlDbType.Binary:
                case SqlDbType.Image:
                case SqlDbType.Timestamp:
                case SqlDbType.VarBinary:
                    return typeof(byte[]);

                case SqlDbType.Bit:
                    return typeof(bool?);

                case SqlDbType.Char:
                case SqlDbType.NChar:
                case SqlDbType.NText:
                case SqlDbType.NVarChar:
                case SqlDbType.Text:
                case SqlDbType.VarChar:
                case SqlDbType.Xml:
                    return typeof(string);

                case SqlDbType.DateTime:
                case SqlDbType.SmallDateTime:
                case SqlDbType.Date:
                case SqlDbType.Time:
                case SqlDbType.DateTime2:
                    return typeof(DateTime?);

                case SqlDbType.Decimal:
                case SqlDbType.Money:
                case SqlDbType.SmallMoney:
                    return typeof(decimal?);

                case SqlDbType.Float:
                    return typeof(double?);

                case SqlDbType.Int:
                    return typeof(int?);

                case SqlDbType.Real:
                    return typeof(float?);

                case SqlDbType.UniqueIdentifier:
                    return typeof(Guid?);

                case SqlDbType.SmallInt:
                    return typeof(short?);

                case SqlDbType.TinyInt:
                    return typeof(byte?);

                case SqlDbType.Variant:
                case SqlDbType.Udt:
                    return typeof(object);

                case SqlDbType.Structured:
                    return typeof(DataTable);

                case SqlDbType.DateTimeOffset:
                    return typeof(DateTimeOffset?);

                default:
                    throw new ArgumentOutOfRangeException("sqlDataType");
            }
        }






Have a try, happy coding ..


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday 28 October 2013

Modal Popup Message Box ASP.NEt C# Example

Leave a Comment

Message box is a must in a web application right now. I will show example how to create message box like picture above.

Requirement to try this example :
  • AjaxControl Toolkit
  • User Control  :  MessageBox.ascx
  • Sample Page To call Message Box : MessageModalPopup.aspx

The MessageBox.ascx 

<link href="../messageBoxStyle.css" type="text/css" rel="Stylesheet" />
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:ModalPopupExtender BackgroundCssClass="modalBackground" ID="ModalPopupExtender1"
    Drag="true" DropShadow="true" PopupControlID="Panel1" TargetControlID="Button2"
    runat="server">
</asp:ModalPopupExtender>
<asp:Button ID="Button2" runat="server" Text="Button" Style="display: none;" />
<asp:Panel ID="Panel1" runat="server" Style="display: none;">
    <div id="MessageBox">
        <div id="signup-ct">
            <div id="MessageBox-header">
                <h2>
                    <asp:Label ID="Label2" runat="server"></asp:Label>
                </h2>
            </div>
            <div class="txt-fld">
                <label>
                    <asp:Label ID="Label1" runat="server"></asp:Label></label>
            </div>
            <div class="btn-fld">
                <asp:Button ID="Button1" runat="server" Text="OK" CssClass="button" OnClick="Button1_Click" />
            </div>
        </div>
    </div>
</asp:Panel>



Note : The message box user controller will call css style for the box Ui



The Message Box Style

    #MessageBox
    {
        width: 404px;
        padding-bottom: 2px;        
        background: #FFF;
        border-radius: 5px;
        -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
        box-shadow: 0px 0px 4px rgba(0,0,0,0.7);
        -webkit-box-shadow: 0 0 4px rgba(0,0,0,0.7);
        -moz-box-shadow: 0 0px 4px rgba(0,0,0,0.7);
    }
    
    .modalBackground
        {
            border-color: Gray;
            filter: alpha(opacity=65);
            opacity: 0.65;
            -moz-opacity: 0.65;
        } 
    #MessageBox-header
    {
        background:#CCCCCC;
        padding: 18px 18px 14px 18px;
        border-bottom: 1px solid #CCC;
        border-top-left-radius: 5px;
        -moz-border-radius-topleft: 5px;
        -webkit-border-top-left-radius: 5px;
        border-top-right-radius: 5px;
        -moz-border-radius-topright: 5px;
        -webkit-border-top-right-radius: 5px;
    }
    
    #MessageBox-header h2
    {
        color: #444;
        font-size: 2em;
        font-weight: 700;
        margin-bottom: 3px;
        text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
    }
    #MessageBox-header p
    {
        color: #444;
        font-size: 1.3em;
        margin: 0;
        text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
        text-shadow: none;
    }
    
    #MessageBox .txt-fld
    {
        position: relative;
        width: 364px;
        padding: 14px 20px;
        border-bottom: 1px solid #EEE;
        text-align: right;
    }
    #MessageBox .btn-fld
    {
        width: 254px;
        overflow: hidden;
        padding: 12px 20px 12px 130px;
    }
    
    #MessageBox .txt-fld label
    {
        display: block;
        float: left;
        width: 90px;
        padding-top: 8px;
        color: #222;
        font-size: 1.3em;
        text-align: left;
    }
    #MessageBox .txt-fld input
    {
        width: 244px;
        padding: 8px;
        border-radius: 4px;
        -moz-border-radius: 4px;
        -webkit-border-radius: 4px;
        font-size: 1.2em;
        color: #222;
        background: #F7F7F7;
        font-family: "Helvetica Neue";
        outline: none;
        border-top: 1px solid #CCC;
        border-left: 1px solid #CCC;
        border-right: 1px solid #E7E6E6;
        border-bottom: 1px solid #E7E6E6;
    }
    #MessageBox .txt-fld input.good_input
    {
        background: #DEF5E1 url(../img/good.png) 236px center no-repeat;
    }
    #MessageBox .txt-fld input.error_input
    {
        background: #FDE0E0;
    }
    
    
    
    p.error
    {
        position: absolute;
        bottom: 48px;
        right: 20px;
        width: 262px;
        color: #FFF;
        font-size: 1.1em;
        padding-bottom: 5px;
        background: url(../img/error-arw.png) 20px bottom no-repeat;
        text-align: left;
        margin: 0;
        text-shadow: none;
    }
    p.error span
    {
        display: inline-block;
        background: #D43636;
        padding: 6px;
        border-radius: 3px;
        -moz-border-radius: 3px;
        -webkit-border-radius: 3px;
    }
    .txt-fld input:focus, .txt-fld textarea:focus
    {
        background-color: #FAF9DC;
    }
    
    .button
    {
        float: right;
        font-family: "Helvetica Neue" , "Helvetica" , "Arial" , sans-serif;
        background: #3F9D4A;
        border: none;
        width: auto;
        overflow: visible;
        font-size: 1.4em;
        color: #FFF;
        padding: 7px 10px;
        border-radius: 4px;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        font-weight: bold;
        text-shadow: 0 1px 0 rgba(0,0,0,0.4);
    }
    
    .modal_close
    {
        position: absolute;
        top: 12px;
        right: 12px;
        display: block;
        width: 14px;
        height: 14px;
        background: url(../img/modal_close.png);
        z-index: 2;
    }
    

Code Behind For Message Box User Controller

 protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void showPopupMesage(string title, string message)
        {
            ModalPopupExtender1.Show();
            Label2.Text = title;
            Label1.Text = message;
        }

        public void closePopup()
        {
            ModalPopupExtender1.Hide();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ModalPopupExtender1.Hide();
        }



The MessageModalPopup.aspx Page

<%@ Register Src="~/UserControl/MessageBox.ascx" TagName="MessageBox" TagPrefix="uc" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Show Message Box" OnClick="Button1_Click" />
    <uc:MessageBox ID="MessageBox1" runat="server"></uc:MessageBox>
</asp:Content>



The Code Behind for MessageModalPopup.aspx 

       protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MessageBox1.showPopupMesage("Message Box", "Hello world");
        } 





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Sunday 27 October 2013

Auto Complete Example ASP.NET AjaxToolkit C#

Leave a Comment
Auto complete is one powerful feature in modern web application. It is helping people to get the suggestion what are the word to put in the textbox.

Today i want to show example how to use AutoComplete feature in AjaxToolkit Asp.Net

The List of requirement :

The AutoCompleteTextBox.aspx Page :


 <%--Script Manager--%>
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <%--The Textbox--%>
    <asp:TextBox ID="TextBox1" runat="server" Width="259px"></asp:TextBox>
    <%--Auto Complete Textbox Extender Controller--%>
    <asp:AutoCompleteExtender ID="autoComplete1" runat="server" EnableCaching="true"
        BehaviorID="Auto" MinimumPrefixLength="2" TargetControlID="TextBox1"
        ServicePath="DataAutoComplete.asmx" ServiceMethod="GetCompletionList" CompletionInterval="500"
        CompletionSetCount="20" DelimiterCharacters=";, :" ShowOnlyCurrentWordInCompletionListItem="true">
        <Animations>
          <OnShow>
              <Sequence>  
              <OpacityAction Opacity="0" />
              <HideAction Visible="true" />
             <ScriptAction Script="var behavior = $find('Auto');
                                    if (!behavior._height) {
                                      var target = behavior.get_completionList();
                                      behavior._height = target.offsetHeight - 2;
                                      target.style.height = '0px';
                                    }" />
  
              <Parallel Duration=".4">
              <FadeIn />
              <Length PropertyKey="height" StartValue="0" 
                EndValueScript="$find('Auto')._height" />
              </Parallel>
              </Sequence>
        </OnShow>
        <OnHide>  
          <Parallel Duration=".4">
          <FadeOut />
          <Length PropertyKey="height" StartValueScript=
            "$find('Auto')._height" EndValue="0" />
          </Parallel>
        </OnHide>
      </Animations>
    </asp:AutoCompleteExtender>



The DataAutoComplete.asmx Web Services

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;

namespace BlogExample
{
    /// <summary>
    /// Summary description for DataAutoComplete1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class DataAutoComplete : System.Web.Services.WebService
    {
        [WebMethod]
        public string[] GetCompletionList(string prefixText, int count)
        {
            DataTable table = new DataTable();
            table.Columns.Add("CompanyName", typeof(string));
            table.Columns.Add("ID", typeof(string));           
            
            DataRow row = table.NewRow();
            row["CompanyName"] = "malaysia";
            row["ID"] = "1";
            table.Rows.Add(row);

            row = table.NewRow();
            row["CompanyName"] = "madinah";
            row["ID"] = "2";
            table.Rows.Add(row);

            row = table.NewRow();
            row["CompanyName"] = "mecca";
            row["ID"] = "3";
            table.Rows.Add(row);

            row = table.NewRow();
            row["CompanyName"] = "syiria";
            row["ID"] = "4";
            table.Rows.Add(row);

            row = table.NewRow();
            row["CompanyName"] = "mesir";
            row["ID"] = "5";
            table.Rows.Add(row);

            row = table.NewRow();
            row["CompanyName"] = "saudi arabia";
            row["ID"] = "6";
            table.Rows.Add(row);

            DataRow[] collectionRows = null;
            try{ collectionRows = table.Select("CompanyName like '%" + prefixText.Trim().ToLower() + "%'"); }
            catch (Exception ex){  /* exception handler */   }

            //Then return List of string(txtItems) as result
            List<string> txtItems = new List<string>();
            string dbValues = null;
            foreach (DataRow _row in collectionRows)
            {                
                dbValues = _row["CompanyName"].ToString();
                dbValues = dbValues.ToLower();
                txtItems.Add(dbValues);
            }

            return txtItems.ToArray();

        }
    }
}





The Output














NOTE : You can change the code to select data in database or cache table to optimize the performance. Have a try


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Thursday 24 October 2013

How to create zip file to download asp.net - C#

Leave a Comment
Today i want to show you how to create file on the fly from server side and pass it to client to download. The idea is to create the zip file when the button clicked, and then save the zip file and pass the zip file to client side. After file finish to download, you may be delete the zip file to reduce the resource of the server.

Some application will allow user to download multiple file, but to download file by clicking one by one button is not necessary as you can zip the file and download all the file as one single zip file.

In this tutorial i will use library DotNet Zip Library :

This is The Sample program , you can freely enhance or change the part of the program to meet your program requirement.

The ASPX Page

 <asp:Label ID="Label1" Text="DirectoryPath : " runat="server"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server" Height="25px" Width="362px"></asp:TextBox>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Download" 
        onclick="Button1_Click" />

Code Behind ASPX Page

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string path = TextBox1.Text;
            string[] FileList = Directory.GetFiles(path);
            string[] directoryList = Directory.GetDirectories(path);
            using (ZipFile zip = new ZipFile())
            {
                AddFileToZip(zip, FileList); //add root file to zip
                for (int level = 0; level < directoryList.Length; level++)
                {
                    AddFolderToZip(zip, directoryList[level]);
                }

                zip.Save(Server.MapPath("~") + "MyZipFile.zip");               

                HttpContext.Current.Response.ContentType = "application/zip";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"MyZipFile.zip\"");
                HttpContext.Current.Response.WriteFile(Server.MapPath("~") + "MyZipFile.zip");
            }
        }
        bool HasSubfoldersAlternate(string path)
        {
            IEnumerable<string> subfolders = Directory.EnumerateDirectories(path);
            return subfolders != null;
        }
        void AddFileToZip(ZipFile zip, string[] listFile)
        {
            for (int i = 0; i < listFile.Length; i++)
            {
                zip.AddFile(listFile[i]);
            }
        }
        void AddFolderToZip(ZipFile zip, string path)
        {
            string[] list = Directory.GetDirectories(path);
            if (list.Length > 0)
            {
                for (int i = 0; i < list.Length; i++)
                {
                    if (HasSubfoldersAlternate(list[i].ToString()))
                    {
                        AddFolderToZip(zip, list[i]);
                    }
                    else
                    {
                        AddFileToZip(zip, Directory.GetFiles(path));

                    }
                }
            }

            AddFileToZip(zip, Directory.GetFiles(path));//to add files from current folder

        }

Have a try. Feel free to check on How to create zip file to download in JSP- Servlet


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

How to create zip file to download in JSP- Servlet

Leave a Comment
Hye, my previous post show that how to download zip file in ASP.NET,. In this tutorial i will show the same thing, but in Jsp-Servlet.

Note : In this tutorial i will use this library :-

  • JSTL 1.1

 The JSP File

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Download File As ZIP File</title>
    </head>
    <body>
       <h1>Download File As ZIP File</h1>
        ${DownloadMessage}
        <br/>
        <form action="<c:url value="/downloadFileServletZip" />" method="post" >
            Default Path is server to download is D:\JAVA\dist\Output\
            <input type="submit" name="bDownload" value="Download Zip file"/>
        </form>
    </body>
</html>





The Servlet

 import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class downloadFileServletZip extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = "D:\\JAVA\\dist\\Output\\";
        File directory = new File(path);
        String[] files = directory.list();
       
        //check if directories have files
        if (files != null && files.length > 0) {
           
            //create zip stream
            byte[] zip = zipFiles(directory, files);
           
           
            // Sends the response back to the user / browser with zip content
            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
           
            sos.write(zip);
            sos.flush();
        }
       
        request.setAttribute("DownloadMessage", "Successfully");
        request.getRequestDispatcher("DownloadZipFile.jsp").forward(request, response);
       
    }
   
    private byte[] zipFiles(File directory, String[] files) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        byte bytes[] = new byte[4096];
       
        for (String fileName : files) {
            try (FileInputStream fis = new FileInputStream(directory.getPath()
                    + "/" + fileName);
                   
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
               
                zos.putNextEntry(new ZipEntry(fileName));
               
                int bytesRead;
                while ((bytesRead = bis.read(bytes)) != -1) {
                    zos.write(bytes, 0, bytesRead);
                }
                zos.closeEntry();
            }
        }
        zos.flush();
        baos.flush();
        zos.close();
        baos.close();
       
        return baos.toByteArray();
    }
   
   
}



The Web.xml

 <servlet-mapping>
        <servlet-name>downloadFileServletZip</servlet-name>
        <url-pattern>/downloadFileServletZip</url-pattern>
    </servlet-mapping>

 <servlet>
        <servlet-name>downloadFileServletZip</servlet-name>
        <servlet-class>sys.servlet.downloadFileServletZip</servlet-class>

</servlet>




Note : This code will throw exception Access denied if the folder  to create zip file contain subfolder.





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Tuesday 22 October 2013

Date Time Conversion utility Java

Leave a Comment
In this post, i will like to share code snippet for date time manipulation in Java.

Convert hour from integer to string

Description : Converts hour from integer to String. If the hour is single digit, the leading zero will be added.

public static String getHourString(int localHourNumber) {
        if ((localHourNumber > 23) || (localHourNumber < 0)) {
            return "";
        }

        if ((localHourNumber >= 0) && (localHourNumber <= 9)) {
            return "0" + localHourNumber;
        }

        return String.valueOf(localHourNumber);
    }

Convert minute from integer to string 

Description : Converts minute from integer to String. If the minute is single digit, the leading zero will be added.

public static String getMinuteString(int localMinuteNumber) {
        if ((localMinuteNumber > 59) || (localMinuteNumber < 0)) {
            return "";
        }

        if ((localMinuteNumber >= 0) && (localMinuteNumber <= 9)) {
            return "0" + localMinuteNumber;
        }

        return String.valueOf(localMinuteNumber);
    }

Converts the input parameter to the date format

public static String convertDateTimeFormat(String inputDate, String dateFormat) {
        String outPutDate = "";
        SimpleDateFormat patternDateTimeFormat = new SimpleDateFormat(dateFormat);
        try {
            if ((inputDate != null) && (inputDate.trim().length() > 0)) {
                // outPutDate = patternDateTimeFormat.format(new java.util.Date(inputDate));
                outPutDate = patternDateTimeFormat.format(DateFormat.getInstance().parse(inputDate));

            } else {
                outPutDate = patternDateTimeFormat.format(new java.util.Date());
            }
        } catch (Exception e) {
            outPutDate = patternDateTimeFormat.format(new java.util.Date());
        }
        return outPutDate;
    }



Gets the format java.sql.Date based on the frag ID value.

 public static java.sql.Date getSQLDateFromFragIDString(String fragID) {
        java.sql.Date date = null;
        Calendar cal = Calendar.getInstance();

        if (fragID.length() == 6) {
            cal.set(Integer.parseInt(fragID.substring(0, 4)), Integer.parseInt(fragID.substring(4, 6)) - 1, 01);
            date = new java.sql.Date(cal.getTime().getTime());
        }

        return date;
    }



Converts the input date to the date format specified Timestamp format.

/* * @param inputDate The string contains input date in the dd/MM/yyyy format.
     * @param inputTime The strin contains input time in the hh:mm:ss.fffffffff
     * format.
     * @return Timestamp Contains a Timestamp. 

*/

public static Timestamp convertToTimestamp(String inputDate, String inputTime) {
        StringTokenizer stringTokenizer = new StringTokenizer(inputDate, "/");
        String day = stringTokenizer.nextToken();
        String month = stringTokenizer.nextToken();
        String year = stringTokenizer.nextToken();
        Timestamp inputTransactionDateTime = Timestamp.valueOf(year + "-" + month + "-" + day + " " + inputTime);

        return inputTransactionDateTime;
    }



Gets the previous month value based on the entered fragmentation ID.

/**
     * Gets the previous month value based on the entered fragmentation ID.
     *
     * @param localfragId The int contains fragmentation ID to act as the base
     * for subtraction.
     * @return int Contains previous month value based on current fragmentation
     * id.
     */
    public static int getPreviousMonth(int localfragId) {

        if ((localfragId % 100) == 1) {
            localfragId = (((localfragId / 100) - 1) * 100) + 12;
        } else {
            localfragId--;
        }

        return localfragId;

    }



Gets the time different in hours:minutes:seconds:miliseconds

/**
     * Gets the time different in hours:minutes:seconds:miliseconds.
     *
     * @param startTime The object contains the fragmentation ID to act as the
     * base for subtraction.
     * @param endTime The object contains end time.
     * @return String Contains month value based on current fragmentation id.
     */
    public static String getTimeDifferent(Calendar startTime, Calendar endTime) {

        long timeStamp = endTime.getTime().getTime() - startTime.getTime().getTime();     
        return (timeStamp / hour) + ":" + (timeStamp / minute) + ":" + (timeStamp / second) + ":" + (timeStamp / milisecond);

    } 

Bonus : Method to Trims the session ID

/**
     * Trims the session ID to the full of the session ID string before the "!"
     * character.
     *
     * @param sessionID The string contains session id.
     * @return String Contains the trimmed sessionID.
     */

public static String trimSessionID(String sessionID) {
        return sessionID.substring(0, sessionID.indexOf("!"));
    }




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday 21 October 2013

How to read all folder and subfolder path C#

Leave a Comment
Today i want to show how you can get folder path and all subfolder path. The process is more efficient and faster because im using IEnumerable type to determine if path has sub directory or not.

I write this example in c# using window form. Here is my winform GUI :


The sample Output

----------------------------------
Directory List
Start Path : C:\Android Project
----------------------------------
List file and directory

Directory and Subdirectory Name
C:\Android Project\FirstProject
C:\Android Project\FirstProject\.metadata
C:\Android Project\FirstProject\.metadata\.plugins
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.cdt.core
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.cdt.make.core
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.resources
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.runtime
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.debug.core
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.debug.ui
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.jdt.core
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.jdt.ui
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.ui.intro
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.ui.workbench
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.resources\.history
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.resources\.root
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.resources\.safetable
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes
C:\Android Project\FirstProject\.metadata\.plugins\org.eclipse.core.runtime\.settings

when the button GetFolderName  clicked, the process will be like this :

The Source Code



 private void button1_Click(object sender, EventArgs e)
        {
            string fileNameOutput = "listofDirectory.txt";
            string folderName = Path.GetDirectoryName(textBox1.Text);
            string[] directoryList = Directory.GetDirectories(textBox1.Text);
            string[] filesName = Directory.GetFiles(textBox1.Text);
            if (File.Exists(fileNameOutput))
            {
                File.Delete(fileNameOutput);
            }

            StreamWriter sw = new StreamWriter(fileNameOutput);
            sw.WriteLine("----------------------------------");
            sw.WriteLine("Directory List");
            sw.WriteLine("Start Path : " + textBox1.Text);
            sw.WriteLine("----------------------------------");
            sw.WriteLine("List file and directory");
            if (filesName.Length > 0)
            {
                sw.WriteLine("Files Name");
            }

            writeToFile(sw, filesName);

            if (directoryList.Length > 0)
            {
                sw.WriteLine("\r\nDirectory and Subdirectory Name");
            }
           
            writeToFile(sw, directoryList);
            string[] list = directoryList;
            string[] _temp = null;
            int index = 0;
            for (int level = 0; level < directoryList.Length; level++)
            {
                if (HasSubfoldersAlternate(directoryList[level].ToString()))
                {
                    writeSubfolder(directoryList[level].ToString(), sw);
                }               
            }

            sw.Close();

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer anyway?", "Open Rendered File", MessageBoxButtons.YesNo);

            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(fileNameOutput);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);                    
                }
            }
        }
        public void writeSubfolder(string path,StreamWriter sw)
        {
            string[] list = Directory.GetDirectories(path);
            writeToFile(sw, list);
            for (int i = 0; i < list.Length; i++)
            {
                if(HasSubfoldersAlternate(list[i].ToString()))
                {
                    writeSubfolder(list[i].ToString(),sw);
                }
            }
        }
        public void writeToFile(StreamWriter sw, string[] listtoWrite)
        {
            for (int i = 0; i < listtoWrite.Length; i++)
            {
                sw.WriteLine(listtoWrite[i].ToString());
            }
        }
        bool HasSubfoldersAlternate(string path)
        {
            IEnumerable<string> subfolders = Directory.EnumerateDirectories(path);
            return subfolders != null;
        }






By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Sunday 20 October 2013

How to read XMl using LINQ - ASP.NET C#

Leave a Comment
LINQ -  stand for Language Integrated Query is a powerful features that extend the query capability to the language syntax in C# or Visual basic.

In this tutorial i will show one example how to read xml file using Linq.

Checklist :
  1. Create one aspx page name "ReadxmlUsingLinq.aspx".
  2. Create one xml file name "XmlDataTest.xml"

The XmlDataTest.xml 

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <TransactionName Description="Transaksi ASB">
    <MENU Name="Inquiry">
      <ITEMS TargetUrl="/Transaction/Default.aspx" DESCRIPTION="DefaultPage" ShortcutKey="Ctrl + H,1"></ITEMS>
      <ITEMS TargetUrl="/Transaction2/Default.aspx" DESCRIPTION="DefaultPage2" ShortcutKey="Ctrl + H,2"></ITEMS>
      <ITEMS TargetUrl="/Transaction3/Default.aspx" DESCRIPTION="DefaultPage3" ShortcutKey="Ctrl + H,3"></ITEMS>
      <ITEMS TargetUrl="/Transaction4/Default.aspx" DESCRIPTION="DefaultPage4" ShortcutKey="Ctrl + H,4"></ITEMS>
    </MENU>
  </TransactionName>
</root>



The ReadxmlUsingLinq.aspx Page

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="ReadxmlUsingLinq.aspx.cs" Inherits="BlogExample.ReadxmlUsingLinq" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Content>



The ReadxmlUsingLinq.aspx Code Behind

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace BlogExample
{
    public partial class ReadxmlUsingLinq : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string output = "";
                string path = Server.MapPath("~") + "/XML/XmlDataTest.xml";

                XDocument xDoc = XDocument.Load(path);
                var feed = from collection in xDoc.Descendants("MENU")
                           select new
                           {
                               UniqueID = collection.Elements("ITEMS")
                           };

                int feedItem = feed.ToList().Count;
                int countLength = 0;
                if (feedItem != 0)
                {
                    //this step to count how many length element to set in string array
                    foreach (var a in feed)
                    {
                        int countElement = a.UniqueID.Count();
                        countLength = countLength + countElement;
                    }
                }

                output += "The Unique ID count : " + countLength.ToString() + "<br/>";
                
                if (feedItem != 0)
                {
                    
                    int index = 1;
                    foreach (var a in feed)
                    {
                        int countElement = a.UniqueID.Count();
                        for (int k = 0; k < countElement; k++)
                        {
                            output += "Details number " + index.ToString() + "<br/>";
                            output += "The Target URL : " + a.UniqueID.ElementAt(k).Attribute("TargetUrl").ToString().Replace("TargetUrl=", "").Replace("\"","") + "<br/>";
                            output += "The DESCRIPTION : " + a.UniqueID.ElementAt(k).Attribute("DESCRIPTION").ToString().Replace("DESCRIPTION=", "").Replace("\"", "") + "<br/>";
                            output += "The ShortcutKey : " + a.UniqueID.ElementAt(k).Attribute("ShortcutKey").ToString().Replace("ShortcutKey=", "").Replace("\"", "") + "<br/>";
                            output += "<br/>";
                            index++;
                        }
                    }
                    Label1.Text = output;
                }
            }
        }
    }
}

The Output



References

  1. http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

How to create captcha image asp.net C#

Leave a Comment
The word CAPTCHA (stand for "Completely Automated Public Turing test to tell Computers and Humans Apart") is a one mechanism that used in web application to determined is user that access the web application is a human or bot. This is because, the captcha contains some word as Image that required users to enter same word in web application form to complete the process.  The captcha also used to prevent bots from automatically access the web page and do some SPAM thing in the web page.

Today i will show tutorial to create Captcha image in asp.net application :

Checklist :
  1. Create one dummy aspx page name "CaptchaImage.aspx".
  2. Create Captcha class name "CaptchaClass.cs".
  3. Create Page dummy to create captcha image name "Captcha.aspx".

The CaptchaImage.aspx page

 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CaptchaImage.aspx.cs" Inherits="Captcha.CaptchaImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>



The CaptchaImage.aspx Code Behind

 
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Drawing;

namespace Captcha
{
    public partial class CaptchaImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CaptchaClass C = new CaptchaClass();
            Bitmap bitmap = C.CreateImage();
        }
    }
}

The CaptchaClass.cs

 
using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace Captcha
{
    public class CaptchaClass
    {
        public Random rand = new Random();
        public Bitmap CreateImage()
        {
            string randomCode = GetRandomText();
            Bitmap bitmap = new Bitmap(200, 150, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            Graphics g = Graphics.FromImage(bitmap);
            Pen pen = new Pen(Color.Gold);
            Rectangle rect = new Rectangle(0, 0, 200, 150);

            SolidBrush b = new SolidBrush(Color.DarkKhaki);
            SolidBrush blue = new SolidBrush(Color.Gray);

            int counter = 0;
            g.DrawRectangle(pen, rect);
            g.FillRectangle(b, rect);

            for (int i = 0; i < randomCode.Length; i++)
            {
                g.DrawString(randomCode[i].ToString(), new Font("Verdana", 10 + rand.Next(14, 18)), blue, new PointF(10 + counter, 10));
                counter += 20;
            }
            DrawRandomLines(g);
            bitmap.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);

            g.Dispose();
            bitmap.Dispose();
            return bitmap;
        }
        public void DrawRandomLines(Graphics g)
        {
            SolidBrush greenLine = new SolidBrush(Color.Green);
            for (int i = 0; i < 20; i++)
            {
                g.DrawLines(new Pen(greenLine, 2), GetRandomPoints());
            }
        }
        public Point[] GetRandomPoints()
        {
            Point[] points = { new Point(rand.Next(10, 150), rand.Next(10, 150)), new Point(rand.Next(10, 100), rand.Next(10, 100)) };
            return points;
        }
        public string GetRandomText()
        {
            StringBuilder randomText = new StringBuilder();
            string alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            
            Random r = new Random();
            for (int j = 0; j <= 5; j++)
            {
                randomText.Append(alphabets[r.Next(alphabets.Length)]);
            }
            HttpContext.Current.Session["Code"] = randomText.ToString();
            return HttpContext.Current.Session["Code"] as String;
        }

    }
}



The Captcha.aspx Page

 
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="Captcha.aspx.cs" Inherits="Captcha.Captcha" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Draw Captcha" 
        onclick="Button1_Click" /><br />
    <asp:Image ID="Image1" runat="server" />
</asp:Content>



The Captcha.aspx Code Behind

 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Captcha
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Image1.ImageUrl = "CaptchaImage.aspx";
            //to check captcha code, you can try check in session 
            // HttpContext.Current.Session["Code"]<-- store value in captcha image
        }
    }
}



The Output



Have a try =)

References 

  1. http://en.wikipedia.org/wiki/CAPTCHA
  2. http://en.wikipedia.org/wiki/Spam_%28electronic%29


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Saturday 19 October 2013

Page Asynchronous and Synchronous Postback page example - ASP.NET

Leave a Comment
Asynchronous postback and synchronous postback is a process submission back to server. Only update panel are sent back to server if you using async postback(AJAX) while synchronous postback will sent all page content to server back.

Today i will create one example to differentioate between async postback and sync postback.

The ASPX page

Register the ajaxtoolkit script manager :
     

 <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
 </asp:ToolkitScriptManager>

Update Panel Content :

 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Text="Do AsyncPostback Update" OnClick="Button1_Click" />
            <asp:Button ID="Button2" runat="server" Text="Do Postback Update" OnClick="Button2_Click" />
            <br />
            <asp:Label ID="Label1" runat="server"></asp:Label>
            <br />
            <div id="pageUpdating">
            </div>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="click" />
            <asp:PostBackTrigger ControlID="Button2" />
        </Triggers>
    </asp:UpdatePanel>

Optional : If you want to show that the page pregress, you can register this script on your page 


 
<script type="text/javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
        function BeginRequestHandler(sender, args) {
            writePageLoading();
        }
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
        function endRequestHandler(sender, args) {
            RemoveLoading();
            if (args.get_error() != undefined && args.get_error().httpStatusCode == '500') {
                var errorMessage = args.get_error().message
                alert(errorMessage + " . " + errorMessageAdditional);
            }
        }
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler)
        function pageLoadingHandler(sender, args) {
            writePageUpdating();
            
        }
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler)
        function pageLoadedHandler(sender, args) {
            RemoveLoading();
        }
        function writePageLoading() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "Please Wait While Processing Your Request...";
        }
        function RemoveLoading() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "";
        }
        function writePageUpdating() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "Please Wait While System Updating Your Page...";
        }
    </script>

Code Behind :

 
        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(10000);//Just to stop the process for a while
            Label1.Text = "Async Postback Update: " + DateTime.Now.ToShortTimeString();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
             Thread.Sleep(10000);//Just to stop the process for a while
             Label1.Text = "Postback Update: " + DateTime.Now.ToShortTimeString();
        } 

The Output

Async Postback

1. The Starting page


2. After click button 'Do Asyncpostback Update' :


3. Page finish update


Synchronous Postback

1. The Starting page

 
2. Page finish update



 Note : You can read more about different this different postback here

Reference

  1. http://msdn.microsoft.com/en-us/library/bb398976%28v=vs.100%29.aspx




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.