Rss Feed Like Us on facebook Google Plus
Showing posts with label asp.net. Show all posts
Showing posts with label asp.net. Show all posts

November 18, 2013

Retrieve Data from Client Machine DataBase on Web using Javascript Active-X object

To Retrieve data from Local database you can use JavaScript simulation using Active-X
object on your Asp.net Website.

If all of your users are on Windows computers, you could use ADO or ODBC to connect to a corresponding database. checkout the example

Limitations:
This script will work only on Internet Explorer

EXAMPLE

SCRIPT:

<script id="clientEventHandlersJS" type="text/javascript">
        function GetData() {
            var connection = new ActiveXObject("ADODB.Connection");
            var connectionstring = "Data Source=AJIT-LAPTOP\\sqlexpress;Initial Catalog=user;User ID=ajit;Password=ajit;Provider=SQLOLEDB";
            connection.Open(connectionstring);
            if (connection) {
                var rs = new ActiveXObject("ADODB.Recordset");
    //FOR Single Record
                var userid = document.getElementById("txtuserid").value;
                rs.open("select password from userdetail where userid='" + userid + "'", connection);
                if (!rs.EOF) {
                    var c1 = rs.fields("userid").value;
                    alert(c1);
                }
                else {
                    alert("Record Not Found");
                }
              //For Multiple Records
          rs.Open ("select col1,col2 from tbl_test", conn,0,1);
          while (! rs.EOF)
          {
             c1 = rs.fields("col1").value;
             c2 = rs.fields("col2").value;
             document.write(c1+' - '+c2+'<br>');
             rs.MoveNext ();
          }
                rs.close();
                rs = null;
                connection.close;
                return true;
            }
            else {
                return false;
            }
        }
    </script>

HTML:

<form id="form1" runat="server">
    <table>
        <tr>
            <td>
               USER ID: <input type="text" id="txtuserid" runat="server" />
                <input type="button" id="btn" onclick="javascript:return GetData()" style="width: 80px;
                    height: 30px;" value="OK" runat="server" />
            </td>
        </tr>
    </table>
    </form>



Read More

October 28, 2013

Dynamic Google Chart with Asp.net , C Sharp

To display live data on your site using Google chart with asp.net 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 asp.net, 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="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Chart.aspx/GetData',  // Your aspx page url with web method..
                data: '{}',
                success:
                    function (response) {
                        drawVisualization(response.d);
                    }
            });
        })

        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"} }
            });
        }        
    </script>


2. HTML ( Design Page chart.aspx)

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

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)
    {

    }

    [WebMethod]
    public static List<Data> GetData()
    {
        SqlConnection conn = new SqlConnection("--YOUR CONNECTION STRING--;");
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        conn.Open();
        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);
        adp.Fill(ds);
        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

August 29, 2013

JQuery ColorBox : Do Postback for inline HTML

While using JQuery Color Box with inline content , postback of submit button is not working...



CAUSE:
Color Box script generates an iframe for your target Page/Html.In case of inline content/html ColorBox generates an iframe outside the  <form> tag. As we all know to do postback we need  <form> tag. So in generated iframe HTML there is no  <form> tag available.

SOLUTION:
very simple hack , we have to just append the generated iframe html to <form> tag. checkout the below script.

SCRIPT

<script type="text/javascript">
        function cbox() {
            $.colorbox({ inline: true, width: "50%", href: "#inline_content", onOpen: AllowPostback });
        }
        function AllowPostback() {
            $("div#cboxOverlay").appendTo("form:first");
            $("div#colorbox").appendTo("form:first");
        }
    </script>

HTML

<div id='inline_content' style='padding:10px; background:#fff;'>
      <h2>Inline Content </h2>
      <input type="submit" id="btn" name="btn" />
</div>



Read More

August 24, 2013

Use More Than One Web.Config File : Asp.Net

If you have planned to have different Web.config files for sub-folders in the application root folder. It helps us to have small and easily maintainable configuration files.

System wide configuration settings are defined in the Machine.config for the .NET Framework. The Machine.config file is located in the  C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG
folder. The settings defined in this file are applicable to all ASP.NET applications in that system.

We can override these default settings by including a Web.config file in the application's root folder.

By including Web.config files in sub-folders, we can override the settings defined in the Web.config file in the application's root folder.

