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

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.

Reference:-


Read More

© 2011-2016 Techimpulsion All Rights Reserved.


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