Friday 29 November 2013

Detect Browser In Code Behind ASP.NET

Leave a Comment
Certain javascript will work on certain browser only. So inorder to avoid your client from using the application which is bot supported by your application, you can filter the browser type from code behind of your web application.
 
Let see the example

The ASPX page

<!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 Code Behind

 protected void Page_Load(object sender, EventArgs e)
        {
            System.Web.HttpBrowserCapabilities browser = Request.Browser;
            string s = "Browser Capabilities &lt;br/&gt;"
                + "Type = " + browser.Type + "&lt;br/&gt;"
                + "Name = " + browser.Browser + "&lt;br/&gt;"
                + "Version = " + browser.Version + "&lt;br/&gt;"
                + "Major Version = " + browser.MajorVersion + "&lt;br/&gt;"
                + "Minor Version = " + browser.MinorVersion + "&lt;br/&gt;"
                + "Platform = " + browser.Platform + "&lt;br/&gt;"
                + "Is Beta = " + browser.Beta + "&lt;br/&gt;"
                + "Is Crawler = " + browser.Crawler + "&lt;br/&gt;"
                + "Is AOL = " + browser.AOL + "&lt;br/&gt;"
                + "Is Win16 = " + browser.Win16 + "&lt;br/&gt;"
                + "Is Win32 = " + browser.Win32 + "&lt;br/&gt;"
                + "Supports Frames = " + browser.Frames + "&lt;br/&gt;"
                + "Supports Tables = " + browser.Tables + "&lt;br/&gt;"
                + "Supports Cookies = " + browser.Cookies + "&lt;br/&gt;"
                + "Supports VBScript = " + browser.VBScript + "&lt;br/&gt;"
                + "Supports JavaScript = " +
                    browser.EcmaScriptVersion.ToString() + "&lt;br/&gt;"
                + "Supports Java Applets = " + browser.JavaApplets + "&lt;br/&gt;"
                + "Supports ActiveX Controls = " + browser.ActiveXControls
                      + "&lt;br/&gt;"
                + "Supports JavaScript Version = " +
                    browser["JavaScriptVersion"]  + "&lt;br/&gt;&lt;br/&gt;";

            

            Response.Write(s);

            switch (browser.Browser.ToUpper().Trim())
            {
                // WHY No OPERA BROWSER,because opera and chrome user agent is same, 
                // the browser.Browser will return Chrome value in Opera
                case "CHROME": Response.Write("<b>application support your browser</b>"); break;
                case "INTERNETEXPLORER": Response.Write("<b>application does not support your browser</b>"); break;
                case "FIREFOX": Response.Write("<b>application support your browser</b>"); break;
                case "SAFARI": Response.Write("<b>application support your browser</b>"); break;
                default: break;
            }
        } 

The Output


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 alter DataTable to add new Column -C#, asp.net

Leave a Comment
In this tutorial i will show how to manipulate the DataTable to append with new column.
In this example i will retrieve data from database using SqlDataAdapter, you can refer this tutorial to know how to using SqlDataAdapter.
After fill DataTable with data, the program will append the column of the DataTable.

Lets check on the example below.

The Database Table "Users"

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Users](
    [Userid] [varchar](50) NOT NULL,
    [UserEmail] [varchar](50) NOT NULL,
    [DateTimeCreated] [datetime] NOT NULL,
    [CreatedBy] [varchar](50) NOT NULL,
    [DateTimeModified] [datetime] NULL,
    [ModifiedBy] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Users] ([Userid], [UserEmail], [DateTimeCreated], [CreatedBy], [DateTimeModified], [ModifiedBy]) VALUES (N'developers', N'developersnote@gmail.com', CAST(0x0000A284014950B0 AS DateTime), N'SYS', NULL, NULL)
INSERT [dbo].[Users] ([Userid], [UserEmail], [DateTimeCreated], [CreatedBy], [DateTimeModified], [ModifiedBy]) VALUES (N'noted', N'developersnote@gmail.com', CAST(0x0000A284014950B0 AS DateTime), N'SYS', NULL, NULL)


