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

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.



European ASP.NET 4.5 Cloud Hosting - Germany :: Claims-Based Security in ASP.NET 4.5

clock June 5, 2014 10:42 by author Scott

When you talk about authentication in ASP.NET you will most undoubtedly hear the mention of the MembershipProvider. I'm here to tell you not to go down that road. That road will only lead to tears and suffering. This post will help you understand and implement your ASP.NET authentication built on top of FormsAuthentication. I hope you take away that building this stuff is not hard as long as you don't try to over think it.

Before I show you how to implement a kick-butt authentication system, I'll show you the simplest solution you could build.

FormsAuthentication.SetAuthCookie(user.Id, createPersistentCookie: true);

Congratulations you are now officially signed into your ASP.NET application using forms authentication. Notice I don't have any SQL migrations, crazy classes, or any other crap you didn't ask for.

 

The code above writes a cookie to the response of the current HttpContext. On the user's next request that cookie will be passed back to the server and used to check whether they are authenticated or not.

Password Hasher

Hashing passwords is really easy with .NET. The trick is to generate a salt with every password. The idea of the salt is not to be a secret, but to be unique every time. This makes it difficult for hackers to process all your passwords in the case your system is compromised. This is my standard password hasher:

public static class PasswordHasher {
    private const int SaltSize = 64;

    public static Passphrase Hash(string password) {
        if (password == null) throw new ArgumentNullException("password");

        byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
        byte[] saltBytes = CreateRandomSalt();
        string hashedPassword = ComputeHash(passwordBytes, saltBytes);

        return new Passphrase {
            Hash = hashedPassword,
            // Convert salt from byte[] to string
            Salt = Convert.ToBase64String(saltBytes)
        };
    }

    public static bool Equals(string password, string salt, string hash) {
        return String.CompareOrdinal(hash, Hash(password, salt)) == 0;
    }

    public static string GenerateRandomSalt(int size = SaltSize) {
        return Convert.ToBase64String(CreateRandomSalt(size));
    }

    private static string ComputeHash(byte[] password, byte[] salt) {
        var passwordAndSalt = new byte[salt.Length + password.Length];

        Buffer.BlockCopy(salt, 0, passwordAndSalt, 0, salt.Length);
        Buffer.BlockCopy(password, 0, passwordAndSalt, salt.Length, password.Length);
        byte[] computedHash;
        using (HashAlgorithm algorithm = new SHA256Managed()) {
            computedHash = algorithm.ComputeHash(passwordAndSalt);
        }
        return Convert.ToBase64String(computedHash);
    }

    private static string Hash(string password, string salt) {
        return ComputeHash(Encoding.Unicode.GetBytes(password), Convert.FromBase64String(salt));
    }

    private static byte[] CreateRandomSalt(int size = SaltSize) {
        if (size <= 0)
            throw new ArgumentException("size must be greater than zero.");

        var saltBytes = new Byte[size];
        using (var rng = new RNGCryptoServiceProvider()) {
            rng.GetBytes(saltBytes);
        }
        return saltBytes;
    }
}

public class Passphrase {
    public string Hash { get; set; }
    public string Salt { get; set; }
}

Principal and Identity

The IPrincipal and IIdentity interfaces are crucial to authentication in .NET. If you have ever used HttpContext, WebForms, or ASP.NET MVC then you are using derivations of these interfaces. It usually comes in the guise of a User property. You don't have to implement these classes, you can always use the GenericPrincipal and GenericIdentity. I like to implement them myself, because it allows me to pass a bit more useful data around in the cookie (remember cookies have size limits).

Let's first look at the IPrinicipal implementation:

public class MuchoPrincipal : IPrincipal {
    private readonly MuchoIdentity _identity;

    public MuchoPrincipal(MuchoIdentity identity) {
        _identity = identity;
    }

    #region IPrincipal Members

    public bool IsInRole(string role) {
        return
            _identity.Roles.Any(
                current => string.Compare(current, role, StringComparison.InvariantCultureIgnoreCase) == 0);
    }

    public IIdentity Identity {
        get { return _identity; }
    }

    public MuchoIdentity Information {
        get { return _identity; }
    }

    public bool IsUser {
        get { return !IsGuest; }
    }

    public bool IsGuest {
        get { return IsInRole("guest"); }
    }

    #endregion
}

Next up is the IIdentity, just take a look:

public class MuchoIdentity : IIdentity {
    public MuchoIdentity(FormsAuthenticationTicket ticket) {
        if (ticket == null) {
            Name = "Guest";
            Roles = new List<string> { "guest" };
            return;
        }

        var data = JsonConvert.DeserializeObject<MuchoCookie>(ticket.UserData);

        if (data == null) {
            AsGuest();
            return;
        }

        Id = data.Id;
        FirstName = data.FirstName;
        LastName = data.LastName;
        Name = string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName)
                   ? data.Email
                   : "{0} {1}".With(FirstName, LastName);
        Email = data.Email;
        Roles = data.Roles ?? new List<string> { "user" };
        RememberMe = data.RememberMe;

        try {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById(data.TimeZone);
        } catch (Exception) {
            TimeZone = TimeZoneInfo.Utc;
        }
    }

    public MuchoIdentity(User user) {
        if (user == null) {
            AsGuest();
            return;
        }

        Id = user.Id;
        Email = user.Email;
        FirstName = user.FirstName;
        LastName = user.LastName;
        Name = string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName)
                   ? user.Email
                   : "{0} {1}".With(FirstName, LastName);

        try {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById(user.TimeZone);
        } catch (Exception) {
            TimeZone = TimeZoneInfo.Utc;
        }
        Roles = new List<string> { user.Role ?? "user" };
    }

    private void AsGuest() {
        Name = "Guest";
        Roles = new List<string> { "guest" };
    }

    public int Id { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public TimeZoneInfo TimeZone { get; set; }
    public bool RememberMe { get; set; }
    public IList<string> Roles { get; set; }

    #region IIdentity Members

    public string AuthenticationType {
        get { return "MuchoForms"; }
    }

    public bool IsAuthenticated {
        get { return !( Id == 0 || string.IsNullOrWhiteSpace(Email)); }
    }

    public string Name { get; protected set;

    #endregion
}

C is for Cookie

The cookie object is really just a data transfer object. Nothing really mind blowing here. I usually create a structure to store my useful information. Again, keep in mind the size limitations of a cookie which is about 4kb (4096 bytes).

public class MuchoCookie {
    public MuchoCookie() {
        Roles = new List<string>();
    }

    public int Id { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TimeZone { get; set; }
    public List<string> Roles { get; set; }
    public bool RememberMe { get; set; }
}

FormsAuthenticationService

FormsAuthentication is built right into ASP.NET, but I like to write a littler wrapper around it so I can test and inject it into other classes. Also I create the cookie from the previous section when a user successfully signs in.

public class FormsAuthenticationService : IFormsAuthenticationService {
    private readonly HttpContextBase _httpContext;

    public FormsAuthenticationService(HttpContextBase httpContext) {
        _httpContext = httpContext;
    }

    #region IFormsAuthenticationService Members

    public void SignIn(User user, bool createPersistentCookie) {
        if (user == null)
            throw new ArgumentNullException("user");

        var cookie = new MuchoCookie {
            Id = user.Id,
            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,
            RememberMe = createPersistentCookie,
            TimeZone = user.TimeZone,
            Roles = new List<string> { user.Role ?? "user" }
        };

        string userData = JsonConvert.SerializeObject(cookie);
        var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
                                                   DateTime.Now.Add(FormsAuthentication.Timeout),
                                                   createPersistentCookie, userData);
        string encTicket = FormsAuthentication.Encrypt(ticket);
        var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };

        _httpContext.Response.Cookies.Add(httpCookie);
    }

    public void SignOut() {
        // Not worth covering, has been tested by Microsoft
        FormsAuthentication.SignOut();
    }

    #endregion
}

Notice the SignIn method creates the cookie and just writes it to the response using FormsAuthentication. We are leveraging what ASP.NET gives us. There is no reason to reinvent the wheel when it comes to passing secure cookies to the client.

PrincipalService

The principal service helps us get the information out of a cookie and rehydrate our IPrinipal and our IIdentity to our custom implementations. The other added benefit is we can actually set the User property to a Guest principal with extra information if we need it.

public class MuchoSupportPrincipalService : IPrincipalService {
    private readonly HttpContextBase _context;

    public MuchoSupportPrincipalService(HttpContextBase context) {
        _context = context;
    }

    #region IPrincipalService Members