The following are sample section declarations from a Machine.config file:
<section name="processModel" 
  type="System.Web.Configuration.ProcessModelConfigurationHandler, 
        System.Web, Version=1.0.5000.0, Culture=neutral, 
        PublicKeyToken=b03f5f7f11d50a3a" 
  allowDefinition="MachineOnly"/>
 
<section name="sessionState" 
  type="System.Web.SessionState.SessionStateSectionHandler, 
        System.Web, Version=1.0.5000.0, Culture=neutral, 
        PublicKeyToken=b03f5f7f11d50a3a" 
  allowDefinition="MachineToApplication"/>
 
<section name="appSettings" 
  type="System.Configuration.NameValueFileSectionHandler, System,
        Version=1.0.5000.0, Culture=neutral, 
        PublicKeyToken=b77a5c561934e089"/>
There is an attribute allowDefinition specified in the first two section declarations with the values: MachineOnlyand MachineToApplication.

What it does mean?

If allowDefinition="MachineOnly", then we can not override this section either in application level or in folder level. The only section declared in the Machine.config file with this settings is processModel.

If allowDefinition="MachineToApplication", then we can override these sections by the root directoryWeb.config. Sections with this setting 
in Machine.config are authenticationmachineKeysessionStatetrust, and securityPolicy.
If allowDefinition attribute is omitted in a section declaration of the Machine.config file, we can override that section at any level.

We can override the section appSettings at any level and can access it by usingConfigurationSettings.AppSettings easily.


Read More

August 15, 2013

Auto Refresh an Asp.Net Web page


when You want to Refresh a web page automatically..
You can simply add following line of code in the Header section to enable auto refresh in an ASP.NET web page.
<meta http-equiv="refresh" content="15">
Where 15 refers to the number of seconds it will take before refreshing the page.
Also you can redirect to a specific page if you put the URL inside the tag.

<meta http equiv="refreshcontent="15;url=http://www.techimpulsion.in" >
In reality, this is standard HTML functionality and nothing specific to ASP.NET. The same effect of auto-refresh would be seen whether it is an ASP.NET page or just a HTML page, or a page made in Java, PHP, ColdFusion, Perl or the like.
More Preferential for Asp.net Developers

If you want to set the refresh time dynamically then that can be done in ASP.NET by adding server side code in the Page_Load function to set it, as shown below: 
Response.AppendHeader("Refresh", "15")
you can change the refresh time according to your requirement.
Read More

August 9, 2013

Disable Ctrl+C ,Ctrl+V ,Ctrl+A in a web page : Javascript

Question How to disable Ctrl+C , Ctrl+V , Ctrl+A in any web page by using javascript.

More..
Disable Button after clicking on it.

Solution:
just copy and paste below script in <head> section


<script type="text/javascript">
        function Disable_Control_C() {
            var keystroke = String.fromCharCode(event.keyCode).toLowerCase();
 
            if (event.ctrlKey && (keystroke == 'c' || keystroke == 'v' || keystroke == 'a')) {
                alert("This function not allowed");
                event.returnValue = false; // disable Ctrl+C
            }
        }
    </script>

and call the function in html body

<body onkeydown="javascript:Disable_Control_C()">
Hello World!
</body>
</html>
Read More

August 7, 2013

Disable Right Click Button - Javascript

while developing web application ,some situation arises where we have to disable right click button of a mouse in web pages of Asp.Net,PHP ,JSP. you can achieve this by using Javascript.

Qusetion - How to disable right click button of mouse in webpage.

Solution- 
add below script in head section of web page

<script type="text/javascript">
        var msg = "This function is disabled!";
        var bV = parseInt(navigator.appVersion)
        var bNS = navigator.appName == "Netscape"
        var bIE = navigator.appName == "Microsoft Internet Explorer"
 
        function nrc(e) {
            if (bNS && e.which > 1) {
                alert(msg)
                return false
            } else if (bIE && (event.button > 1)) {
                alert(msg)
                return false;
            }
        }
 
        document.onmousedown = nrc;
        if (document.layers) window.captureEvents(Event.MOUSEDOWN);
        if (bNS && bV < 5) window.onmousedown = nrc;
    </script>
..........................................................................................

Read Also...

How to prevent page going back on backspace button click

Read More

July 12, 2013

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

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)
    {
        try
        {
            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;
            p.Start();
            p.WaitForExit();
            p.Close();
            p.Dispose();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  
Read More

© 2011-2016 Techimpulsion All Rights Reserved.


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