The ASPX Page

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

<!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>
        <h1>
            Data From Database without modified
        </h1>
        <asp:GridView ID="GridView1" runat="server" BackColor="White" 
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
            ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>
    </div>
    <div>
        <h1>
            Data From Database append with new column id
        </h1>
        <asp:GridView ID="GridView2" runat="server" BackColor="White" 
            BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
            GridLines="Vertical">
            <AlternatingRowStyle BackColor="#DCDCDC" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#0000A9" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#000065" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>


The Code Behind

protected void Page_Load(object sender, EventArgs e)
        {
            BindGridView1();
            BindGridView2();
        }

        private void BindGridView1()
        {
            DataTable tableUsers = getDataTableUsers();
            GridView1.DataSource = tableUsers;
            GridView1.DataBind();
        }

        private void BindGridView2()
        {
            DataTable tableUsers = getDataTableUsers();
            //create new datatable
            DataTable newTableUsers = new DataTable();
            //create column id
            newTableUsers.Columns.Add("ID",typeof(string));

            //copy table get from database to new table with append id column
            newTableUsers = copyTable(tableUsers,newTableUsers);

            GridView2.DataSource = newTableUsers;
            GridView2.DataBind();

        }

        public DataTable copyTable(DataTable TableToCopy, DataTable tableAfterCopy)
        {
            //copy table column first
            foreach(DataColumn col in TableToCopy.Columns)
            {
                tableAfterCopy.Columns.Add(col.ColumnName,col.DataType);
            }

            //copy table data
            int index =1;
            for(int i = 0; i < TableToCopy.Rows.Count;i++)
            {
                DataRow row = tableAfterCopy.NewRow();
                foreach(DataColumn col in TableToCopy.Columns)
                {
                    row[col.ColumnName] = TableToCopy.Rows[i][col.ColumnName];
                }
                //add value to the column ID
                row["ID"] = index.ToString();

                //add row into new datatable
                tableAfterCopy.Rows.Add(row);

                //increase value index
                index++;
            }
            return tableAfterCopy;
        }

        public DataTable getDataTableUsers()
        {
            DataTable usersTable = new DataTable();
            using (SqlConnection dbConn = new SqlConnection("Data Source=<Data source location>;Initial Catalog=<Catalog name>;Integrated Security=True"))
            {
                using (SqlDataAdapter dbAdapter = new SqlDataAdapter("SELECT * FROM Users",dbConn))
                {
                    dbConn.Open();
                    dbAdapter.Fill(usersTable);
                }
            }

            return usersTable;
        }

The Output




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...

Get Method Names using Reflection [C#]

Leave a Comment
If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name).

To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.

The example will show method name and return type of the method of developersnote class

The developersnote Class

    public class developersnoteClass
    {
        public developersnoteClass()
        {
        }
        public void ConvertDateTime()
        {
        }
        public static void ConvertInteger()
        {
        }
        public static void FormatString()
        {
        }
        public void FormatDouble()
        {
        }
    }


The ASPX Page

<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 Code Behind

       protected void Page_Load(object sender, EventArgs e)
       {
            // get all public static methods of MyClass type
            MethodInfo[] methodInfos = typeof(developersnoteClass).GetMethods(BindingFlags.Public |
                               BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod |
                               BindingFlags.Instance
                               );

            // sort methods by name
            Array.Sort(methodInfos,
                    delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
                    { return methodInfo1.Name.CompareTo(methodInfo2.Name); });

            // write method names
            foreach (MethodInfo methodInfo in methodInfos)
            {
                Response.Write(methodInfo.ReturnType + " "  +  methodInfo.Name  + "<br/>");
            }
        } 


The Output



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...

Read data from DataTable - C#

Leave a Comment
This is the example of reading data from datatable :

The code explaination :

The code will retrieve data from database and store into databable. Andthen , the code will continue by looping each row in a datatable and try to read every column on the row.

