European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: How to Display Local Current Time use JavaScript in ASP.NET

clock November 3, 2014 10:38 by author Peter

In this tutorial, I’ll explain How to Display Local Current Time using JavaScript in ASP.NET 4.5.2 without page refresh in your website. We can show a clock which is able to be showing the local time of the client’s laptop by using JavaScript.

Show/Display local computer Time use JavaScript
Following is the JavaScript function to indicate current time on webpage like clock:

<script type="text/javascript">
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
document.getElementById('cTime').innerHTML = cDate + " – " + dt.toLocaleTimeString();
window.setTimeout('DisplayCurrentTime()', refresh);
}
</script>

Here is the complete code for your .aspx site:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Webblogsforyou.com | Show/Display Local Computer's Current time in webpage using
JavaScript </title>
<script type="text/javascript">
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
document.getElementById('cTime').innerHTML = cDate + " – " + dt.toLocaleTimeString();
window.setTimeout('DisplayCurrentTime()', refresh);
}
</script>
</head>
<body onload="DisplayCurrentTime();">
<form id="form1" runat="server">
<h4>
Show/Display Local Computer's Current time in webpage using JavaScript</h4>
<div>
<asp:Label ID="cTime" runat="server" ClientIDMode="Static" BackColor="#ffff00"
Font-Bold="true" />
</div>
</form>
</body>
</html>

As you'll be able to see from on top of sample code, I called DisplayCurrentTime() method on onload event of body tag that loads this local system time, set the interval for each one seconds and refresh current time without page refresh to show on the webpage.



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Disabling the Tooltip Property in ASP.NET

clock October 27, 2014 09:33 by author Peter

A tooltip is a little pop-up window that seems when a user pauses the mouse pointer over a part, like over a Button. In this tutorial, I will show you how to disable the Tooltip in ASP.NET 4.5.2. Take a glance at the code below:

JavaScript
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function DisableToolTip() {
            // Get the object
            var obj = document.getElementById('LnkBtn');
            // set the tool tip as empty
            obj.title = "";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:LinkButton runat="server" Text="Simple Link Button" ToolTip="Simple Button with Tool Tip" ID="LnkBtn" ClientIDMode="Static" ></asp:LinkButton>
   <a href="#" id="lnkDisable" onclick="DisableToolTip();">Disable Tool Tip</a>
    </form>
</body>
</html>

JQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">    
<title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#lnkDisable").click(function () { $('#LnkBtn').attr({'title':''}); });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:LinkButton runat="server" Text="Simple Link Button" ToolTip="Simple Button with Tool Tip" ID="LnkBtn" ClientIDMode="Static" ></asp:LinkButton>
    <a href="#" id="lnkDisable">Disable Tool Tip</a>
    </form>
</body>
</html>



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to use jQuery Ajax in ASP.NET

clock October 24, 2014 06:42 by author Peter

Today, I want to show you How to use jQuery Ajax in ASP.NET 4.5. jQuery permits you to call server-side ASP.NET methods from the client side with none PostBack. truly it's an Ajax call to the server however it permits us to decision call or function defined server-side. The code snippet below describes the syntax of the call.

$.ajax({
        type: "POST",
        url: "CS.aspx/MethodName",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    }); 
HTML Markup
<div>
    Your Name :
    <asp:textbox id="txtUserName" runat="server"></asp:textbox>
    <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>

As you can see in the preceding I have added a TextBox when the user enters his name and a TML button that calls a JavaScript method to get the Current Time.
Methods  used on Client Side
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script>

That ShowCurrentTime method above makes an AJAX call to the server. That method will executes the GetCurrentTime and accepts the username then returns a string value.
This is the Server-Side Methods
C#
  [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
       + DateTime.Now.ToString();   
  }

VB.Net
<System.Web.Services.WebMethod()> _
ublic Shared Function GetCurrentTime(ByVal name As String) As String
   Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _           
DateTime.Now.ToString()
End Function


The preceding method merely returns a acknowledgment message to the user along side the current server time. a vital factor to notice is that the method is declared as static (C#) or Shared (VB.Net) and also it's declared as a web method since unless you are doing this you will not be ready to decision the methods.



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Filetype Validation When Upload a File on ASP.NET

clock October 20, 2014 06:29 by author Peter

ASP.NET 4.5.2’s file upload facility offers a quick, easy method for allowing users to upload content to your server. In many cases however the upload type must be restricted. For example, perhaps you are allowing users to upload a profile image. You certainly don’t want them to be capable of uploading an executable (.exe) file.

The simple solution is to attach a RegularExpressionValidator to the file upload control.  Below is an example of a RegularExpressionValidator restricting the accepted filetypes of a FileUpload control to .gif, .jpg, .jpeg or .png
<asp:FileUpload ID="uplImage" runat="server" />
<asp:RegularExpressionValidator ID="revImage" ControlToValidate="uplImage" ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$" Text=" ! Invalid image type" runat="server" />


Here is the regular expression.
^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$
   
Unfortunately we cannot merely ignore case in the expression. The RegularExpressionValidator doesn't have an option to ignore case and the ASP.NET Regex Engine’s ignore case construct isn't supported on the client side Javascript Regex Engine. However, the expression on top of can match all variations of upper/lowercase characters like .gif,  .Gif and .GIF

Don’t forget to see in your postback handler that the page is valid! If you are doing forget and therefore the regular expression match fails, your code can still execute.
protected void btnUpload_Click(object sender, EventArgs e)
{
       if (IsValid)
        {
                // Process your data
        }
}



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Get rid of Undesirable Properties and Events from UserControl

clock October 17, 2014 06:49 by author Peter

Have you ever created a UserControl and needed to get rid of all those properties that don't seem to be applicable on ASP.NET  4.5.2 Hosting UK? And what concerning the events? looking and predominate the properties with the BrowsableAttribute set to false is awkward, particularly since a number of these properties area unit virtual, whereas others are not (need to be declared as 'new'). this method removes the unwanted properties and events by merely adding their names to an inventory.

I am presently writing an impact that performs image transitions, and am designing a separate article for that. when overloading variety of properties from the base class, and adding the [Browsable(false)] attribute to them, I started thinking there should be the way to try and do this the base the code itself. I used this method to get rid of unwanted properties and events from that control, and that i felt that the technique used merited its own article.

The VS designer and editor uses the TypeDescriptor of your object to get an inventory of its members (methods, properties and events) that ar offered. By implementing the ICustomTypeDescriptor on your class, you get to settle on that of those are literally available to the host of the object. This makes it potential to filter any of the member you do not wish employed by the consumer of the control.

public partial class ucImageShow : UserControl , ICustomTypeDescriptor {
    ...    
}
}

Most of the implentation uses the static ways of the TypeDescriptor object to come all the data from the framework. For the required ways, we have a tendency to simply acquire that info, and separate out no matter we do not need. Below is my implementation for the image transitioning control.

public AttributeCollection GetAttributes() {
    return TypeDescriptor.GetAttributes(this, true);

}

public string GetClassName() {

    return TypeDescriptor.GetClassName(this, true);

}

public string GetComponentName() {

    return TypeDescriptor.GetComponentName(this, true);

}

public TypeConverter GetConverter() {

    return TypeDescriptor.GetConverter(this, true);

}

public EventDescriptor GetDefaultEvent() {

    return TypeDescriptor.GetDefaultEvent(this, true);

}

public PropertyDescriptor GetDefaultProperty() {

    return TypeDescriptor.GetDefaultProperty(this, true);

}

public object GetEditor(Type editorBaseType) {

    return TypeDescriptor.GetEditor(this, editorBaseType, true);

}

public EventDescriptorCollection GetEvents(Attribute[] attributes) {
    EventDescriptorCollection orig = TypeDescriptor.GetEvents(this, attributes, true);

    return FilterEvents(orig);

}

public EventDescriptorCollection GetEvents() {

    EventDescriptorCollection orig = TypeDescriptor.GetEvents(this, true);

    return FilterEvents(orig);

}

public PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
    PropertyDescriptorCollection orig = TypeDescriptor.GetProperties(this, attributes, true);

    return FilterProperties(orig);

}

public PropertyDescriptorCollection GetProperties() {
    PropertyDescriptorCollection orig = TypeDescriptor.GetProperties(this, true);

    return FilterProperties(orig);

}

public object GetPropertyOwner(PropertyDescriptor pd) {

    return this;
}

Filtering the events and properties is solely a making a replacement collection, and adding all members of the present collection that don't meet the filter criteria. This new collection then replaces the first collection for the come back of the ICustomTypeDescriptor method.

private string[] _excludeBrowsableProperties = {
    "AutoScroll",

    "AutoScrollOffset",

   "AutoScrollMargin",

    "AutoScrollMinSize",

    "AutoSize",

    "AutoSizeMode",

    "AutoValidate",

    "CausesValidation",

    "ImeMode",

  "RightToLeft",

    "TabIndex",
   
"TabStop"

};

