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 :: 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.



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. 



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