The Code

    using System;
    using System.Data;
    using System.Data.SqlClient;

    class PopDataset
    {
       static void Main()
       {
          string connString = "<connection string>";
          string sql = "select * from employee";
          SqlConnection conn = new SqlConnection(connString);

          try
          {
         DataTable dt = new DataTable();
             conn.Open();
             SqlDataAdapter da = new SqlDataAdapter(sql, conn);   
             da.Fill(dt);
         conn.Close();             
             foreach (DataRow row in dt.Rows)
             {
        //read each column in row
                foreach (DataColumn col in dt.Columns)
        {
                   Console.WriteLine(row[col]);
        }
             }
          }
          catch(Exception e)
          {
             Console.WriteLine("Error: " + e);
          }
          finally
          {
             conn.Close();
          }
       }  
    }

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 25 November 2013

Java - Get Visitor/Client ip address : JSP : Servlet

Leave a Comment
The previous post show how to get Visitor or client ip address in C# / ASP.NET .

This post will show how to get ip address of client / visitor from jsp / servlet application. In order to make this method work, you need to test this method on the server and you are accessing the server from your computer. Otherwise you will get your local ipaddress or ::1 value.

The getClientIpAddr Method

     public static String getClientIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader("X-FORWARDED-FOR");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }


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...

C# - Get Visitor/Client ip address : ASP.NET

Leave a Comment
If you want to get the ip address of users from asp.net web application when user access the web page, you can use this method to return the Client / visitor ip address.

Method GetVisitorIPAddress - .Net 4 and above

        /// <summary>
        /// method to get Client ip address
        /// </summary>
        /// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
        /// <returns></returns>
        public static string GetVisitorIPAddress(bool GetLan = false)
        {
            string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (String.IsNullOrEmpty(visitorIPAddress))
                visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (string.IsNullOrEmpty(visitorIPAddress))
                visitorIPAddress = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
            {
                GetLan = true;
                visitorIPAddress = string.Empty;
            }

            if (GetLan)
            {
                if (string.IsNullOrEmpty(visitorIPAddress))
                {
                    //This is for Local(LAN) Connected ID Address
                    string stringHostName = Dns.GetHostName();
                    //Get Ip Host Entry
                    IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                    //Get Ip Address From The Ip Host Entry Address List
                    IPAddress[] arrIpAddress = ipHostEntries.AddressList;

                    try
                    {
                        visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
                    }
                    catch
                    {
                        try
                        {
                            visitorIPAddress = arrIpAddress[0].ToString();
                        }
                        catch
                        {
                            try
                            {
                                arrIpAddress = Dns.GetHostAddresses(stringHostName);
                                visitorIPAddress = arrIpAddress[0].ToString();
                            }
                            catch
                            {
                                visitorIPAddress = "127.0.0.1";
                            }
                        }
                    }
                }
            }
            return visitorIPAddress;
        }


Method GetVisitorIPAddress - .Net 3.5 and below

         /// <summary>
        /// method to get Client ip address
        /// </summary>
        /// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
        /// <returns></returns>
        public static string GetVisitorIPAddress(bool GetLan)
        {
            string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (String.IsNullOrEmpty(visitorIPAddress))
                visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (string.IsNullOrEmpty(visitorIPAddress))
                visitorIPAddress = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
            {
                GetLan = true;
                visitorIPAddress = string.Empty;
            }

            if (GetLan)
            {
                if (string.IsNullOrEmpty(visitorIPAddress))
                {
                    //This is for Local(LAN) Connected ID Address
                    string stringHostName = Dns.GetHostName();
                    //Get Ip Host Entry
                    IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                    //Get Ip Address From The Ip Host Entry Address List
                    IPAddress[] arrIpAddress = ipHostEntries.AddressList;

                    try
                    {
                        visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
                    }
                    catch
                    {
                        try
                        {
                            visitorIPAddress = arrIpAddress[0].ToString();
                        }
                        catch
                        {
                            try
                            {
                                arrIpAddress = Dns.GetHostAddresses(stringHostName);
                                visitorIPAddress = arrIpAddress[0].ToString();
                            }
                            catch
                            {
                                visitorIPAddress = "127.0.0.1";
                            }
                        }
                    }
                }
            }
            return visitorIPAddress;
        }


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 24 November 2013