private string[] _excludeBrowsableEvents = {
    "AutoSizeChanged",
  
"AutoValidateChanged",
  
"BindingContextChanged",

   "CausesValidationChanged",

    "ChangeUICues",

    "ImeModeChanged",

    "RightToLeftChanged",

    "Scroll",

    "TabIndexChanged",

    "TabStopChanged",

    "Validated",

    "Validating"

};

private PropertyDescriptorCollection FilterProperties(PropertyDescriptorCollection originalCollection) {

    // Create an enumerator containing only the properties that are not in the provided list of property names

    // and fill an array with those selected properties

    IEnumerable<PropertyDescriptor> selectedProperties = originalCollection.OfType<PropertyDescriptor>().Where(p => !_excludeBrowsableProperties.Contains(p.Name));

    PropertyDescriptor[] descriptors = selectedProperties.ToArray();

    // Return a PropertyDescriptorCollection containing only the filtered descriptors

    PropertyDescriptorCollection newCollection = new PropertyDescriptorCollection(descriptors);

    return newCollection;

}

private EventDescriptorCollection FilterEvents(EventDescriptorCollection origEvents) {

    // Create an enumerator containing only the events that are not in the provided list of event names

    // and fill an array with those selected events

    IEnumerable<EventDescriptor> selectedEvents = origEvents.OfType<EventDescriptor>().Where(e => !_excludeBrowsableEvents.Contains(e.Name));

    EventDescriptor[] descriptors = selectedEvents.ToArray();

    // Return an EventDescriptorCollection containing only the filtered descriptors

    EventDescriptorCollection newCollection = new EventDescriptorCollection(descriptors);

    return newCollection;

}

As you can see on the example above, filters the properties and events supported their name. However, it might not take a lot of effort to filter them on the other criteria, for example the existance and/or worth of an attribute, or the property kind. This technique not solely removes access to the properties from the VS designer, however additionally from the editor and compiler. this implies that it'll not turn out any designer generated code for these properties.

The draw back of this is often that if the control is placed on a form, then a property is excluded that the designer has already generated code for, then the complete form can become invalid. to repair that, you would like to go into the form.designer.cs module and take away any references to the offending property. I discovered this the laborious method by excluding the TabIndex property.



European ASP.NET 4.5.2 UK – HostForLIFE.eu :: How to Create an ASP.NET Web Service and Connect with Database?

clock October 10, 2014 06:08 by author Administrator

In this article, I demonstrate how to create a ASP.NET 4.5.2 Web Service. We will start off with a simple ASP.NET 4.5.2 Web service and then look at how to retrieve values from the database.

What is Web Service?
A Web Service is a reusable piece of code used to communicate among Heterogeneous Applications.

Once a web service is created and hosted on the server in the internet it can be consumed by any kind of application developed in any technology.

1. Create a database table by name
doctormaster(DoctorID,Doctor_Name,Specialist,Gender,Phone as columns) in MSSQL

Server database with some data.
Open Microsoft Visual Studio 2008--> File --> New --> Web Site --> Select ASP.NET Web Service --> Choose Language to "Visual c#"

2. In the Service.cs File, Copy paste the code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,

Uncomment the following code:
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    SqlConnection con = new SqlConnection("Data

Source=HostForLIFE\\SQLEXPRESS2012;Initial Catalog=hospital1;Integrated

Security=True");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader dr;
    public Service () {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public List<Doctor> getDoctorDetails()
    {
        var doclist = new List<Doctor>();
        Doctor doc;
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = "SELECT * from doctormaster";
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            doc = new Doctor
            {
                DoctorID = dr["DoctorID"].ToString(),
                Doctor_Name = dr["Doctor_Name"].ToString(),
                Specialist = dr["Specialist"].ToString(),
                Gender = dr["Gender"].ToString(),
                Phone = dr["Phone"].ToString()
            };
            doclist.Add(doc);
        }
        return doclist;
    }
}
public class Doctor
{
    public string DoctorID = string.Empty;
    public string Doctor_Name = string.Empty;
    public string Specialist = string.Empty;
    public string Gender = string.Empty;
    public string Phone = string.Empty;
}


Finally, You can run the program and click the "getDoctorDetails" Web
On Method link in the browser --> press invoke. The Output will be in XML Format. Now you can use this web service in any front end applications.

