Tuesday 31 December 2013

Remove Whitespace From aspx pages - Performance with page speed

Leave a Comment
Some web page have a thousand line of html code and it will increase the size of the page to download to users. It is often possible to make a content of web page fewer bytes(their size) without changing the appearance or function of the page. This approach will improve download time and makes the page load faster.

The question how to make this happen without extra effort to remove the space manually and without effect the development time.

This is a snippet code that you need to put in your Master page so that the code will automatically override the Render Event in asp.net

The Code to put in Master Page

The Attribute/Field for masterpage
private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);
private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);


The Override Method

        /// <summary>
        /// Initializes the <see cref="T:System.Web.UI.HtmlTextWriter"></see> object and calls on the child 
        /// controls of the <see cref="T:System.Web.UI.Page"></see> to render.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"></see> that receives the page content.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
            {
                base.Render(htmlwriter);
                string html = htmlwriter.InnerWriter.ToString();

                html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
                html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

                writer.Write(html.Trim());
            }
        } 

The Output 

Before
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title></title>
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
</body>
</html>


After
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head><title> </title><link href="Styles/Site.css" rel="stylesheet" type="text/css" /> </head> <body></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...

Friday 27 December 2013

Understanding The Web Page Processing(End To End)

Leave a Comment
A common way to think about the Web is that there is a browser on one end of a network connection
and a web server with a database on the other end.

 Simplified web architecture model

The simplified model is easy to explain and understand, and it works fine up to a point. However,
quite a few other components are actually involved, and many of them can have an impact on
performance and scalability.The next picture shows some of them for web sites based on ASP.NET and SQL Server.

Web architecture components that can impact performance

All of the components in picture above can introduce delay into the time it takes to load a page, but that delay is manageable to some degree. Additional infrastructure-oriented components such as routers, load balancers, and firewalls aren’t included because the delay they introduce is generally not very manageable from a software architecture perspective.

In the following list, I’ve summarized the process of loading a web page. Each of these steps offers  opportunities for optimization.
  1. First, the browser looks in its local cache to see whether it already has a copy of the page.(see this post for knowledge about caching, Improve load page performance by setting Browser Cache for Static Content - ASP.NET , Caching in ASP.NET advantage and example , Javascript - Inline Code VS External Files )
  2. If the page isn’t in the local cache, then the browser looks up the IP address of the web or proxy server using DNS. The browser and the operating system have each have separate DNS caches to store the results of previous queries. If the address isn’t already known or if the cache entry has timed out, then a nearby DNS server is usually consulted next (it’s often in a local router, for example).
  3. Next, the browser opens a network connection to the web or proxy server. Proxy servers can be either visible or transparent. A visible proxy is one that the user’s browser or operating system is aware of . They are sometimes used at large companies, for example, to help improve web performance for their employees or sometimes for security or filtering purposes. A transparent proxy intercepts all outgoing TCP connections on port 80 (HTTP), regardless of local client settings. If the local proxy doesn’t have the desired content, then the HTTP request is forwarded to the target web server.
  4. Some ISPs also use proxies to help improve performance for their customers and to reduce the bandwidth they use. As with the local proxy, if the content isn’t available in the ISP proxy cache, then the request is forwarded along.
  5. The next stop is a web server at the destination site. A large site will have a number of load-balanced web servers, any of which will be able to accept and process incoming requests. Each machine will have its own local disk and separate caches at the operating system driver level (http.sys), in Internet Information Services (IIS), and in ASP.NET.
  6. If the requested page needs data from the database, then the web server will open a connection to one or more database servers. It can then issue queries for the data it needs. The data might reside in RAM cache in the database, or it might need to be read in from disk.
  7. When the web server has the data it needs, it dynamically creates the requested page and sends it back to the user. If the results have appropriate HTTP response headers, they can be cached in multiple locations.
  8. When the response arrives at the client, the browser parses it and renders it to the screen.

This are the process actually involved when client enter the url at browser ( www.google.com.my for example) . If the web application already in good scalability and good performance while the other component not as good as the application. The end result also will be "slow performance" .

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

Simple Image Resizer Tools - C# Example

Leave a Comment
This example will use the  Image Resizer Class from previous post. I have change a little bit on the class so that i can use it for my example image resizer tools.