Netbean : java.lang.OutOfMemoryError: Java heap space - Solutions

Leave a Comment
In java application development, sometimes your application will throw an exception

run:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.classpackage.MainConsole.main(MainConsole.java:24)
Java Result: 1 


This is because your program consuming a lot of memory. One of the solutions is to increase the Xms and Xmx argument on the project.

Lets see the example :

The Main Class

import java.util.ArrayList;
import java.util.List;

public class MainConsole {
    public static void main(String[] args){
        List<PhoneContacts> phoneContacts = new ArrayList<PhoneContacts>();
        // You can use diamond inference in JDK 7 like example below
        //List<PhoneContacts> phoneContacts = new ArrayList<>();
        
        for(int index = 0;index< 10000000;index++ ){
            PhoneContacts p = new PhoneContacts();
            p.setFirstName("developersnote" + Integer.toString(index));
            p.setLastName("developersnote" + Integer.toString(index));
            p.setPhoneNumber(Integer.toString(index));
            phoneContacts.add(p);            
        }        
        for(PhoneContacts p : phoneContacts){
            System.out.println(p.getPhoneNumber());
        }
    }    
}


The Phone Contacts Class

public class PhoneContacts {
    
    private String firstName;
    private String lastName;
    private String phoneNumber;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    
}


The above example will cause out of memory exception . So the solutions is to increase the argument in JVM. Lets see the solution below.

The Solutions

  1. Right click  on the java project >> properties
  2. Set the VM options -Xms512m -Xmx1024m  (You can increase the value -Xmx to the suitable maximum memory allocation depends on your project memory consumption).  
  3. Refer this post -X Command line options post for more information


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...

SCRIPT5007: Unable to get value of the property '0': object is null or undefined - jquery.jqGrid.js

Leave a Comment

If you try to create data grid using mvc jqGrid and somehow the error above occur while debugging script using IE Debugger. Please follow this step to fix it..

The error because of in your mvc jqGrid coding, you not specify the json reader.
Just add this line of code in your View and also in your mvc jqGrid .

The Solution

@{
                MvcJqGrid.DataReaders.JsonReader jsonReader = new MvcJqGrid.DataReaders.JsonReader();
                jsonReader.RepeatItems = false;
                jsonReader.Id = "dataJson";
            }

@(Html.Grid("GridDataBasic")
                .SetCaption("List Of User")
                .AddColumn(new Column("AdminID"))
                .AddColumn(new Column("Email"))
                .AddColumn(new Column("Tel"))
                .AddColumn(new Column("Role"))
                .AddColumn(new Column("Active"))
                .SetUrl("/Home/GridDataBasic")
                .SetAutoEncode(true)
                .SetDataType(MvcJqGrid.Enums.DataType.Json)
                .SetAutoWidth(false)
                .SetWidth(650)
                .SetRowNum(10)
                .SetJsonReader(jsonReader)
                .SetLoadUi(MvcJqGrid.Enums.LoadUi.Block)
                .SetRowList(new int[] { 10, 15, 20, 50 })
                .SetViewRecords(true)
                .SetGridView(true)
                .SetEmptyRecords("No record Found")
                .SetShowAllSortIcons(true)
                .SetShrinkToFit(true)            
                .SetPager("pager"))

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 23 November 2013

Simple Image Galery in PHP - Example

Leave a Comment
This post is a different from others post. because in this example i will use PHP language to create very simple Image Galery.

The code will get list from image directory, and the build a image tag element in html to show the image. Very simple.

Lets see the example.

The  Project list Folder and file



The PHP File 

<html>
    <body>        
        <h1>Image Gallery</h1>        
        <div style="width:640px;">
            <?php 
            //change directory to image stored location
            //if image is at another server try to do like this 
            //$dir = 'http://<server ip address>/<location at server>'
            //make sure image is accessible
            $dir    = 'Images';
            $files1 = scandir($dir);           
            
            foreach ($files1 as $value) {
                if(strtoupper(explode('.', $value)[1]) == "JPG"){//make sure image is JPG or just remove this filter                                   
                    echo "<img src=\"";
                    echo $dir ;
                    echo "\\";
                    echo $value ;
                    echo "\" width=\"200px\" ";
                    echo "height=\"200px\" ";
                    echo " />";
                    echo "<br/>";                           
                }
            }
            ?>
        </div>        
    </body>    
