Friday, September 30, 2011

Creating IP Restriction using asp.net


//IPAddress.csv
"IP Address"
"127.0.0.1"





private void GetIPAddressONFile()
    {
        string SystemIpAddress = "";
        string SystemIpName = "";
     
        SystemIpAddress = Request.UserHostAddress;

        SystemIpName = Request.UserHostName;
        SystemIpAddress = Context.Request.ServerVariables["REMOTE_HOST"];
        string path = Server.MapPath("../IPAddress//IPAddress.csv");
        System.IO.FileInfo file = new FileInfo(path);
        DataSet dsCSV = new DataSet();
        dsCSV = ConnectFile(file);

        //DataColumn tableColumn = dsCSV.Tables[0].Columns["IP Address"];
        DataRowCollection tableRows = dsCSV.Tables[0].Rows;
        int count = 0;
        foreach (DataRow row in tableRows)
        {
            if (row["IP Address"].ToString() == SystemIpAddress)
            {
                count += 1;
            }
        }
        if (count < 1)
            Response.Redirect("~/loginsubmit.aspx?Msg=NA");
    }


 private DataSet ConnectFile(FileInfo filetable)
    {
        DataSet ds = new DataSet();
        string str;
        try
        {
            ConnCSV = ConnCSV + filetable.DirectoryName.ToString();
            string sqlSelect;
            OleDbConnection objOleDBConn;
            OleDbDataAdapter objOleDBDa;
            objOleDBConn = new OleDbConnection(ConnCSV);
            objOleDBConn.Open();
            sqlSelect = "select * from [" + filetable.Name.ToString() + "]";
            objOleDBDa = new OleDbDataAdapter(sqlSelect, objOleDBConn);
            objOleDBDa.Fill(ds);
            objOleDBConn.Close();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return ds;
    }

Read CSV Files into Dataset using asp.net

set in web.config
<appSettings>
  <add key="connxls" value="Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='text;HDR=Yes;FMT=Delimited';Data Source=" />
</appSettings>


In test.aspx.cs
using System.Data.OleDb;
using System.Collections.Specialized;



protected void Page_Load(object sender, EventArgs e)
    {
NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
        ConnCSV = config["connxls"];
      

    }

protected void UploadButton_Click(object sender, EventArgs e)
    {
string str=strSavedFilePath;
System.IO.FileInfo file11 = new FileInfo(str);
            DataSet dsCSV = new DataSet();
            dsCSV = ConnectFile(file11);

}
  private DataSet ConnectFile(FileInfo filetable)
    {
        DataSet ds = new DataSet();
        string str;
        try
        {
            ConnCSV = ConnCSV + filetable.DirectoryName.ToString();
            string sqlSelect;
            OleDbConnection objOleDBConn;
            OleDbDataAdapter objOleDBDa;
            objOleDBConn = new OleDbConnection(ConnCSV);
            objOleDBConn.Open();
            sqlSelect = "select * from [" + filetable.Name.ToString() + "]";
            objOleDBDa = new OleDbDataAdapter(sqlSelect, objOleDBConn);
            objOleDBDa.Fill(ds);
            objOleDBConn.Close();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return ds;
    }






For getting Last modified procedures

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P' order by modify_date desc

Thursday, September 29, 2011

Using CheckBox List Asp.net

In aspx file
 <asp:CheckBoxList ID="chkModuleList" runat="server">
 <asp:ListItem Text="Test 1" Value="1"></asp:ListItem>
 <asp:ListItem Text="Test 2" Value="2"></asp:ListItem>
 <asp:ListItem Text="Test 3" Value="3"></asp:ListItem>
  <asp:ListItem Text="Test 4" Value="4"></asp:ListItem>
  </asp:CheckBoxList>

In aspx.cs file
 for (int i = 0; i <chkModuleList.Items.Count; i++)
        {
string strtest = Convert.ToString(chkModuleList.Items[i].Selected);
//string strtest = Convert.ToString(chkModuleList.Items[i].Value);
//string strtest = Convert.ToString(chkModuleList.Items[i].Text); 
}

Wednesday, September 28, 2011

Check Uncheck radio button with java script

  <script language="javascript" type="text/javascript">
   function CheckUncheckRadio(id) {
            var val;
            var rdo = document.getElementById(id)
            var radio = rdo.getElementsByTagName("input");
            if (radio.checked == true) {

                radio.checked = false;
                val = 0;
            }
            else {

                radio.checked = true;
                val = 1;
            }

            if (val == 0) {
                rdo.checked = false;
            }
            else {
                rdo.checked = true;
            }
        }

    </script>





 <asp:RadioButton ID="rbExpenseCost" runat="server" Text="1" onclick="CheckUncheckRadio('rbExpenseCost');"/>

<asp:RadioButton ID="rbLeaveCost" runat="server"  Text="2" onclick="CheckUncheckRadio('rbLeaveCost');" />
                                                 












Concating two #eval for a label in grid view

  <ItemTemplate>
  <asp:Label ID="totalApprovals" runat="server" ForeColor="#fe9a00" Text='<%#Eval("TotalApprovals")+" "+"Pending"%>'></asp:Label>
  </ItemTemplate>

Tuesday, September 27, 2011

Alert message on hyper link click

 <a href="#" onclick='alert("hiii");return false;'  >Click Here</a>
or
<a href='javascript:alert("hello")'>hello</a>
 
For Confirmation box 
 OnClientClick="return confirm('Are you sure, you want to delete.');"  




Monday, September 26, 2011

Executing .bat files on button click asp.net

 protected void btn_Click(object sender, EventArgs e) 
{
   ProcessStartInfo psi = new ProcessStartInfo(@"C:\bank.bat");
          psi.RedirectStandardOutput = true;
          psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
          psi.UseShellExecute = false;
          System.Diagnostics.Process listFiles;
          listFiles = System.Diagnostics.Process.Start(psi);
          System.IO.StreamReader myOutput = listFiles.StandardOutput;
          listFiles.WaitForExit(2000);
}




//bat file code

@echo off
cd\
c:


start iexplore.exe www.google.com

Binding Grid View,Drop down with in grid view from aspx page

//Drop Down In Item template
//Test .aspx
<asp:DropDownList ID="ddlCreditClient" runat="server" Visible="true" DataSource='<%#BindCreditClient()%>'    DataTextField="CName" DataValueField="ClientId">

//Test.aspx.cs
protected DataTable BindCreditClient()
    {
        DataTable dt = new DataTable();
        //bind data table here
        return dt;
    }


 //Data List  in Item template
//Test.aspx
 <asp:DataList ID="DlInnerWorkFlow" runat="server" RepeatDirection="Horizontal" DataSource='<%#getWorkFlowForm(Convert.ToInt32(Eval("FormId")),(Convert.ToInt32(Eval("DepartmentID"))))%>'>
 <ItemTemplate>
 <asp:Label ID="lblUserName" runat="server" BorderStyle="None" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
 <SeparatorTemplate>
 <asp:Image ID="imgarrow" runat="server" ImageAlign="Bottom" BorderStyle="None" ImageUrl="~/images/btn-arrow_right_Gray.gif" />
 </SeparatorTemplate>
 </asp:DataList>


//Test.aspx.cs

  public DataTable getWorkFlowForm(int FormId, int DepartmentId)
    {
      
        DataTable dt = new DataTable();
      //bind datatable here
          
        return dt;
    }



Telerik Controls Help Urls

//link for implementing google like filetring in telerik grid view
http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx

//File upload control , Upload / Client-side Validation 

http://demos.telerik.com/aspnet-ajax/upload/examples/clientsidevalidation/defaultcs.aspx?RadUrid=af0a12bf-569e-4359-b73b-4116b5daa247 

//Filtering in ComboBox / Autocomplete 

http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/autocompleteclientside/defaultcs.aspx

 //Tool tips Help

http://demos.telerik.com/aspnet-ajax/tooltip/examples/waiariasupport/defaultcs.aspx

 //Tabbed grid in telerik

http://demos.telerik.com/aspnet-ajax/grid/examples/hierarchy/nestedviewtemplate/defaultcs.aspx

//Calender Control,ToolTip / RadToolTip for RadCalendar 

http://demos.telerik.com/aspnet-ajax/tooltip/examples/tooltipcalendar/defaultcs.aspx

//BUG: ASyncFileUpload javascript error affects Firefox 4+ with Upate Panel and Update Progress
http://ajaxcontroltoolkit.codeplex.com/workitem/26932

//Tips for avoiding Spam Filters with System.Net.Mail

 http://www.andreas-kraus.net/blog/tips-for-avoiding-spam-filters-with-systemnetmail/








Creating Google Map with multiple way points and draggable directions using asp.net and java script

//This code is for Creating Google Map with multiple way points and draggable directions using asp.net and java script. Please set design according to your css//

<head id="Head1" runat="server">
     <title>Calculate distance</title>
 
    <script src="http://maps.google.com/maps/api/js?sensor=false&amp;key=ABQIAAAAJBjl1Th9QFwMQaJjFDBKahS_UYXK4NsaVm1AC7JD1mYvEQ3NmBRS7MuG9QhvC79P5JUmScpoMMAI8Q"
        type="text/javascript"></script>

    <script type="text/javascript">

        function showInformation() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
            document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Calculate Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + document.getElementById('txtDistance').value + ' kilometers)';
        }

        function showLocation() {
            geocoder.getLocations(document.forms[0].fromAddress.value, function(response) {
                if (!response || response.Status.code != 200) {
                    alert("Sorry, we were unable to geocode the first address");
                }
                else {
                    location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                    geocoder.getLocations(document.forms[0].toAddress.value, function(response) {
                        if (!response || response.Status.code != 200) {
                            alert("Sorry, we were unable to geocode the second address");
                        }
                        else {
                            location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                            gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                        }
                    });
                }
            });
        }



        var finalToAddress = "";
        var address = 'India'; //Default map location on page load
        var rendererOptions = {
            draggable: true
        };
        var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        var directionsService = new google.maps.DirectionsService();
        var map;
        var mygc = new google.maps.Geocoder();
        mygc.geocode({ 'address': address },

         function(results, status) {
             var country1 = results[0].geometry.location.lat();
             var country2 = results[0].geometry.location.lng();
             var australia = new google.maps.LatLng(country1, country2);
             initialize(australia);
         }
        );

        function initialize(australia) {
            var myOptions =
    {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: australia
    };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));
            google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {


                computeTotalDistance(directionsDisplay.directions);
            });
            calcRoute();

        }

        function calcRoute(fromAddress, toAddress) {
            var items = new Array();
            for (var i = 1; i <= textboxes; i++) {
                items[(i - 1)] = document.getElementById(i.toString()).value;
            }
            var waypoints = [];
            var address;
            address = document.getElementById('toAddress').value;

            if (items.length > 0) {
                waypoints.push({
                    location: address,
                    stopover: true
                })
            };

            for (var i = 0; i < items.length - 1; i++) {
                address = items[i];
                if (address !== "") {

                    waypoints.push({
                        location: address,
                        stopover: true
                    });
                }
            }

            var toAddress1 = "";

            if (waypoints.length != 0) {
                toAddress1 = document.getElementById((waypoints.length).toString()).value;
                finalToAddress = document.getElementById((waypoints.length).toString()).value;

            }
            else {
                toAddress1 = document.getElementById('toAddress').value;
                finalToAddress = document.getElementById('toAddress').value;


            }


            var request = {
                origin: fromAddress,
                destination: toAddress1,

                waypoints: waypoints,

                optimizeWaypoints: false,

                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });
        }

        function computeTotalDistance(result) {
            var total = 0;

            var myroute = result.routes[0];

            for (i = 0; i < myroute.legs.length; i++) {
                total += myroute.legs[i].distance.value;

            }

            total = parseFloat(Math.round((total / 1000) * 100) / 100);
            var measurUnit = 'KM'; //set unit of distance according to you
            if (measurUnit == "KM") {
                document.getElementById('txtDistance').value = total;
                document.getElementById('lblType').innerHTML = "KM";
            }
            else {
                document.getElementById('txtDistance').value = parseFloat(Math.round(((total * 1000) / 1609.344) * 100) / 100);
                document.getElementById('lblType').innerHTML = "Miles";
            }
        }
        function setDirections(fromAddress, toAddress) {
            calcRoute(fromAddress, toAddress);
        }


        /*Functions for adding and removing text boxes*/
        var intTextBox = 0;
        var textboxes = 0;

        function addElement() {
            intTextBox = intTextBox + 1;
            var contentID = document.getElementById('content');
            var newTBDiv = document.createElement('div');
            newTBDiv.setAttribute('id', 'strText' + intTextBox);
            newTBDiv.innerHTML = String.fromCharCode(64 + (intTextBox + 2)) + ' :' + "<input style='margin-top:5px;margin-left:30px;' class='txt3_double' type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
            contentID.appendChild(newTBDiv);
            textboxes = intTextBox;
        }


        function removeElement() {
            if (intTextBox != 0) {
                var contentID = document.getElementById('content');
                contentID.removeChild(document.getElementById('strText' + intTextBox));
                intTextBox = intTextBox - 1;
                textboxes = intTextBox;
            }
        }
                
      
        
        
    </script>