ImageResizer Tool Requirement

  • ImageResizer tool will require user to choose the image to resize.
  • Only JPG image supported.
  • After that user can simply put the width and height to change the selected image width and height.
  • User can choose is either to use aspect ratio.
  • After Complete , user will prompt to open the new image after resize.
  • The tools use .NET version 4.

The GUI of ImageResizer Tool

The Code Behind

        private string _ImageName;
        private string _ImageExtension;

        public Form1()
        {
            InitializeComponent();
            TPercentage.Text = "0";
            tWidth.Text = "0";
            THeight.Text = "0";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "JPEG Files (.JPG)|*.JPG";
            openFileDialog1.FilterIndex = 1;

            openFileDialog1.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            DialogResult Dr = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (Dr.ToString().Equals("OK",StringComparison.CurrentCultureIgnoreCase))
            {
                TSelectImage.Text = openFileDialog1.FileName;
                _ImageName = (openFileDialog1.FileName.Split('\\'))[openFileDialog1.FileName.Split('\\').Length - 1];
                _ImageExtension = _ImageName.Substring(_ImageName.Length - 4);
                loadImage();
            }
        }

        protected void loadImage(string filename = "")
        {
            panel1.Visible = true;
            pictureBox1.WaitOnLoad = false;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            if(filename == "")
                pictureBox1.LoadAsync(openFileDialog1.FileName);
            pictureBox1.LoadCompleted += new AsyncCompletedEventHandler(pictureBox1_LoadCompleted);
        }

        void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //label3.Text = pictureBox1.Image.Width.ToString();
            //label5.Text = pictureBox1.Image.Height.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string reSizeImageName = _ImageName + "_Resize" + _ImageExtension;
            long width = Convert.ToInt64(tWidth.Text);
            long height = Convert.ToInt64(THeight.Text);
            double percentageRatio = Convert.ToDouble(TPercentage.Text);
           

        AGAIN:
            ImageResizer.ResizeImage(pictureBox1.ImageLocation, Directory.GetCurrentDirectory() + "\\" + reSizeImageName,
                100,percentageRatio,width,height,checkBox1.Checked);

            if (ImageResizer.Status == 1)           
                goto AGAIN;//this is because method need to run in async which is not supported in .NET 4 ..only support .NET 4.5 currently


            DialogResult dr = MessageBox.Show("Resize succes, open file in an external viewer?", "Open File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "\\" + reSizeImageName);
            }           

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                label2.Visible = false;
                label3.Visible = false;
                tWidth.Visible = false;

                label4.Visible = false;
                label5.Visible = false;
                THeight.Visible = false;

                label6.Visible = true;
                TPercentage.Visible = true;
                label7.Visible = true;
                TPercentage.Text = "0";
                tWidth.Text = "0";
                THeight.Text = "0";
            }
            else
            {
                label2.Visible = true;
                label3.Visible = true;
                tWidth.Visible = true;

                label4.Visible = true;
                label5.Visible = true;               
                THeight.Visible = true;

                label6.Visible = false;
                TPercentage.Visible = false;
                label7.Visible = false;
                tWidth.Text = "0";
                THeight.Text = "0";
                TPercentage.Text = "0";
            }
        }

        private void TPercentage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }



The Modified ImageResizer Class