</html>

The Output



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 use PathGradientBrush WrapMode Property

Leave a Comment


Here The code To Create Page like picture above.

The code behind

       protected void Button1_Click(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(600, 300);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);

            GraphicsPath gPath = new GraphicsPath();
            Rectangle rect = new Rectangle(0, 0, 100, 100);
            gPath.AddRectangle(rect);

            PathGradientBrush pathGradientBrush = new PathGradientBrush(gPath);
            pathGradientBrush.CenterColor = Color.Crimson;

            Color[] colors = { Color.Snow, Color.IndianRed };
            pathGradientBrush.SurroundColors = colors;
            pathGradientBrush.WrapMode = WrapMode.Tile;

            Rectangle rect2 = new Rectangle(0, 0, 300, 300);
            g.FillRectangle(pathGradientBrush, rect2);

            pathGradientBrush.WrapMode = WrapMode.TileFlipXY;
            Rectangle rect3 = new Rectangle(300, 0, 300, 300);
            g.FillRectangle(pathGradientBrush, rect3);

            String path = Server.MapPath("~/Image/PathGradientBrushWrapModeProperty.jpg");
            bmp.Save(path, ImageFormat.Jpeg);

            Image1.ImageUrl = "~/Image/PathGradientBrushWrapModeProperty.jpg";
            g.Dispose();
            bmp.Dispose(); 
        }


Page aspx code

  
<!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>
        <h2 style="color: WindowText; font-style: normal;">
            How to use PathGradientBrush WrapMode Property
            System.Drawing.Drawing2D.PathGradientBrush
            PathGradientBrush.WrapMode Property
            .NET GDI+ Graphics
        </h2>
        <hr width="600" align="left" color="DarkBlue" />
        <asp:Image ID="Image1" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Test PathGradientBrush WrapMode Property"
            Height="45"  />
    </div>
    </form>
</body>
</html>

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...

Javascript - Inline Code VS External Files

Leave a Comment

Inline Code

<html>
<head> 
<script type="text/javascript">
function a()
{
alert('hello world'); 
} 
</script>
</head>
<body>
:
:
</body>
</html>

External Files

<html>
<head> 
<script type="text/javascript" src="/scriptone.js">
</script>
</head>
<body>
:
:
</body>
</html>

scriptone.js

function a()
{
alert('hello world'); 
} 

As you can see from the above example,  what is the advantage to put all script in one file and just call it from html(External Code) instead of just write it in html(inline code).?

The answer is here :

  1.  By using external code, the javascript code is much more maintainability :- javascript Code that is sprinkled throughout various HTML pages turns code maintenance into a problem. It is much easier to have a directory for all javascript files so that developers can edit JavaScript code independent of the markup in which it is used.
  2. Caching - browser cache all externally linked JavaScript files according to specific settings, meaning that if two pages are using the same file, the file is download only once. This ultimately means faster page load times.
  3. Future-proof - By including JavaScript using external files, there is no need use the XHTML. The syntax to include external files is the same for both HTML and XHTML.


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...

Friday 22 November 2013

Step by step how to create MVCJQGrid ASP.NET MVC4

1 comment
First step is to install MVCJQGrid in your project application(MVC). In This tutorial i will show you how to install MVCJQGrid using NuGet in Microsoft Visual Studio 2010.

Install MVCJQGrid


1. In VS2010 open NuGet Manager.

2. Search MVCJQGrid and install the latest MVCJQGrid from NuGet Package Manager.


Note : Recommended install latest version of JQGrid

3. Apply Installed NuGet Package into your project.


Ok done the first step. Now your project already have MVCJQGrid package with it.


Create your first Data Grid using MVCJQGrid


