Tag Archives: ASP.NET

ASP.NET – show location using postal code on Google Map

<asp:Content ID="Content2" ContentPlaceHolderID="HeadPlaceHolder" Runat="Server">    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=YourKey" type="text/javascript"></script>    <script type="text/javascript">        var geocoder;        var map;        function initialize() {            map = new google.maps.Map(document.getElementById("googleMap"));            geocoder = new GClientGeocoder();        }       function codeAddress(address) {           if (geocoder) {               geocoder.getLatLng(                        address,                        function (point) {                            if (!point) {                                console.log(address + " not found");                            }                            else {                                map.setCenter(point, 15);                                var marker = new GMarker(point, { draggable: false });                                map.addOverlay(marker);                                GEvent.addListener(marker, "dragend", function () {                                    marker.openInfoWindowHtml("<h2>Event name here</h2>");                                });                                GEvent.addListener(marker, "click", function () {                                    marker.openInfoWindowHtml("<h2>Event name here</h2>");                                });                                GEvent.trigger(marker, "click");                            }                        }                    );           }      }       $(document).ready(function () {           initialize();           codeAddress("<%= EventLocation %>,Canada");       });    </script></asp:Content><asp:Content ID="Content1" ContentPlaceHolderID="InteriorContent" Runat="Server">    <h1>Additional Information</h1>    <br />    <p>Event Location:</p>    <div class="googleMapWrapper">        <div id="googleMap" style="width:530px; height:291px"></div>    </div></asp:Content>

ASP.NET: Get selected RadioButton’s value in specific GroupName

RadioButton selRB = radioButtonsContainer.Controls.OfTypeRadioButton>().FirstOrDefault(rb => rb.Checked);if(selRB != null){    int registrationTypeAmount = Convert.ToInt32(selRB.ToolTip);    string cbText = selRB.Text;}

where radioButtonsContainer is the container of the radiobuttons.

Update

If you want to ensure you get RadioButtons with the same group, you have 2 options:

  • Get them in separate containers
  • Add the group filter to the lamdba expression, so it looks like this:

    rb => rb.Checked && rb.GroupName == "YourGroup"

Update 2

Modified the code to make it a little more fail proof by ensuring it won’t fail if there’s no RadioButton selected.

Extending the asp:image control to set a maximum width

In this example, we are going to extend the control to allow a MaxWidth proprety, which will limit the size of the image to that value, if it is specified.
Create a new class called MaxWidthImage.cs in your App_Code folder and add the following code:
using System;using System.Web;using System.Web.UI.WebControls;namespace MyNameSpace{public class MaxWidthImage : Image{    private int _MaxWidth;    public int MaxWidth    {        get        {            return _MaxWidth;        }        set        {            _MaxWidth = value;        }    }    protected override void OnPreRender(EventArgs e)    {        if (string.IsNullOrEmpty(ImageUrl)) return;        using (System.Drawing.Image MyImage =            System.Drawing.Image.FromFile            (HttpContext.Current.Server.MapPath(ImageUrl)))        {            int CurrentWidth = MyImage.Width;            if (MaxWidth != 0 && CurrentWidth > MaxWidth)            {                CurrentWidth = MaxWidth;            }            Attributes.Add("width", CurrentWidth.ToString());        }    }}}

ASP.NET: Modify WebControl on Render

protected override void Render(HtmlTextWriter writer){    if (this.StopProcessing)    {        base.Render(writer);    }    else    {        System.Text.StringBuilder sb = new System.Text.StringBuilder();        Html32TextWriter mwriter = new Html32TextWriter(new System.IO.StringWriter(sb));        base.Render(mwriter);        string content = sb.ToString();        content = ParseLinks(content);        writer.Write(content);    }}

How to Round Numbers in JavaScript

Important: There are two different options provided below. The first option uses the popular Math.round method which is relatively simple. Unfortunately it is not always 100% accurate due to the way JavaScript handles numbers (see below for more information). However the errors are not serious or common so this technique is acceptable for most applications. The second option is an experimental attempt to get 100% accuracy—give it a try and tell us what you think.

Option 1: Math.round()

Add the following code to the head of your HTML page:

<script language="javascript" type="text/javascript"> function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places   var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);   document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) } </script>

Read more: mediacollege.com

 

ASP.NET Simple ADO class (2)