class ImageResizer
    {
        private static ImageCodecInfo jpgEncoder;
        private static int _status;

        public static int Status
        {
            get { return ImageResizer._status; }
            set { ImageResizer._status = value; }
        }

        /// <summary>
        /// Method to resize JPEG and GIF Image
        /// </summary>
        /// <param name="inFile">input file location</param>
        /// <param name="outFile">output file location</param>
        /// <param name="level"> level of compression between 0 and 100, with 0 being maximum compression and minimum size and 
        /// with 100 being minimum compression and maximum size.(For JPEG Only)</param>
        /// <param name="maxDimension">percentage ratio</param>
        /// <param name="newWidth">width of new image</param>
        /// <param name="newHeight">height of new image</param>
        /// <param name="useAspectRatio">true | false</param>
        public static void ResizeImage(string inFile, string outFile, long level,double maxDimension = 0, long newWidth = 0, long newHeight = 0,bool useAspectRatio = false)
        {       
        
            byte[] buffer;
            using (Stream stream = new FileStream(inFile, FileMode.Open))
            {
                buffer = new byte[stream.Length];
                Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
            }

            try
            {
                using (MemoryStream memStream = new MemoryStream(buffer))
                {
                    using (Image inImage = Image.FromStream(memStream))
                    {
                        double width = 0;
                        double height = 0;

                        if (newWidth > 0)
                            width = Convert.ToDouble(newWidth);
                        if (newHeight > 0)
                            height = Convert.ToDouble(newHeight);

                        if (useAspectRatio)
                        {
                            width = inImage.Width * (maxDimension / 100);
                            height = inImage.Height * (maxDimension / 100);                            
                        }

                        using (Bitmap bitmap = new Bitmap((int)width, (int)height))
                        {
                            using (Graphics graphics = Graphics.FromImage(bitmap))
                            {
                                graphics.SmoothingMode = SmoothingMode.HighQuality;
                                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                graphics.DrawImage(inImage, 0, 0, bitmap.Width, bitmap.Height);
                                if (inImage.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                                {
                                    if (jpgEncoder == null)
                                    {
                                        ImageCodecInfo[] ici = ImageCodecInfo.GetImageDecoders();
                                        foreach (ImageCodecInfo info in ici)
                                        {
                                            if (info.FormatID == ImageFormat.Jpeg.Guid)
                                            {
                                                jpgEncoder = info;
                                                break;
                                            }
                                        }
                                    }
                                    if (jpgEncoder != null)
                                    {
                                        EncoderParameters ep = new EncoderParameters(1);
                                        ep.Param[0] = new EncoderParameter(Encoder.Quality, level);
                                        bitmap.Save(outFile, jpgEncoder, ep);
                                    }
                                    else
                                    {
                                        bitmap.Save(outFile, inImage.RawFormat);
                                    }
                                }
                                else
                                {
                                    //
                                    // Fill with white for transparent GIFs
                                    //
                                    graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);
                                    bitmap.Save(outFile, inImage.RawFormat);

                                }                                
                                Status = 0;
                            }
                        }
                    }
                }
            }
            catch (ArgumentException arg)
            {
                if (arg.Message.Equals("Parameter is Not Valid.", StringComparison.CurrentCultureIgnoreCase))
                    Status = 1;
                else
                    MessageBox.Show(arg.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "." + Environment.NewLine + "Please Try Again");
            }
        }
       
    }



Have a try ..Do PM me in Google+ to share the project.

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

Example to disable save as certain file type in SSRS Report Viewer

Leave a Comment
SQL Server Reporting Service(SSRS) is a full range of ready-to-use tools and services to help you create, deploy, and manage reports for your organization, as well as programming features that enable you to extend and customize your reporting functionality.

The Report Viewer provide functionality to save the report as a pdf, word and also as a excel format. Sometime organization require this feature, sometime not. This is how to disable save as function in Report Viewer(SSRS).

The example will invoke methode pre-render in Report Viewer Controller.

The ASPX Page

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %> 

:

:

: 

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt"
        InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt"
        Height="730px" Width="886px" ShowCredentialPrompts="False" ShowDocumentMapButton="False"
        ShowParameterPrompts="False" ShowWaitControlCancelLink="False" EnableTheming="False"
        ExportContentDisposition="AlwaysAttachment" OnPreRender="ReportViewer1_PreRender">
        <LocalReport ReportPath="Reports\Report1.rdlc">
            <DataSources>
                <rsweb:ReportDataSource DataSourceId="SqlDataSource1" Name="DataSet1" />               
            </DataSources>
        </LocalReport>
    </rsweb:ReportViewer>
  
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:UnitTrustSystemConnectionString %>"
        SelectCommand="SELECT [CREATE_USERID], [REPORT_ID], [SEQ_NO], [V1], [V2], [V3] FROM [T_REPORT_DTL] WHERE ([CREATE_USERID] = @CREATE_USERID)">
        <SelectParameters>
            <asp:QueryStringParameter Name="CREATE_USERID" QueryStringField="uid" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