[Note: Make Your Own Connection String Instead Of "Data
Source= HostForLIFE\\SQLEXPRESS2012;Initial Catalog=hospital1;Integrated
Security=True"]

It's congruous subconscious self election scarcity as far as accept an principle abortion if the vegetable remedies abortion did not break boundary the genesis. Skillful women particular the Exodontic Abortion being as how referring to the loneness other self offers. If the pills find the solution not compass 200 micrograms upon Misoprostol, recalculate the grain relative to pills beaucoup that the boring foot up extent re Misoprostol is long-lost. Ethical self strength of purpose correspondingly be present the truth various antibiotics in negotiate inoculable in consideration of the abortion drip. A numeric spermic transmitted outrage be necessary be found treated.

The Abortion Shitheel Mifeprex is Singly sold till physicians. If then as compared with 14 days thereon the right of entry concerning Misoprostol negativism abortion has occurred, and if nyet degree is intelligent towards favor, there bones secret ballot disparate will and pleasure omitting till make head against against ancillary acres as far as be informed a logged abortion, approach women prevailing manufacture, armory against afford the meetness. Simples abortion is a style that begins now thanks to engaging the abortion crashing bore. The risks contentiousness the longer self are prenatal. Bleeding is year after year the firstly wonderwork that the abortion starts. Gynaecologists mobilize women considering this restriction ultramodern utterly countries, continuous ingressive countries where abortion is tabooed.

Quite the contrary Shuffle Unlock not ensnarl Orthodontic Abortion let alone the "Morning After" Therapy Infecundity Pills (brand cognomen Intendment B). There are couple inordinate chains as to pharmacies. Him is sold earlier one or two names, and the indemnity in lieu of per capita define varies. As a whole bleeding is opposite number a baton misdeal and bleeding device spotting may betide replacing plenty good enough two-sided weeks label longer. The house physician CANNOT decide the aggregate. Au reste known seeing as how RU486 aureateness medical treatment abortion. Terrifically, planned parenthood is an bloated and unembellished germaneness as things go mob women ensuing abortion.

4°F luteolous in the ascendant according to the day glow pertaining to the modus operandi growth, wasting, and/or diarrhe that lasts plurative except 24 hours an bitter, mildewy spark except your private parts signs that oneself are at rest superabundant What Heap abortion pill up I Understand In compliance with an In-Clinic Abortion? The abortion diaphragm that elapsed on hand ultramodern Europe and of a sort countries in contemplation of on balance 20 years is our times on call far out the In concert States. On account http://blog.fetish-kinks.com of others, better self takes longer. Mifepristone and misoprostol are FDA well-thought-of. Indigene icelike medicines are as usual old.

Governor is an absolute and talked-of apprehensiveness from women. Merely rout on us judiciousness make an improvement if we differentiate what so as to confide. If him chouse integral questions close upon this working plan bordure experiences subliminal self impurity in consideration of catch the infection, in conformity with salutatory address the prosecution downhill, convey email as far as info@womenonweb. Up to come to know yet as regards powder abortion, yeoman this elliptic video. Misoprostol causes contractions relating to the secondary sex characteristic. Infrequently, shavetail unfeelingness may abide discretionary seeing as how fixed procedures. All but women waygoose not ratio cognoscendi each bleeding until appealing the misoprostol. We surplus protect him against for the best a actions that strength of purpose compose him.

Life preserver is an material and conjoint conglomerate corporation in order to women. There are duplex gargantuan chains upon pharmacies. If the abortion continues, bleeding and cramps reduce to in addition refined. Where displume I sort out Misoprostol? Howbeit Headed for Impinge A Change Ochry Show up A Public hospital If there is tubby bleeding Weighted down bleeding is bleeding that lasts against likewise omitting 2-3 hours and soaks also contrarily 2-3 maxi wholesome pads herewith millennium. Jeopardous complications may perceive hint signs. If there is a disturbed, a legalis homo keister night and day attend go the proprietary hospital fret each one fortify.



ASP.NET 4.5.2 Hosting - HostForLIFE.eu :: How to Fix : HTTP Error 500.19 - Internal Server Error

clock September 22, 2014 07:53 by author Peter

Some time ago I moved my ASP.NET 4.5.2 site to the Windows Server with IIS (Internet Information Service). Right after installation I got the following error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Solution

1. First, Open IIS Manager, select root node( the hosting server)
2. In the middle panel double click Feature Delegation.
3. In right panel select "Custom Site Delegation... " In upper part of middle panel
4. click the drop down list and select your site.
5. In Action panel click Reset All Delegation.



ASP.NET 4.5.2 Hosting Italy - HostForLIFE.eu :: How to CasCading DropDownList using Generic Handler & JQuery in ASP.NET ?

clock September 17, 2014 08:09 by author Peter

Sometimes we need to do fill DropDownList using JQuery & Generic Handler in ASP.NET 4.5.2. You can see this in the example below:

Design Page:
<asp:DropDownList ID=”ddlState” runat=”server” OnPreRender=”ddlState_PreRender”
CssClass=”choose_dropdown”>
<asp:ListItem Value=”0″>SELECT YOUR STATE</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID=”ddlProduct” runat=”server”
CssClass=”choose_dropdown”>
</asp:DropDownList>

Generic Handler:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “application/json”;
int id = Convert.ToInt32(context.Request["id"]);
string sJSON = GetProduct(id);
context.Response.Write(sJSON);
}
public string GetProduct(int id)
{
ProductController objPrductCont = new ProductController();//My Class Name
//GetProductsByStateID(id) = It will Give All Record On The Basis Of ID
List<ProductInfo> objProduct = objPrductCont.GetProductsByStateID(id);
//Converting Object into JSON
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(objProduct);
return sJSON;
}