First of all in order for you to start write MVCJQGrid coding, you need to add new namespace for the project. In This tutorial i will add the MvcJQGrid in web.config file :

Web.Config File


     <pages>
          <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Optimization" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
            <add namespace="MvcSiteMapProvider.Web.Html" />
            <add namespace="MvcJqGrid" />
          </namespaces>
        </pages>




Lets Start Coding

If you using BundleConfig class to add bundle of javascript file to your share layout view , configure your BundleConfig class to include jQGrid script file and the css style :

BundleConfig

       bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                                "~/Scripts/jquery-{version}.js",
                                "~/Scripts/i18n/grid.locale-en.js",
                                 "~/Scripts/jquery.jqGrid.js",
                                 "~/Scripts/jquery-ui-1.10.0.js"
                                ));
        bundles.Add(new StyleBundle("~/Content/css").Include(
                        "~/Content/site.css",
                        "~/Content/jquery.jqGrid/ui.jqgrid.css"                  
                        ));


Or just add file jquery.jqGrid.js,jquery-ui-1.10.0.js and css style ui.jqgrid.css  using old style method :

        <script type="text/javascript" src="jquery.jqGrid.js"></script>
        <script type="text/javascript" src="jquery-ui-1.10.0.js"></script>
        <link href="ui.jqgrid.css" type="text/css" rel="Stylesheet" /> 


Lets add coding MVCJQGrid for your first data grid in MVC. Add code below in your view to create data grid in your view


The View

    @using MvcJqGrid
         @{
                    MvcJqGrid.DataReaders.JsonReader jsonReader = new MvcJqGrid.DataReaders.JsonReader();
                    jsonReader.RepeatItems = false;
                    jsonReader.Id = "dataJson";
          }

           @(Html.Grid("GridDataBasic")
                    .SetCaption("List Of User")
                    .AddColumn(new Column("AdminID"))
                    .AddColumn(new Column("Email"))
                    .AddColumn(new Column("Tel"))
                    .AddColumn(new Column("Role"))
                    .AddColumn(new Column("Active"))
                    .SetUrl("/Home/GridDataBasic")
                    .SetAutoEncode(true)
                    .SetDataType(MvcJqGrid.Enums.DataType.Json)
                    .SetAutoWidth(false)
                    .SetWidth(650)
                    .SetRowNum(10)
                    .SetJsonReader(jsonReader)
                    .SetLoadUi(MvcJqGrid.Enums.LoadUi.Block)
                    .SetRowList(new int[] { 10, 15, 20, 50 })
                    .SetViewRecords(true)
                    .SetGridView(true)
                    .SetEmptyRecords("No record Found")
                    .SetShowAllSortIcons(true)
                    .SetShrinkToFit(true)               
                    .SetPager("pager"))


Ok now create method in controller to handle request fromView. This method will handle every request from View and will pass JSON result to View


The Controller

    public ActionResult GridDataBasic(GridSettings grid)
            {
                IRepositoryUser _repository = new IRepositoryUser();
                var query = _repository.Users();

                //sorting
                query = query.OrderBy<User>(grid.SortColumn, grid.SortOrder);
                //count
                var count = query.Count();
                //paging
                var data = query.Skip((grid.PageIndex - 1) * grid.PageSize).Take(grid.PageSize).ToArray();
                var result = new
                {
                    total = (int)Math.Ceiling((double)count / grid.PageSize),
                    page = grid.PageIndex,
                    records = count,
                    rows = (from UserInfo in data
                            select new
                            {
                                AdminID = UserInfo.AdminID.ToString(),
                                Email = UserInfo.Email,
                                NoTel = UserInfo.Tel,
                                Role = UserInfo.Role,
                                Active = UserInfo.Active,
                            }).ToArray()
                };
                return Json(result, JsonRequestBehavior.AllowGet);
            } 


When you copy code above. There will be error because you need to create Class IRepositoryUser, Class User, Class LinqExtensions, enum WhereOperation, and Class StringEnum.

So just copy and paste code below and try to understand the coding work.