The Code Behind

        protected void ReportViewer1_PreRender(object sender, EventArgs e)
        {
            DisableUnwantedExportFormat((ReportViewer)sender, "Excel");
            DisableUnwantedExportFormat((ReportViewer)sender, "Word");
        } 



        /// <summary>
        /// Hidden the special SSRS rendering format in ReportViewer control
        /// </summary>
        /// <param name="ReportViewerID">The ID of the relevant ReportViewer control</param>
        /// <param name="strFormatName">Format Name</param>
        public void DisableUnwantedExportFormat(ReportViewer ReportViewerID, string strFormatName)
        {
            FieldInfo info;
            foreach (RenderingExtension extension in ReportViewerID.LocalReport.ListRenderingExtensions())
            {
                if (extension.Name.Trim().ToUpper() == strFormatName.Trim().ToUpper())
                {
                    info = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
                    info.SetValue(extension, false);
                }
            }

        }

The Output Before

The Output After


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 17 December 2013

Multiple Button in MVC 4

Leave a Comment
Many developers now have experience on ASP.NET Web development but when microsoft introduce the new solution for web development(ASP.NET Model View Controller - MVC framework) back at April 2009, not all developers like it. Because ASP.NET is just drag and drop, and easy to use different with ASP.NET MVC.

Recently i have develop one web application using MVC framework and this is my first experience using it i never done it before...

Just want to share some information for newbie like me to have a multiple button in one form. Sound like very easy but it is very popular in google search keyword "Multiple Button MVC" ..

ok here the solution i figure out :

Solution One

The View(cshtml)

    @using (Html.BeginForm("ActionTaken", "TestController"))
      {
           <button name="button" value="ActionOne" class="button" style="width: 200px;">
              test1</button>
           <button name="button" class="button" style="width: 160px;" value="ActionTwo">
             test2</button>        
       }


The Controller

          [AcceptVerbs(HttpVerbs.Post)]
          public ActionResult ActionTaken(string butt)
          {
             string ButtCommand= butt;
             switch (ButtCommand)
             {
                case "ActionOne":
                  //do stuff here
                case "ActionTwo":
                 //do stuff here
                default:
                        return View();
             }
          }


Solution Two

Sometimes when you use solution one and you click on the button, there is no event fire on the browser even the postback action not happen.(mostly in IE6) .. Here i figure out the second solution how to handle that thing.

change on the view part like this :

The View

    @using (Html.BeginForm("ActionTaken", "TestController"))
    {
       <input type="submit" class="button" style="width: 130px;" value="test1" />
       <input type="button" class="button" style="width: 150px;" value="test2"
             onclick=" onclick="$('#ResetForm').submit();" />
    } 
    @using (Html.BeginForm("ResetButton", "TestController", FormMethod.Post, new { id = "ResetForm" }))
    {
    }

The Controller

   public ActionResult ResetButton()
   {
       //do stuff here
   }
   public ActionResult ActionTaken()
   {
       //do stuff here
   }



The second button will call form with id #ResetButton and postback to server..


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 16 December 2013

How to open file using their default external viewer - C#

Leave a Comment
When write the application, some of the activity is to create file, convert file, etc . After create the file, the program should prompt user to open the created file using their respective default external viewer . Letsay you create .pdf file, so the default application to open the file is Adobe Reader .

The example will ask user is either user want to open file or not, if user agreed to open the file created, then the application will open file using their respective default external viewer depend on the file extension .

The code

   string outFilePath = File.Create("PDFFILE.pdf");                            
   DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
   if (dr == DialogResult.Yes)
   {
      System.Diagnostics.Process.Start(outFilePath);
   }


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 read XML file in PHP

Leave a Comment
 In this example show how to read xml file in PHP. Let say the XML file is like this :

<?xml version="1.0" encoding="utf-8"?>
<database>
<config userdb="custinfosys" dbpass="P@ssw0rd" host="localhost:3306" database="customerinfosys"/>
<defaultPassword></defaultPassword>
</database>


So i want to read config element and all of the attribute . Here is a sample code to read xml file :

PHP -> read XML File :

        //declare DOMDocument
        $objDOM = new DOMDocument();

        //Load xml file into DOMDocument variable
        $objDOM->load("../configuration.xml");

        //Find Tag element "config" and return the element to variable $node
        $node = $objDOM->getElementsByTagName("config");

        //looping if tag config have more than one
        foreach ($node as $searchNode) {
            $dbHost = $searchNode->getAttribute('host');
            $dbUser = $searchNode->getAttribute('userdb');
            $dbPass = $searchNode->getAttribute('dbpass');
            $dbDatabase = $searchNode->getAttribute('database');
        }


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 15 December 2013

