Rss Feed Like Us on facebook Google Plus
Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

October 28, 2013

Dynamic Google Chart with , C Sharp

To display live data on your site using Google chart with and C#.

  • Google chart tools are powerful, simple to use, and free. Try out our rich gallery of interactive charts and data tools
to create Dynamic Google chart with, we have to fetch data in Data Table with your preferred back-end server, checkout following steps...
  1. Fetch data in Data Table..
  2. Convert Data into JSON format
  3. Pass JSON Data to Script with web method
  4. Pass JSON Data to google.visualization.DataTable()
  5. Execute Google Chart Script - new google.visualization.ColumnChart("HtmlElementID")
Below is Code Example with three types of chart..(Column Chart, Line Chart, Combo Chart)

1. SCRIPT ( Design Page chart.aspx)

<script src="//" type="text/javascript"></script>
    <script type="text/javascript" src="//"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    <script type="text/javascript">
        $(document).ready(function () {
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Chart.aspx/GetData',  // Your aspx page url with web method..
                data: '{}',
                    function (response) {

        function drawVisualization(dataValues) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Product Catalogue');
            data.addColumn('number', 'Total Sales');
            data.addColumn('number', 'MOP');
            for (var i = 0; i < dataValues.length; i++) {
                data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Value2]);
            var options = {
                title: 'Total Sales by Years',
                is3D: true,
                hAxis: { title: 'Product Catalogue', titleTextStyle: { color: 'red'} }
            new google.visualization.ColumnChart(document.getElementById('Div1')).
                draw(data, options);

            new google.visualization.LineChart(document.getElementById('Div2')).
            draw(data, options);

            new google.visualization.ComboChart(document.getElementById('visualization')).
            draw(data, {
                title: 'Total Sales by Years',
                width: 600,
                height: 400,
                is3D: true,
                vAxis: { title: "Total Sales" },
                hAxis: { title: "Produt Catalogue" },
                seriesType: "bars",
                series: { 1: { type: "line"} }

2. HTML ( Design Page chart.aspx)

    <form id="form1" runat="server">
        <div id="visualization" style="width: 600px; height: 350px;">
        <div id="Div1" style="width: 600px; height: 350px;">
        <div id="Div2" style="width: 600px; height: 350px;">

3. Code Behind ( chart.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

public partial class Chart : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)


    public static List<Data> GetData()
        SqlConnection conn = new SqlConnection("--YOUR CONNECTION STRING--;");
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        string cmdstr = @"select productcatalogue,convert(decimal,sum(localamt)) as totalsales ,convert(decimal,sum(mop)) as mop
                        from [salesdata] group by productcatalogue ";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        dt = ds.Tables[0];
        List<Data> dataList = new List<Data>();
        string cat = "";
        decimal val = 0;
        decimal val2 = 0;
        foreach (DataRow dr in dt.Rows)
            cat = dr[0].ToString();
            val = Convert.ToDecimal(dr[1]);
            val2 = Convert.ToDecimal(dr[2]);
            dataList.Add(new Data(cat,val,val2));
        return dataList;
public class Data
    public string ColumnName = "";
    public decimal Value = 0;
    public decimal Value2 = 0;
    public Data(string columnName, decimal value, decimal value2)
        ColumnName = columnName;
        Value = value;
        Value2 = value2;

Read More

September 11, 2013

Upload files to FTP server using C#

Upload any type of files (text,zip,images etc.) to FTP using C#

In order to upload a file using FTP details, one should know the server’s FTP URL, FTP username and FTP password.

We can achieve the file uploading task by using the below three inbuilt classes of .NET: FtpWebRequest,WebRequestMethods, and NetworkCredential.

Here is a sample code to upload TEXT file.

using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
    public class WebRequestGetExample
        public static void Main ()
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("");
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","");
            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("testfile.txt");
            byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            request.ContentLength = fileContents.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

>> As we know streamreader used only to read text files / binary files. here is sample code to upload all type of files.

private static void up(string sourceFile, string targetFile)
        string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
        string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
        string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
        ////string ftpURI = "";
        string filename = "ftp://" + ftpServerIP + "//" + targetFile; 
        FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
        ftpReq.UseBinary = true;
        ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
        ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        byte[] b = File.ReadAllBytes(sourceFile);
        ftpReq.ContentLength = b.Length;
        using (Stream s = ftpReq.GetRequestStream())
            s.Write(b, 0, b.Length);
        FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
        if (ftpResp != null)
    catch (Exception ex)

Read More

July 12, 2013

Convert Web Page (Aspx,Html) to PDF File -

For many developers while developing applications the question arises that How to Convert  Web Page (Aspx,Html,php) to PDF File. Solution is here..

You can convert any web URL in to PDF file by this utility.

Convert html to pdf using webkit (qtwebkit)

Searching the web, I have found several command line tools that allow you to convert a HTML-document to a PDF-document, however they all seem to use their own, and rather incomplete rendering engine, resulting in poor quality. Recently QT 4.4 was released with a WebKit widget (WebKit is the engine of Apples Safari, which is a fork of the KDE KHtml), and making a good tool became very easy.

Simple shell utility to convert HTML to PDF using the webkit rendering engine, and qt.

That is it. You can go to any web page... even aspx. is supported better than any other utility as it uses the web-kit HTML rendering engine (Safari, Chrome). Enjoy
There is a single .exe (7 mb) that can be used from .Net simply by using Process.Start Make sure that you copy the exe into your project directory or you have to specify the full path..

Example: -

public void HtmlToPdf(string website, string destinationFile)
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\wkhtmltopdf.exe";
            website = "\"" + website + "\"";
            string arguments1 = website + " " + destinationFile;
            p.StartInfo.Arguments = arguments1;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
        catch (Exception ex)
            throw ex;
Read More

July 9, 2013

Real World Example of Abstract Class and Interface

An abstract class is a class that you cannot create an instance of. It can provide basic functionality, but in order for that functionality to be used, one or more other classes must derive from the abstract class. One of the major benefits of abstract classes is that you can reuse code without having to retype it. 

That has a plethora of benefits, such as reducing bugs and making coding faster. A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). 

The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

Now, an interface is like an abstract class, except it does not contain any logic. Rather, it specifies an interface. So, there might be an interface called IFly. This might have the methods GoForward and GoDown. Those methods would not actually contain any logic... each class that implements interface IFly would have to implement those GoForward and GoDown methods. You could have classes Duck and Finch implement interface IFly. Then, if you want to keep a list of instances that can fly, you just create a list that contains items of type IFly. That way, you can add Ducks and Finches and any other instance of a class the implements IFly to the list.

So, abstract classes can be used to consolidate and share functionality, while interfaces can be used to specify what the common functionality that will be shared between different instances will be, without actually building that functionality for them. Both can help you make your code smaller, just in different ways. There are other differences between interfaces and abstract classes, but those depend on the programming language, so I won't go into those other differences here.

Do you mean real-world as in "A live software system which includes  Abstract classes or interfaces" or do you mean "

If you mean the latter think of Vehicle as an abstract class. You can't yet do anything with it because you have no idea what it does, or how to drive it.

abstract class Vehicle{}

Vehicles could be split into morotized and pedal-powered, but still this is abstract, we still dont know what to do with it.

abstract class MotorVehicle : Vehicle {} 
abstract class PedaledVehicle : Vehicle {}

You could now define a concrete (non-abstract) class, like car.

class MotorCar : MotorVehicle {}

 Intefaces come in handy you can only inherit from one base class. So imagine some vehicles are drivable, others are remote controlled, some vehicles use a stearing wheel, others dont

interface IDrivable{}
interface IHasStearingWheel{}

Now you could derive a DrivableMotorCar from its base clas, and also implement other behaviours.
class DrivableMotorCar : MotorVehicle, IDrivable, IHasStearingWheel {}

Recommendations for Abstract Classes vs. Interfaces

The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


Read More

July 4, 2013

How to prevent page going back on backspace button click

Stop page going back on backspace button click in,C#,java,PHP.

1. To prevent page going back on backspace or browser back button. you can achieve this by short snippet by javascript below.

<script type="text/javascript">
function preventBack() 
setTimeout(function () { preventBack() }, 0);
window.onunload = function () { null };

Follow my blog with Bloglovin
Read More

Disable Button after once Click by Javascript

Disable Button after clicking on it.If when you set disabled="disabled" immediately after
the user clicks the button, and the form doesn't submit because before form submission button is already diasabled..

Uses- It prevents double form submission/ prevent double postback

 you could try these things

1st Way...

<script type="text/javascript">
function disable() {
            var v = confirm('Are you sure to save');
            if (v == true) {
                setTimeout(function () { document.getElementById('<%= btnSave.ClientID %>').disabled = true }, 1);
                return true;
            return false;
        function preventBack() { window.history.forward(); }
        setTimeout(function () { preventBack() }, 0);
        window.onunload = function () { null };
<input type="button" id="btnsave" runat="server" value="Save" onclick="javascript:disable()" />
2nd Way

myInputButton.disabled = "disabled";
Whether it be due to a users lack of tech know-how or a twitch of the finger, a secondary click of a forms ‘Submit’ button could result in the form being submitted twice. Depending on the action of the form this could in turn send two enquiries, create two orders or insert a record into the database twice.

3rd Way

<input type="submit" name="Submit" value="Submit" onclick="this.disabled=true; this.value='Please Wait...';" /> 

4th Way
We can also use AJAX to disable postback element on Request Begin to prevent multiple clicks.

<form id="form1" runat="server">
<asp:scriptmanager id="sc" runat="server" enablepartialrendering="true">  
<script type="text/javascript">
    function beginReq(sender, args) {
        document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing.....";
        args.get_postBackElement().disabled = true;
<asp:updatepanel id="updpnlSubmit" runat="server">  
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />  
        <asp:Label ID="lblMessage" runat="server"></asp:Label>  

Read More

June 27, 2013

change internet explorer page setup programmatically with C#

Change printer setting of internet explorer with C#,basically you can change it bu updating
registry key.

Users can easily change Internet Explorer printer settings for the page margins, the header, and the footer through the Internet Explorer user interface. However, Internet Explorer and the Web Browser control do not include methods to change these settings programmatically.

The following steps outline how Microsoft Internet Explorer accesses the printer settings:

  1. Internet Explorer tries to obtain the values from the following registry key:
    HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\PageSetup
  2. If the key in step 1 does not exist, Internet Explorer tries to create this key by copying the values from the following key:
    HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\PageSetup
  3. If the key in step 2 does not exist, default values are provided.
Checkout the below program..

using Microsoft.Win32;
namespace iesttings
    Class ie
        public void ChangeIEPageSetupSetting()
            string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup";
            bool bolWritable = true;
            string strName = "header";
            object oValue = "";
            string strName1 = "footer";
            object oValue1 = "";
            string strName2 = "margin_top";
            object oValue2 = "0.75";
            string strName3 = "margin_right";
            object oValue3 = "0.75";
            string strName4 = "margin_bottom";
            object oValue4 = "0.75";
            string strName5 = "margin_left";
            object oValue5 = "0.75";
            RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable);
            oKey.SetValue(strName, oValue);
            Console.WriteLine("0 updated");
            oKey.SetValue(strName1, oValue1);
            Console.WriteLine("1 updated");
            oKey.SetValue(strName2, oValue2);
            Console.WriteLine("2 updated");
            oKey.SetValue(strName3, oValue3);
            Console.WriteLine("3 updated");
            oKey.SetValue(strName4, oValue4);
            Console.WriteLine("4 updated");
            oKey.SetValue(strName5, oValue5);
            Console.WriteLine("5 updated");
    class Program
        static void Main(string[] args)
           ie obj = new ie();

Note : - Your Web Application should have rights to change the registry settings.

Read More

© 2011-2016 Techimpulsion All Rights Reserved.

The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.