    public IPrincipal GetCurrent() {
        IPrincipal user = _context.User;
        // if they are already signed in, and conversion has happened
        if (user != null && user is MuchoPrincipal)
            return user;

        // if they are signed in, but conversion has still not happened
        if (user != null && user.Identity.IsAuthenticated && user.Identity is FormsIdentity) {
            var id = (FormsIdentity)_context.User.Identity;

            var ticket = id.Ticket;
            if (FormsAuthentication.SlidingExpiration) 
                ticket = FormsAuthentication.RenewTicketIfOld(ticket);

            var fid = new MuchoIdentity(ticket);
            return new MuchoPrincipal(fid);
        }

        // not sure what's happening, let's just default here to a Guest
        return new MuchoPrincipal(new MuchoIdentity((FormsAuthenticationTicket)null));
    }

    #endregion
}

The trick here is just to check the current context for the cookie already being passed in with our request. You need to call this code from your Global.asax as such (note I am using ASP.NET MVC and the dependency resolver built into it).

protected void Application_AuthenticateRequest(object sender, EventArgs e) {
    var principalService = DependencyResolver.Current.GetService<IPrincipalService>();
    var context = DependencyResolver.Current.GetService<HttpContextBase>();
    // Set the HttpContext's User to our IPrincipal
    context.User = principalService.GetCurrent();
}

Usage in Your Code

This is what my ASP.NET MVC controller looks like:

[RequireScheme(Scheme.Https)]
public class AuthenticationController : ApplicationController {
public ActionResult Login(string returnUrl) {

if (User.Identity.IsAuthenticated) {
if (!string.IsNullOrWhiteSpace(returnUrl))
return Redirect(returnUrl);

return RedirectToAction("show", "dashboard");
}

var model = new LoginModel {
ReturnUrl = returnUrl
};

return View(model);
}

[HttpPost]
public ActionResult Login(LoginModel input) {
// validation does password hash check
// you could do it more explicitly
if (ModelState.IsValid) {
Logger.Info("successful!", input.Username);
var user = Db.Users
.FirstOrDefault(u => u.Email == input.Username);
// set cookie
Forms.SignIn(user, input.RememberMe);
return input.HasReturnUrl(Url)
? Redirect(input.ReturnUrl)
: (ActionResult) RedirectToAction("show", "dashboard");
}

Flash.Error("Please try again");

return View("login", input);
}

public ActionResult Logout() {
Forms.SignOut();
return RedirectToAction("login");
}
}

Conclusion

The parts of an authentication system are all infrastructural. It is all smooth sailing once you get over the hump of setting it up. Once the infrastructure is set up you can work on creating your own tables for Users, Profiles, or any other domain model that makes sense. All access to user's is up to you, so feel free to use any data access provider you like: SQL Server, RavenDB, MongoDB, etc. Additionally, the cookie is now yours; feel free to add or remove data from it as you see fit, but always remember the 4kb size limit.



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>



HostForLIFE.eu offers €1.29/month Affordable and High Performance Windows & ASP.NET Shared Hosting Plan

clock May 20, 2014 11:50 by author Peter

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched the new Windows & ASP.NET Shared Hosting Plan offered from as low as €1.29/month only. This LITE Windows & ASP.NET Hosting packages combine generous or 1 website, 1 GB disk space, 10 GB bandwidth, Support UTF-8 Domains, Dedicated Pool, etc. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu  is confident that their new LITE shared hosting plans will surely appeal to the personal across the world, besides the website owners and companies owning websites. The new web hosting plans will meet the requirement of high performance web hosting where one can easily update the content of a website on a regular basis. This plan is designed more for the web hobbiest needing affordable, high availability, hosting and easy backend management of windows and ASP.NET with powerful Plesk control panel.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don’t always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

For additional information about LITE Shared Hosting Plan offered by HostForLIFE.eu, please visit http://hostforlife.eu

About HostForLIFE.eu:

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

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, They have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



European ASP.NET 4.5 Hosting - HostForLIFE.eu :: Send Bulk Email Using ASP.NET 4.5

clock January 22, 2014 05:58 by author Scott

This article explains how to send bulk email using ASP.Net 4.5. You can use:

  • ASP .NET web page
  • Grid View
  • HTML Email Templates
  • Gmail SMTP Mail Server

Create a new project using "File" -> "New" -> "Project..." then select web "ASP .Net Web Forms Application". Name it " Bulk Email".

Now in the Design page “Default.aspx” design the web page as in the following screen:

In the Design Source (Default.aspx) write the code as: 

Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
 Inherits="BulkEmail._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
   
 <section class="featured">
       
 <div class="content-wrapper">
           
 <hgroup class="title">              
               
 <h2>Send Bulk email using asp.net</h2>
           
 </hgroup>
           
 <p>
                To learn more about ASP.NET
           
 </p>
       
 </div>
   
 </section>
</asp:Content>
<asp:Content
 runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
      
 <h3>We suggest the following:</h3>
   
 <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
   
 <p>
      
 <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1"
 runat="server" Font-Bold="true" ForeColor="Green" Text="Total Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size
="Larger"></asp:Label> </p>
   
 
       
 <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
       
 <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>

   
 </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:

Web.config

<connectionStrings>     
   
<add
 name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      

</connectionStrings>

In the code behind file (Default.aspx.cs) write the code as: 

using
 System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
   
 
public partial class _Default : Page
    {
        #region MySqlConnection Connection
       
 
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

       
 protected void Page_Load(object sender, EventArgs e)
        {
           
 
Try
            {
               
 if (!Page.IsPostBack)
                {

                }
            }
           
 
catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
       
 
/// <summary>
       
 /// This function is used for show message.
       
 /// </summary>
       
 /// <param name="msg"></param>
       
 void ShowMessage(string msg)
        {
           
 ClientScript.RegisterStartupScript(Page.GetType(), 
"validation", "<script
language='javascript'>alert('"
 + msg + "');</script>");
        }      
 
        #endregion
        #region Bind Data
       
 
/// <summary>
       
 /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter

       
 /// </summary>
       
 /// <param name="sender"></param>
       
 /// <param name="e"></param>
       
 protected void btnBind_Click(object sender, EventArgs e)
        {
           
 
Try
            {
                conn.Open();
               
 MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers"
, conn);
               
 MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
               
 DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
           
 catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
           
 
Finally
            {
                conn.Close();

            }
            btnBind.Visible =
 false;
        }
        #endregion
        #region Bulk email,GridView,gmail
       
 
/// <summary>
       
 /// this code used to Send Bulk email 
       
 /// </summary>
       
 /// <param name="sender"></param>
        
/// <param name="e"></param>
       
 protected void btnSend_Click(object sender, EventArgs e)
        {
           
 
Try
            {
                lbltotalcount.Text =
 string.Empty;
               
 foreach (GridViewRow grow in grvCustomers.Rows)
               {
                   
 
string strCustomerID = grow.Cells[0].Text.Trim();
                   
 
string strContactName = grow.Cells[1].Text.Trim();
                   
 
string strAddress = grow.Cells[2].Text.Trim();
                   
 
string strPhone = grow.Cells[3].Text.Trim();
                   
 
string strEmail = grow.Cells[4].Text.Trim();                

                   
 
string filename = Server.MapPath("~/Event.html");
                   
 string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace(
"##NAME##", strContactName);
                   
 string to = strEmail;
                   
 
string from = "[email protected]";
                   
 MailMessage message = new MailMessage(from, to);
                    message.Subject =
 "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding =
 Encoding.UTF8;
                    message.IsBodyHtml =
 true;
                   
 SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.
NetworkCredential basicCredential = new
System.Net.
NetworkCredential("[email protected]", "Password");
                    client.EnableSsl =
 true;
                   
 client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                   
 try
                    {
                        client.Send(message);
                        ShowMessage(
"Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                   
 catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
           
 
catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
           
 
Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}

See the following screen for the Default.aspx: Total Customers data bind.

Now, see the following screen for the Default.aspx: send email waiting.

Now, show in the Message box “Email sending successfully”.

Now "Email Account Open" - > "View Email". You’ll see the messages on your inbox. Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server. I hope this article is useful. 



European ASP.NET 4.5 Hosting - Amsterdam :: Model Binding with Dropdown List in ASP.NET 4.5

clock December 20, 2013 05:32 by author Administrator

ASP.NET 4.5 Preview introduces new model binding for  ASP.NET web forms. The concept of model binding was first introduced with ASP.NET MVC and now it has incorporated with ASP.NET Web Forms. You can easily perform any CURD operation with any sort of data controls using any data access technology like Entity Framework,  ADO.NET, LINQ to SQL Etc.  In this post I am going talk about how you can bind the data with ASP.NET DropdownList using new Model Binding features.

Let’s say we have a speaker database and we wants to bind the name of the speakers with the DropDownList.  First placed an ASP.NET Dropdown control with the page  and set the “DataTextField” and “DataValueField” properties.

We can set the  ddlName.DataSource to specifying the data source from the code behind and bind the data with dropdpwnlist, but  in this case from the code behind to providing the data source.

Now, instead of specifying the DataSource, we will be setting the Dropdownlists SelectMethod property to point a method GetSpeakerNames() within the code-behind file.

Select method is expected to return us result of type IQueryable<TYPE>. Here is GetSpeakerName() method is defined as follows.

So, Instead of specifying the data source we are specifying the SelectMethod, which return the IQueryable type of Speaker object. Run the application, you will find the names binded with dropdown list. Hope this helps !



European ASP.NET 4.5 Hosting - Amsterdam :: Tutorial Customize ASP.NET 4.5 Membership

clock December 17, 2013 10:29 by author Patrick

The ASP.NET MVC 4 Internet template adds some new, very useful features which are built on top of SimpleMembership. These changes add some great features, like a much simpler and extensible membership API and support for OAuth. However, the new account management features require SimpleMembership and won't work against existing ASP.NET Membership Providers. I'll start with a summary of top things you need to know, then dig into a lot more detail.

Summary:

  • SimpleMembership has been designed as a replacement for the previous ASP.NET Role and Membership provider system
  • SimpleMembership solves common problems developers ran into with the Membership provider system and was designed for modern user / membership / storage need
  • SimpleMembership integrates with the previous membership system, but you can't use a MembershipProvider with SimpleMembership
  • The new ASP.NET MVC 4 Internet application template AccountController requires SimpleMembership and is not compatible with previous MembershipProviders
  • You can continue to use existing ASP.NET Role and Membership providers in ASP.NET 4.5 and ASP.NET MVC 4 - just not with the ASP.NET MVC 4 AccountController
  • The existing ASP.NET Role and Membership provider system remains supported, as it is part of the ASP.NET core
  • ASP.NET 4.5 Web Forms does not use SimpleMembership; it implements OAuth on top of ASP.NET Membership
  • The ASP.NET Web Site Administration Tool (WSAT) is not compatible with SimpleMembership

The following is the result of a few conversations with Erik Porter (PM for ASP.NET MVC) to make sure I had some the overall details straight, combined with a lot of time digging around in ILSpy and Visual Studio's assembly browsing tools.

SimpleMembership: The future of membership for ASP.NET
The ASP.NET Membership system was introduced with ASP.NET 2.0 back in 2005. It was designed to solve common site membership requirements at the time, which generally involved username / password based registration and profile storage in SQL Server. It was designed with a few extensibility mechanisms - notably a provider system (which allowed you override some specifics like backing storage) and the ability to store additional profile information (although the additional  profile information was packed into a single column which usually required access through the API). While it's sometimes frustrating to work with, it's held up for seven years - probably since it handles the main use case (username / password based membership in a SQL Server database) smoothly and can be adapted to most other needs (again, often frustrating, but it can work).

The ASP.NET Web Pages and WebMatrix efforts allowed the team an opportunity to take a new look at a lot of things - e.g. the Razor syntax started with ASP.NET Web Pages, not ASP.NET MVC. The ASP.NET Web Pages team designed SimpleMembership to (wait for it) simplify the task of dealing with membership. As Matthew Osborn said in his post Using SimpleMembership With ASP.NET WebPages:
With the introduction of ASP.NET WebPages and the WebMatrix stack our team has really be focusing on making things simpler for the developer. Based on a lot of customer feedback one of the areas that we wanted to improve was the built in security in ASP.NET. So with this release we took that time to create a new built in (and default for ASP.NET WebPages) security provider. I say provider because the new stuff is still built on the existing ASP.NET framework. So what do we call this new hotness that we have created? Well, none other than SimpleMembership. SimpleMembership is an umbrella term for both SimpleMembership and SimpleRoles.

Part of simplifying membership involved fixing some common problems with ASP.NET Membership.

Problems with ASP.NET Membership
ASP.NET Membership was very obviously designed around a set of assumptions:

  • Users and user information would most likely be stored in a full SQL Server database or in Active Directory
  • User and profile information would be optimized around a set of common attributes (UserName, Password, IsApproved, CreationDate, Comment, Role membership...) and other user profile information would be accessed through a profile provider

Some problems fall out of these assumptions.
Requires Full SQL Server for default case
The default, and most fully featured providers ASP.NET Membership providers (SQL Membership Provider, SQL Role Provider, SQL Profile Provider) require full SQL Server. They depend on stored procedure support, and they rely on SQL Server cache dependencies, they depend on agents for clean up and maintenance. So the main SQL Server based providers don't work well on SQL Server CE, won't work out of the box on SQL Azure, etc.

Custom Membership Providers have to work with a SQL-Server-centric API
If you want to work with another database or other membership storage system, you need to to inherit from the provider base classes and override a bunch of methods which are tightly focused on storing a MembershipUser in a relational database. It can be done (and you can often find pretty good ones that have already been written), but it's a good amount of work and often leaves you with ugly code that has a bunch of System.NotImplementedException fun since there are a lot of methods that just don't apply.

Designed around a specific view of users, roles and profilesThe existing providers are focused on traditional membership - a user has a username and a password, some specific roles on the site (e.g. administrator, premium user), and may have some additional "nice to have" optional information that can be accessed via an API in your application.
This doesn't fit well with some modern usage patterns:

  • In OAuth and OpenID, the user doesn't have a password
  • Often these kinds of scenarios map better to user claims or rights instead of monolithic user roles
  • For many sites, profile or other non-traditional information is very important and needs to come from somewhere other than an API call that maps to a database blob

What would work a lot better here is a system in which you were able to define your users, rights, and other attributes however you wanted and the membership system worked with your model - not the other way around.

Requires specific schema, overflow in blob columns


Update: This schema has been improved a lot with Universal Providers. The views and stored procedures have been removed, and the tables are simplified.

SimpleMembership as a better membership system
As you might have guessed, SimpleMembership was designed to address the above problems.

Then we point SimpleMemberhip at that table with a one-liner:
WebSecurity.InitializeDatabaseFile("SecurityDemo.sdf", "Users", "UserID", "Username", true);

Broaden database support to the whole SQL Server family
While SimpleMembership is not database agnostic, it works across the SQL Server family. It continues to support full SQL Server, but it also works with SQL Azure, SQL Server CE, SQL Server Express, and LocalDB. Everything's implemented as SQL calls rather than requiring stored procedures, views, agents, and change notifications.

Note that SimpleMembership still requires some flavor of SQL Server - it won't work with MySQL, NoSQL databases, etc. You can take a look at the code in WebMatrix.WebData.dll using a tool like ILSpy if you'd like to see why - there are places where SQL Server specific SQL statements are being executed, especially when creating and initializing tables. It seems like you might be able to work with another database if you created the tables separately, but I haven't tried it and it's not supported at this point.

Easy to with Entity Framework Code First
The problem with with ASP.NET Membership's system for storing additional account information is that it's the gate keeper. That means you're stuck with its schema and accessing profile information through its API.

SimpleMembership flips that around by allowing you to use any table as a user store. That means you're in control of the user profile information, and you can access it however you'd like - it's just data. Let's look at a practical based on the AccountModel.cs class in an ASP.NET MVC 4 Internet project. Here I'm adding a Birthday property to the UserProfile class.

How SimpleMembership integrates with ASP.NET MembershipOkay, enough sales pitch (and hopefully background) on why things have changed. How does this affect you? Let's start with a diagram to show the relationship (note: I've simplified by removing a few classes to show the important relationships):
So SimpleMembershipProvider is an implementaiton of an ExtendedMembershipProvider, which inherits from MembershipProvider and adds some other account / OAuth related things. Here's what ExtendedMembershipProvider adds to MembershipProvider:

Membership in the ASP.NET 4.5 project template
ASP.NET 4.5 Web Forms took a different approach which builds off ASP.NET Membership. Instead of using the WebMatrix security assemblies, Web Forms uses Microsoft.AspNet.Membership.OpenAuth assembly. I'm no expert on this, but from a bit of time in ILSpy and Visual Studio's (very pretty) dependency graphs, this uses a Membership Adapter to save OAuth data into an EF managed database while still running on top of ASP.NET Membership.

How does this fit in with Universal Providers (System.Web.Providers)?
Just to summarize:

  • Universal Providers are intended for cases where you have an existing ASP.NET Membership Provider and you want to use it with another SQL Server database backend (other than SQL Server). It doesn't require agents to handle expired session cleanup and other background tasks, it piggybacks these tasks on other calls.
  • Universal Providers are not really, strictly speaking, universal - at least to my way of thinking. They only work with databases in the SQL Server family.
  • Universal Providers do not work with Simple Membership.
  • The Universal Providers packages include some web config transforms which you would normally want when you're using them.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in