public class DbProducts{    SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString);    public List<product> GetProductDetails()    {        try        {            List<product> _lstProducts = new List<product>();            Product _Product = null;            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Select * From Products";            SqlDataReader _Reader = _cmd.ExecuteReader();            while (_Reader.Read())            {                _Product = new Product();                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);                _Product.Name = _Reader["Name"].ToString();                _Product.Unit = _Reader["Unit"].ToString();                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);                _lstProducts.Add(_Product);            }            return _lstProducts;        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string InsertProduct(Product _P)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Insert Into Products(Name,Unit,Qty)Values(@Name,@Unit,@Qty)";            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));            if (_cmd.ExecuteNonQuery() > 0)                return "Record Sucessfully Saved";            else                return "Record not Afftected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string UpdateProduct(Product _P)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Update Products set Name=@Name,Unit=@Unit,Qty=@Qty Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));            _cmd.Parameters.Add(new SqlParameter("@ProductID", _P.ProductID));            if (_cmd.ExecuteNonQuery() > 0)                return "Record Sucessfully Updated";            else                return "Record not Afftected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string DeleteProduct(int ProductID)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Delete From Products Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));            if (_cmd.ExecuteNonQuery() > 0)                return "Records Sucessfully Delete";            else                return "Records not Afftected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public Product GetProductById(int ProductID)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Select * From Products Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));            SqlDataReader _Reader = _cmd.ExecuteReader();            Product _Product = null;            while (_Reader.Read())            {                _Product = new Product();                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);                _Product.Name = _Reader["Name"].ToString();                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);                _Product.Unit = _Reader["Unit"].ToString();            }            return _Product;        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }}public class Product{    private int _ProductID = 0;    public int ProductID    {        get { return _ProductID; }        set { _ProductID = value; }    }    private string _Name = string.Empty;    public string Name    {        get { return _Name; }        set { _Name = value; }    }    private string _Unit = string.Empty;    public string Unit    {        get { return _Unit; }        set { _Unit = value; }    }    private decimal _Qty = 0;    public decimal Qty    {        get { return _Qty; }        set { _Qty = value; }    }}

via CodeProject

ASP.NET Simple ADO class (1)

public class PageManager{    public static PageItem GetPageByFriendlyUrl(string friendlyUrl)    {        PageItem page = null;        using (var cmd = new SqlCommand())        {            cmd.Connection = new SqlConnection("Server=(local);Database=MyWebsite;Trusted_Connection=True;");            cmd.CommandText = "select * from Page where FriendlyUrl = @FriendlyUrl";            cmd.Parameters.Add("@FriendlyUrl", System.Data.SqlDbType.NVarChar).Value = friendlyUrl;                            cmd.Connection.Open();            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))            {                if (reader.Read())                {                    page = new PageItem();                    page.PageId = (int) reader["PageId"];                    page.Title = (string) reader["Title"];                    page.ControllerName = (string) reader["ControllerName"];                    page.FriendlyUrl = (string) reader["FriendlyUrl"];                }            }            return page;        }    }    public class PageItem    {        public int Id { get; set; }        public string Title { get; set; }        public string Content { get; set; }        public string FriendlyUrl { get; set; }        public string ControllerName { get; set; }    }}

Deploying .NET 4.0 applications using IIS 7.x

Overview

This article is meant to give your a step by step overview of how to successfully deploy your .NET 4.0 Visual WebGui application to IIS 7.x.

Even though t is broken down into steps, the steps do not need to be carried out in the order they are presented here.

Mapping

To be able to deploy a .NET 4.0 ASP.NET (includes Visual WebGui) application you need a proper mapping.
IIS 7.5 comes with a built in mapping for the ASP.NET ‘*.aspx’ extension for .NET 4.0 for both 64bit and 32bit.
You need to make an exact copy of the 32bit or 64bit mapping to the Visual WebGui ‘*.wgx’ extension to be able to deploy a Visual WebGui application.