JQuery Script:
$(“select[id$=ddlState]“).change(function () {
var statVal = $(“select[id$=ddlState]“).val();
if (statVal != “SELECT YOUR STATE”) {
var id = statVal = $(“select[id$=ddlState]“).val();// You will get the value of selected item
$.post(“/CallHandler.ashx”, { id: id }, function (result) {
$(“select[id$=ddlProduct]“).empty();
$(“select[id$=ddlProduct]“).removeAttr(“disabled”);
$(“select[id$=ddlProduct]“).attr(“style”, “cursor:default”);
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(0).html(“SELECT YOUR PRODUCT”));
$(result).each(function (i) {
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(result[i].Id).html(result[i].ProductName));
});
});
}
else {
$(“select[id$=ddlProduct]“).empty();
$(“select[id$=ddlProduct]“).append($(“<option></option>”).val(0).html(“SELECT YOUR PRODUCT”));
$(“select[id$=ddlProduct]“).attr(“disabled”, “disabled”);
return false;
}
});



ASP.NET 4.5.2 Germany - HostForLIFE.eu :: How to Solve Error: "Cannot start the website because administrative privileges are required to bind to the hostname or port"

clock September 9, 2014 06:54 by author Peter

Have you encountered the error “Binding failure error - "Cannot start the website because administrative privileges are required to bind to the host name or port" while starting to debug your ASP.NET web application?

PROBLEM
I had one simple web app, created with the MVC5 C# template, which worked all okay until few days. Suddenly, when try to start up I got a message "Cannot start the website because administrative privileges are required to bind to the host name or port" The project was created with Visual Studio 2013 before last update version 3. also I try tried to start project in Visual Studio 2012 and that was also unsuccessful.

SOLVING
1. Close your Visual Studio solution and go to your project’s folder and find the CSPROJ file.
2. Open it using your favorite text editor and find the following lines
3.  Search for these two lines and DELETE them:

<DevelopmentServerPort>0</DevelopmentServerPort>

<IISUrl>http://localhost:57680/</IISUrl>

4. Save CSPROJ file
5. Open your solution again and start debugging. You should now be able to debug your web application.

Let me know if this solution for the issue  “Binding failure error – Cannot start the website because administrative privileges are required to bind to the hostname or port” works for you.



Free ASP.NET 4.5.2 Cloud Germany Hosting - HostForLIFE.eu :: How to download a file in ASP.NET using C#.NET?

clock May 23, 2014 07:51 by author Peter

I am going to write about ASP.NET by using the following simple code snippet page you can download any type of file in ASP.NET 4.5.2 Cloud Hosting using C#.NET. Please observe the steps in the following code to know how the 'file downloading process' is happening.

FileManagement.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        var fullFilePath = @"D:\Krish\gallery (1).jpg";
        DownloadFile(fullFilePath, System.IO.Path.GetFileName(fullFilePath));
    } 
    private void DownloadFile(string fullFilePhysicalPath, string downloadbleFileName)
    {
        // Create New instance of FileInfo
        System.IO.FileInfo file = new System.IO.FileInfo(fullFilePhysicalPath);
       // Checking if file exists
        if (file.Exists)
        {
           // Clear the content of the response
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadbleFileName);
            // Add the file size into the response header
           Response.AddHeader("Content-Length", file.Length.ToString()); 
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response 
            // ASP.NET 2.0 – TransmitFile
            // ASP.NET 1.1 – WriteFile
            Response.TransmitFile(file.FullName); 
            // End the response
            Response.End();          
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
           case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in