How to execute sql query statement in PHP

Leave a Comment
We have learn how to create connection and select database in PHP, now i will show how to run query in php.

we will use "mysqli_query" or "mysql_query " method to run the query in php.
Assume we already have connection and already select the database in PHP, here is a example to run the query statement.

NOTE : Refer both post above to create connection and select database

The Database Table

CREATE TABLE IF NOT EXISTS `users` (
  `userid` varchar(40) NOT NULL,
  `password` varchar(80) NOT NULL,
  `ROLES` varchar(40) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`userid`, `password`, `ROLES`) VALUES
('developersnote', 'P@ssw0rd', 'ADMIN');


The code

<?php

require_once('DbUtility.php');
$dbClass = new DbUtility();
$db = $dbClass->getDbConnectionMySQLi();

if (mysqli_connect_errno($db)) {
    $error = '<p><br />Failed to Connect to Database' . mysqli_connect_error();
} else {
    $dbClass->setDatabaseMySQLi($db);
    $strsql = "SELECT * FROM users where userid='developersnote' AND password='P@ssw0rd'";
    $dbComm = mysqli_query($db, $strsql);
    $num_rows = mysqli_num_rows($dbComm);
    if ($num_rows > 0) {
        session_start();
        $row = mysqli_fetch_array($dbComm);
        $_SESSION["LOGINID"] = 'developersnote';
        $_SESSION["ROLES"] = $row["ROLES"]; //read value from column ROLES in query result
        
        //header("Location: ../secure/defaultPage.php"); //redirect to default page..but i will echo successful message
        echo 'Successful';
    } else {
        echo "Is Either Username or password was wrongly entered : " . mysqli_error($db);
    }
}
?>



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

Select Database in PHP Example

Leave a Comment
This post is a extended from previous post. Read previous here

This example show how to select database schema / name in database MySQL :

The DbUtil Class

<?php

final class DbUtility {
    
    public static $dbHost ;
    public static $dbUser ;
    public static $dbPass ;
    public static $dbDatabase ;

    public function __construct() {  
        self::$dbHost = "localhost:3306";
        self::$dbUser = "custinfosys";
        self::$dbPass = "P@ssw0rd";
        self::$dbDatabase = "customerinfosys"; // database 
    }

    public static function getDbConnectionMySQL() {       
        return mysql_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse         
    }
    public static function getDbConnectionMySQLi() {       
        return mysqli_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse         
    }
    
    public static function setDatabaseMySQL($db){              
        mysql_select_db($db,self::$dbDatabase) or die("Couldn't select the database.");
    }
    
    public static function setDatabaseMySQLi($db){              
        mysqli_select_db($db,self::$dbDatabase) or die("Couldn't select the database.");
    }    
    

}
?>


How to use Example

1. Create php file name index to test the class
2. copy paste this code and try to run in browser using xamp / any web server install with php

<?php

require_once('DbUtility.php');
$dbClass = new DbUtility();
$db = $dbClass->getDbConnectionMySQLi();
if (mysqli_connect_errno($db)) {
    echo '<br/>Failed to Connect to Database' . mysqli_connect_error();
} else {
    echo '<br/>successfully create connection with "mysqli_connect"';
    $dbClass->setDatabaseMySQLi($db);
    echo '<br/>successfully set database with "mysqli_select_db"';
}

$db1 = $dbClass->getDbConnectionMySQL();
if (mysql_error($db1)) {
    echo '<br/>Failed to Connect to Database' . mysql_error();
} else {
    echo '<br/>successfully create connection with "mysql_connect"';
    $dbClass->setDatabaseMySQL($db1);
    echo '<br/>successfully set database with "mysql_select_db"';
}
?> 

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 create mysql connection in php

Leave a Comment
 The example will show how to create connection to MySQL database using "mysql_connect" or "mysqli_connect" . The mysql_connect has been deprecated. Read here for more information.

The  DbUtil Class

<?php