To create the new mapping, please:
   1. Select your Virtual Directory or Application from the tree on the left.
   2. Double-click on the “Handler Mappings” item on the “IIS” group on the right. You will now see all the current mappings.
   3. Click on the “Add Script Map…” link on the right panel. You will now see the ‘Add Script Map’ dialog.
   4. In the “Request path” field place this value: “*.wgx”.
   5. In the “Executable” field place this value:
       for 32bit: “C:WindowsMicrosoft.NETFrameworkv4.0.30319aspnet_isapi.dll”.
       for 64bit: “C:WindowsMicrosoft.NETFramework64v4.0.30319aspnet_isapi.dll”.
       – Set the version in bold to your actual .NET4.0 version.
   6. In the “Name” field type in a name that will be recognizable to you. For example: “WebGui-PageHandlerFactory-ISAPI-4.0”.
   7. Click on OK.

Change .NET Framework Version

The default .NET version of IIS 7.x is .NET 2.0.

To set up the .NET 4.0 framework to be the default, please:
   1. Select the root element in the tree on the left – it contains the name of the machine.
   2. Click on the “Change .NET Framework Version” link on the right panel. You will now see the “Change .NET Framework Version” dialog.
   3. Select the .NET 4.0 framework from the drop down list.
   4. Click on OK.

Application Pool

As you are using .NET 4.0, you need to use the “ASP.NET v4.0 Classic” application pool with your Virtual Directory or Application.

To set this application pool as the default for your Virtual Directory or Application, please:
   1. Select your Virtual Directory or Application from the tree on the left.
   2. Click on the “Basic Settings…” link on the right panel. You will now see the “Edit Application” dialog.
   3. Click on the “Select…” button. You will now see the “Select Application Pool” dialog.
   4. Select the “ASP.NET v4.0 Classic” application pool from the drop down list.
   5. Click on OK.
   6. Click on OK.

Enable 32-Bit Applications

This section is relevant when the deployment machine’s operating system is 64bit.

As the Visual WebGui assemblies are currently complied only to 32bit, you need to able 32bit application for your application pool.
To enable 32bit applications on your application pool, please:
   1. Select the “Application Pools” item from the tree on the left.
   2. Select the “ASP.NET v4.0 Classic” application pool item from the list in the center.
   3. Click on the “Advanced Settings…” link on the right panel. You will now see the “Advanced Settings” dialog.
   4. Change the value of the “Enable 32-Bit Applications” setting in the “(General)” group from “False” to “True”.
   5. Click on OK.

 

ASP.NET clear source code

ApplicationPath class

using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;public class ApplicationPath : System.IO.Stream{    private System.IO.Stream baseStream;    public ApplicationPath(System.IO.Stream responseStream)    {        if (responseStream == null)        {            throw new ArgumentNullException("responseStream");        }        this.baseStream = responseStream;    }    public override bool CanRead    {        get { throw new NotImplementedException(); }    }    public override bool CanSeek    {        get { throw new NotImplementedException(); }    }    public override bool CanWrite    {        get { throw new NotImplementedException(); }    }    public override void Flush()    {        //throw new NotImplementedException();    }    public override long Length    {        get { throw new NotImplementedException(); }    }    public override long Position    {        get        {            throw new NotImplementedException();        }        set        {            throw new NotImplementedException();        }    }    public override int Read(byte[] buffer, int offset, int count)    {        return this.baseStream.Read(buffer, offset, count);    }    public override long Seek(long offset, System.IO.SeekOrigin origin)    {        throw new NotImplementedException();    }    public override void SetLength(long value)    {        throw new NotImplementedException();    }    public override void Write(byte[] buffer, int offset, int count)    {        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);        HTML = HTML.Replace("src="/", "src="" + Classes.Common.ApplicationBaseUrl);        HTML = HTML.Replace("src='/", "src='" + Classes.Common.ApplicationBaseUrl);        HTML = HTML.Replace("href="/", "href="" + Classes.Common.ApplicationBaseUrl);        HTML = HTML.Replace("href='/", "href='" + Classes.Common.ApplicationBaseUrl);        HTML = HTML.Replace("action="/", "action="" + Classes.Common.ApplicationBaseUrl);        HTML = HTML.Replace("action='/", "action='" + Classes.Common.ApplicationBaseUrl);                buffer = System.Text.Encoding.UTF8.GetBytes(HTML);        this.baseStream.Write(buffer, 0, buffer.Length);    }}

Usage (ie from Master Page)

protected void Page_Load(object sender, EventArgs e){    //Response Filter to correct all application root paths to include proxy path    Response.Filter = new Classes.ApplicationPath(Response.Filter);}