Class IRepositoryUser

    class IRepositoryUser
        {
            public IQueryable<User> Users()
            {
                return new List<User>()
                {
                    new User { AdminID = "John", Tel="010-99002202", Role="Administrator", Email="John@gmail.com" , Active="Active"},
                    new User { AdminID = "Johny", Tel="010-99002202", Role="Administrator", Email="Johny@gmail.com" , Active="Active"},
                    new User { AdminID = "samuel", Tel="010-99002202", Role="Super Administrator", Email="samuel@gmail.com" , Active="Active"},
                }.AsQueryable();
            }
        } 

Class User

     public class User
        {
            public string AdminID { get; set; }
            public string Email { get; set; }
            public string Tel { get; set; }
            public string Role { get; set; }
            public string Active { get; set; }
        }


enum WhereOperation

    public enum WhereOperation
        {

            [StringValue("eq")]
            Equal,
            [StringValue("ne")]
            NotEqual,
            [StringValue("cn")]
            Contains
        }   

static class LinqExtensions

    public static class LinqExtensions
        {
            /// <summary>Orders the sequence by specific column and direction.</summary>
            /// <param name="query">The query.</param>
            /// <param name="sortColumn">The sort column.</param>
            /// <param name="ascending">if set to true [ascending].</param>
            public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
            {
                if (sortColumn == "")
                {
                    sortColumn = "AdminID";
                }

                string methodName = string.Format("OrderBy{0}",
                    direction.ToLower() == "asc" ? "" : "descending");

                ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

                MemberExpression memberAccess = null;
                foreach (var property in sortColumn.Split('.'))
                    memberAccess = MemberExpression.Property
                       (memberAccess ?? (parameter as Expression), property);

                LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

                MethodCallExpression result = Expression.Call(
                          typeof(Queryable),
                          methodName,
                          new[] { query.ElementType, memberAccess.Type },
                          query.Expression,
                          Expression.Quote(orderByLambda));

                return query.Provider.CreateQuery<T>(result);
            }

            public static IQueryable<T> Where<T>(this IQueryable<T> query,
                string column, object value, WhereOperation operation)
            {
                if (string.IsNullOrEmpty(column))
                    return query;

                ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");
                MemberExpression memberAccess = null;
                foreach (var property in column.Split('.'))
                    memberAccess = MemberExpression.Property
                       (memberAccess ?? (parameter as Expression), property);


                //change param value type
                //necessary to getting bool from string
                ConstantExpression filter = Expression.Constant
                    (
                        Convert.ChangeType(value, memberAccess.Type)
                    );

                //switch operation
                Expression condition = null;
                LambdaExpression lambda = null;
                switch (operation)
                {
                    //equal ==
                    case WhereOperation.Equal:
                        condition = Expression.Equal(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;

                    //not equal !=
                    case WhereOperation.NotEqual:
                        condition = Expression.NotEqual(memberAccess, filter);
                        lambda = Expression.Lambda(condition, parameter);
                        break;

                    //string.Contains()
                    case WhereOperation.Contains:
                        condition = Expression.Call(memberAccess,
                            typeof(string).GetMethod("Contains"),
                            Expression.Constant(value));
                        lambda = Expression.Lambda(condition, parameter);
                        break;
                }

                MethodCallExpression result = Expression.Call(
                       typeof(Queryable), "Where",
                       new[] { query.ElementType },
                       query.Expression,
                       lambda);

                return query.Provider.CreateQuery<T>(result);

            }

        }


 class StringEnum

     public class StringEnum
        {
            #region Instance implementation

            private Type _enumType;
            private static Hashtable _stringValues = new Hashtable();

            /// <summary>
            /// Creates a new <see cref="StringEnum"/> instance.
            /// </summary>
            /// <param name="enumType">Enum type.</param>
            public StringEnum(Type enumType)
            {
                if (!enumType.IsEnum)
                    throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));

                _enumType = enumType;
            }

            /// <summary>
            /// Gets the string value associated with the given enum value.
            /// </summary>
            /// <param name="valueName">Name of the enum value.</param>
            /// <returns>String Value</returns>
            public string GetStringValue(string valueName)
            {
                Enum enumType;
                string stringValue = null;
                try
                {
                    enumType = (Enum)Enum.Parse(_enumType, valueName);
                    stringValue = GetStringValue(enumType);
                }
                catch (Exception) { }//Swallow!

                return stringValue;
            }



            /// <summary>
            /// Gets the string values associated with the enum.
            /// </summary>
            /// <returns>String value array</returns>
            public Array GetStringValues()
            {
                ArrayList values = new ArrayList();
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in _enumType.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        values.Add(attrs[0].Value);

                }
                return values.ToArray();
            }

            /// <summary>
            /// Gets the values as a 'bindable' list datasource.
            /// </summary>
            /// <returns>IList for data binding</returns>
            public IList GetListValues()
            {
                Type underlyingType = Enum.GetUnderlyingType(_enumType);
                ArrayList values = new ArrayList();
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in _enumType.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));

                }
                return values;

            }

            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <returns>Existence of the string value</returns>
            public bool IsStringDefined(string stringValue)
            {
                return Parse(_enumType, stringValue) != null;
            }

            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Existence of the string value</returns>
            public bool IsStringDefined(string stringValue, bool ignoreCase)
            {
                return Parse(_enumType, stringValue, ignoreCase) != null;
            }

            /// <summary>
            /// Gets the underlying enum type for this instance.
            /// </summary>
            /// <value></value>
            public Type EnumType
            {
                get { return _enumType; }
            }

            #endregion

            #region Static implementation

            /// <summary>
            /// Gets a string value for a particular enum value.
            /// </summary>
            /// <param name="value">Value.</param>
            /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
            public static string GetStringValue(Enum value)
            {
                string output = null;
                Type type = value.GetType();

                if (_stringValues.ContainsKey(value))
                    output = (_stringValues[value] as StringValueAttribute).Value;
                else
                {
                    //Look for our 'StringValueAttribute' in the field's custom attributes
                    FieldInfo fi = type.GetField(value.ToString());
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                    {
                        _stringValues.Add(value, attrs[0]);
                        output = attrs[0].Value;
                    }
                }
                return output;
            }



            /// <summary>
            /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
            /// </summary>
            /// <param name="type">Type.</param>
            /// <param name="stringValue">String value.</param>
            /// <returns>Enum value associated with the string value, or null if not found.</returns>
            public static object Parse(Type type, string stringValue)
            {
                return Parse(type, stringValue, false);
            }

            /// <summary>
            /// Parses the supplied enum and string value to find an associated enum value.
            /// </summary>
            /// <param name="type">Type.</param>
            /// <param name="stringValue">String value.</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Enum value associated with the string value, or null if not found.</returns>
            public static object Parse(Type type, string stringValue, bool ignoreCase)
            {
                object output = null;
                string enumStringValue = null;

                if (!type.IsEnum)
                    throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in type.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        enumStringValue = attrs[0].Value;

                    //Check for equality then select actual enum value.
                    if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                    {
                        output = Enum.Parse(type, fi.Name);
                        break;
                    }
                }
                return output;
            }

            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="enumType">Type of enum</param>
            /// <returns>Existence of the string value</returns>
            public static bool IsStringDefined(Type enumType, string stringValue)
            {
                return Parse(enumType, stringValue) != null;
            }

            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="enumType">Type of enum</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Existence of the string value</returns>

            public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
            {

                return Parse(enumType, stringValue, ignoreCase) != null;
            }

            #endregion
        } 

class StringValueAttribute : Attribute

    public class StringValueAttribute : Attribute
        {
            private string _value;

            /// <summary>
            /// Creates a new <see cref="StringValueAttribute"/> instance.
            /// </summary>
            /// <param name="value">Value.</param>
            public StringValueAttribute(string value)
            {
                _value = value;
            }

            /// <summary>
            /// Gets the value.
            /// </summary>
            /// <value></value>
            public string Value
            {
                get { return _value; }
            }
        }




Output


for more information, please take a look at this demo to play with MvcJQGrid and github page.

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.