final class DbUtil {
    
    public static $dbHost ;
    public static $dbUser ;
    public static $dbPass ;


    public function __construct() {  
        self::$dbHost = "<host name>";
        self::$dbUser = "<user name db>";
        self::$dbPass = "<pasword db>";
        }

   public static function getDbConnectionMySQL() {     
        return mysql_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse        
    }
    public static function getDbConnectionMySQLi() {      
        return mysqli_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse        
    }




?>


How to use Example

1. Create php file name index to test the class
2. copy paste this code and try to run in browser using xamp / any web server install with php

<?php

require_once('DbUtility.php');
$dbClass = new DbUtility();
$db = $dbClass->getDbConnectionMySQLi();
if (mysqli_connect_errno($db)) {
    echo '<br/>Failed to Connect to Database' . mysqli_connect_error();
} else {
    echo '<br/>successfully create connection with "mysqli_connect"';
}

$db1 = $dbClass->getDbConnectionMySQL();
if (mysql_error($db1)) {
    echo '<br/>Failed to Connect to Database' . mysqli_connect_error();
} else {
    echo '<br/>successfully create connection with "mysql_connect"';
}
?>

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

Sunday 8 December 2013

How to convert List to DataTable - C#,ASP.NET

Leave a Comment

Short Description

This example will show how to convert List<T> where T could be any object and convert the List<T> to DataTable. The example will use two class which is System.ComponentModel; and System.Data;

Note : The Convertion class extention method must be in static because System.ComponentModel.TypeDescriptor is a static method

In this example i will use asp.net .

The ASPX page

     <h1>
        How to convert List To DataTable
    </h1>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>


The Code Behind

       protected void Page_Load(object sender, EventArgs e)
        {
            List<string> listOfString = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                listOfString.Add(i.ToString());
            }            
            GridView1.DataSource = Convertion.ToDataTable<string>(listOfString); 
            GridView1.DataBind();
        }


The Convertion Class

    public static class Convertion
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                table.Columns.Add(prop.Name, (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() ==
                    typeof(Nullable)) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
                foreach (T item in data)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor _prop in properties)
                    {
                        row[_prop.Name] = item;
                        table.Rows.Add(row);
                    }
                }
            }
            return table;
        }
    }


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

Saturday 7 December 2013

Tips of send or reply email for customer

Leave a Comment
Email is a one medium to communicate to others people. Mostly now days people use email to communicate with customer. I have learn something which i want to share with others  tips to send or reply email to your customer. Hopefully this note will be useful for someone.

As you know, the problem with emails is that  they do not have "tone".  The interpretation of our emails is concluded by the intended recipient.  Sometimes, the interpretation differs from what we meant. As a small step to improve our customer service and professionalism, let us start with the ethics of emails.  There's a lot being written on the Net but I listed down here the common ones.

Tips of send or reply email to customer

  1. Take care of your grammar and spelling - people may perceive you as sloppy.
  2. Use salutation - Dear Sir... Dear Madam...
  3. Careful with capital letters.  People may interpret your words as screaming or yelling.
  4. Think twice on who you want to C.C. Big bosses may be annoyed with unnecessary C.C.
  5. Go straight to the point.
  6. Some issues are better to be resolved by conducting discussion.  To ensure our backs are covered, after each discussion, quickly distribute discussion notes (issues and action plan).
  7. Be nice.


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 6 December 2013

C#: Retrieve Machine Information

Leave a Comment
This is a example how to get Machine Information in C#. The example will use Class ManagementObjectSearcher --> System.Management

Note: The code will only work on Window 32 bit, If you are using 64 bit Operation system, you need to comment few Method GetTotalPhysicalMemory,GetTotalVirtualMemory,and GetAvailableVirtualMemory.

The MachineInfo Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Net;
using System.Diagnostics;

namespace GenericErrorHandling
{
    class MachineInfo
    {
        ManagementObjectSearcher query;
        ManagementObjectCollection result;
        string responseString;
        int responseInt;