</head>
<body onload="initialize()">
    <form id="Form1" runat="server" action="#" onsubmit="setDirections(this.from.value, this.to.value);return false "
    style="margin-left: 20px; text-align: center; overflow: hidden;">
    <div style="min-height: 325px; min-width: 500px; overflow: hidden; vertical-align: middle;">
        <div>
            <div>
                <b>Calculate Distance</b></div>
            <div>
                <div>
                    A :
                    <div>
                        <input type="text" size="25" id="fromAddress" name="from" />
                        <asp:HiddenField ID="hdnDefault" runat="server" />
                    </div>
                </div>
                <div>
                    <div>
                        B :
                        <div>
                            <input type="text" size="25" id="toAddress" name="to" class="txt3_double" />
                        </div>
                        <div>
                        </div>
                        <div id="content">
                        </div>
                    </div>
                    <div>
                        <div>
                            <div>
                                <a href="javascript:addElement();">Add Destination</a> <a href="javascript:removeElement();">
                                    Remove</a>
                            </div>
                        </div>
                        <div>
                            Distance:
                            <div class="nameValueBox fl ">
                                <asp:TextBox ID="txtDistance" runat="server" Enabled="false" CssClass="txt3_double"></asp:TextBox>
                                <asp:Label ID="lblType" runat="server" Text=""></asp:Label>
                            </div>
                        </div>
                        <div>
                            <div>
                                <asp:Button ID="ibtnCalculate" runat="server" Text="Calculate" />
                                <asp:Button ID="ibtnDone" runat="server" Text="Insert" OnClientClick="returnToParent()" />
                            </div>
                        </div>
                        <div>
                            <div id="map_canvas" style="width: 430px; height: 450px; margin-right: 10px;">
                            </div>
                        </div>
                        <div>
                            <p id="results">
                            </p>
                        </div>
                    </div>
                    <div id="directionsPanel" style="text-align: right; vertical-align: top;">
                        <p>
                            <span id="total"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    <br />
</body>




Executing a utility using Command Line Mode asp.net

This is the code for executing commands using asp.net
 protected void btn_Click(object sender, EventArgs e)
    {

 ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
 processStartInfo.RedirectStandardInput = true;
 processStartInfo.RedirectStandardOutput = true;
 processStartInfo.UseShellExecute = false;
 processStartInfo.RedirectStandardError = true; 
 Process process = Process.Start(processStartInfo);
    if (process != null)
        {
       process.StandardInput.WriteLine("Cd\\");
       //renaming a file
       process.StandardInput.WriteLine("ren data.ofx abc1234.txt");

      //creating directory
      process.StandardInput.WriteLine("mkdir testDir");
   
    //executing utility
   process.StandardInput.WriteLine("bank2csv_pro.exe data.qbo output123.CSV");
     process.StandardInput.Close();
   // display the commands
     string outputString = process.StandardOutput.ReadToEnd();
     Response.Write(outputString);
    // display the errors coming in execution
     string error = process.StandardError.ReadToEnd();
      Response.Write(error);

         }
}