        public string GetMachineName()
        {
            return Environment.MachineName.ToUpper();
        }
        public string GetOSVersion()
        {
            return Environment.OSVersion.VersionString;
        }
        public string GetProcessorCount()
        {
            return Environment.ProcessorCount.ToString();
        }
        public string GetIPAddress()
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ipAddress = ipEntry.AddressList;
            return ipAddress[ipAddress.Length - 1].ToString();
        }
        public string GetTotalPhysicalMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["TotalPhysicalMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }
        public string GetAvailablePhysicalMemory()
        {
            PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes");
            responseInt = ((int)Convert.ToInt64(counter.NextValue()) * (-1)) / (1024 * 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }

        public string GetTotalVirtualMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["TotalVirtualMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;
        }

        public string GetAvailableVirtualMemory()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalMemoryConfiguration");
            result = query.Get();

            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["AvailableVirtualMemory"].ToString());
            }
            responseInt = (responseInt / 1024);
            responseString = responseInt.ToString() + " MB";
            return responseString;

        }
        public string GetCpuFrequency()
        {
            query = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
            result = query.Get();
            foreach (ManagementObject managementObject in result)
            {
                responseInt = Convert.ToInt32(managementObject["CurrentClockSpeed"].ToString());
            }
            responseString = responseInt.ToString() + " MHz";
            return responseString;
        }
    }

}


The Code To Show Machine Information

        private void button2_Click(object sender, EventArgs e)
        {
            MachineInfo M = new MachineInfo();
            string msg = "Number Of Processor : " + M.GetProcessorCount();
            msg += "\nProcessor MHZ : " + M.GetCpuFrequency();
            msg += "\nMachine Name : " + M.GetMachineName();
            msg += "\nGetOSVersion : " + M.GetOSVersion();
            msg += "\nGetIPAddress : " + M.GetIPAddress();
            msg += "\nGetTotalPhysicalMemory : " + M.GetTotalPhysicalMemory();
            msg += "\nGetAvailablePhysicalMemory : " + M.GetAvailablePhysicalMemory();
            msg += "\nGetTotalVirtualMemory : " + M.GetTotalVirtualMemory();
            msg += "\nGetAvailableVirtualMemory : " + M.GetAvailableVirtualMemory();

            MessageBox.Show(msg);

        }


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

Wednesday 4 December 2013

How to Upload CSV File into database MSSQL

Leave a Comment

Brief Description

The post will show code example how to upload CSV file data into Database and insert bulk record into SQL server database.

Before we start the example, create the table in the database :

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CSVTABLE](
    [ID] [int] NOT NULL,
    [NAME] [varchar](40) NOT NULL,
    [ADDRESS] [varchar](80) NOT NULL,
    [POSKOD] [varchar](15) NOT NULL,
    [NOTEL] [varchar](15) NOT NULL,
 CONSTRAINT [PK_CSVTABLE] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

After create the table on the database, now we can proceed on the code example. Let say the csv file like this :

The CSV File

1,NAMA1,ADDRESS1,POSKOD1,NOTEL1
2,NAMA2,ADDRESS2,POSKOD2,NOTEL2
3,NAMA3,ADDRESS3,POSKOD3,NOTEL3
4,NAMA4,ADDRESS4,POSKOD4,NOTEL4
5,NAMA5,ADDRESS5,POSKOD5,NOTEL5
6,NAMA6,ADDRESS6,POSKOD6,NOTEL6
7,NAMA7,ADDRESS7,POSKOD7,NOTEL7
8,NAMA8,ADDRESS8,POSKOD8,NOTEL8
9,NAMA9,ADDRESS9,POSKOD9,NOTEL9
10,NAMA10,ADDRESS10,POSKOD10,NOTEL10
11,NAMA11,ADDRESS11,POSKOD11,NOTEL11
12,NAMA12,ADDRESS12,POSKOD12,NOTEL12
13,NAMA13,ADDRESS13,POSKOD13,NOTEL13
14,NAMA14,ADDRESS14,POSKOD14,NOTEL14
15,NAMA15,ADDRESS15,POSKOD15,NOTEL15
16,NAMA16,ADDRESS16,POSKOD16,NOTEL16
17,NAMA17,ADDRESS17,POSKOD17,NOTEL17
18,NAMA18,ADDRESS18,POSKOD18,NOTEL18
19,NAMA19,ADDRESS19,POSKOD19,NOTEL19
20,NAMA20,ADDRESS20,POSKOD20,NOTEL20
21,NAMA21,ADDRESS21,POSKOD21,NOTEL21
22,NAMA22,ADDRESS22,POSKOD22,NOTEL22
23,NAMA23,ADDRESS23,POSKOD23,NOTEL23
24,NAMA24,ADDRESS24,POSKOD24,NOTEL24
25,NAMA25,ADDRESS25,POSKOD25,NOTEL25

save the csv file as Book1.csv at Drive D:\ . So now run the script in sql server to insert all records as a bulk copy into database .

The Script sql statement


USE Testing123  

BULK
INSERT CSVTABLE
FROM 'D:\Book1.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

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

C#: use EventLog to store error message example

Leave a Comment
EventLog lets you access or customize Windows event logs, which record information about important software or hardware events. Using EventLog, you can read from existing logs, write entries to logs, create or delete event sources, delete logs, and respond to log entries. You can also create new logs when creating an event source.

The example will show how to use event log in your application

The Code

 private void button1_Click(object sender, EventArgs e)
 {
    try
    {
        string[] a = new string[3];
        a[4] = "test";
    }
    catch (Exception ex)
    {
        LogError(ex);
    }
 }
 public void LogError(Exception ex)
 {
    string EventLogSourceName = "Example Log Error";
    int EventLogErrorCode = 99;
    string msg = "The application encountered an unknown error:";
    msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name;
    msg += "\r\nError Message: " + ex.Message;
    EventLog.WriteEntry(EventLogSourceName, msg, EventLogEntryType.Error, EventLogErrorCode);
    MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
 }



*The code will get run time error because you need to run application as administrator.


The Output - Event Viewer




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 3 December 2013

How to show hide form(Desktop application) C#

Leave a Comment
Usually when programmer to hide the form from User they will use this command :

this.Hide();


But the problem is..how to unhide that form..So the this is a solution to unhidden the form..

Scenario

You have 2 Form, Form1 and Form2. the situation is form2 was hide and you want to show it back

 foreach (Form form in Application.OpenForms)
 {
     if (form is Form2)
     {
         form.Show();
         break;
     }
 }


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 2 December 2013

How to create XML file using C#

Leave a Comment
XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). Once we create an XML file in one platform it can be used in other platforms also.

In order to creating a new XML file in C#, we are using XmlTextWriter Class . The class takes FileName and Encoding as argument. Also we are here passing formatting details . The following C# source code creating an XML file product.xml and add four rows in the file

The Code

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace WindowsApplication1
{
   public partial class Form1 : Form
   {
      public Form1()
      {
          InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
          XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
          writer.WriteStartDocument(true);
          writer.Formatting = Formatting.Indented;
          writer.Indentation = 2;
          writer.WriteStartElement("Table"); 
          createNode("1", "Product 1", "1000", writer);
          createNode("2", "Product 2", "2000", writer);
          createNode("3", "Product 3", "3000", writer);
          createNode("4", "Product 4", "4000", writer);
          writer.WriteEndElement();
          writer.WriteEndDocument();
          writer.Close();
          MessageBox.Show("XML File created ! ");
      }

      private void createNode(string pID, string pName, string pPrice, XmlTextWriter writer)
     {

         writer.WriteStartElement("Product");
         writer.WriteStartElement("Product_id");
         writer.WriteString(pID);
         writer.WriteEndElement();
         writer.WriteStartElement("Product_name");
         writer.WriteString(pName);
         writer.WriteEndElement();
         writer.WriteStartElement("Product_price");
         writer.WriteString(pPrice);
         writer.WriteEndElement();
         writer.WriteEndElement();
      }
   }
}

Output Example

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Table>
  <Product>
    <Product_id>1</Product_id>
    <Product_name>Product 1</Product_name>
    <Product_price>1000</Product_price>
  </Product>
  <Product>
    <Product_id>2</Product_id>
    <Product_name>Product 2</Product_name>
    <Product_price>2000</Product_price>
  </Product>
  <Product>
    <Product_id>3</Product_id>
    <Product_name>Product 3</Product_name>
    <Product_price>3000</Product_price>
  </Product>
  <Product>
    <Product_id>4</Product_id>
    <Product_name>Product 4</Product_name>
    <Product_price>4000</Product_price>
  </Product>
</Table>

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

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.