All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET 4.5.1 Windows Cloud Hosting - With ASPHostPortal.com :: How to Transferring User Accounts from ASP.NET to MojoPortal

clock April 10, 2014 08:24 by author Kenny

MojoPortal is a free and open source content management system that allows you to maintain your Web site with no HTML coding knowledge. When you need to build a web application you usually have some business functionality in mind but there is always a certain amount of web plumbing that needs to be implemented for things like navigation, authentication of users, security and roles and other things that are needed to support most kinds of business application logic. Sometimes we need to transfer user accounts from existing ASP.NET membership based sites into MojoPortal. So, in this article i will explain about how to transferring user accounts from ASP.NET to MojoPortal.

For the first step, you must set MojoPortal to use plain text passwords.
And then, create a folder on your PC to contain the scripts > in this folder create the following .bat files:

CreateMojoUserTablesXMLFormats.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set switches= -c -x
set formatDir=[Full path to formats directory with trailing slash]
bcp %database%mp_Users format nul %login% %switches% -f
%formatDir%mojoUsers.xml
bcp %database%mp_UserProperties format nul %login% %switches% -f
%formatDir%mojoUserProperties.xml
bcp %database%mp_userRoles format nul %login% %switches% -f
%formatDir%mp_userRoles.xml


ExportASPNETUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set dataDir=[Full path to data directory with trailing slash]
set database=[Databasename].[Schema].
set switches= -k –c
bcp "SELECT 0 AS UserID, 1 AS SiteID, aspnet_Users.Username AS Name,
aspnet_Users.UserName AS LoginName, COALESCE
(aspnet_Membership.Email,aspnet_Users.UserName + '@dummyemail.co.uk' ) AS
Email, aspnet_Membership.LoweredEmail AS LoweredEmail, NULL AS
PasswordQuestion, NULL AS PasswordAnswer, NULL AS Gender,
aspnet_Membership.IsApproved AS ProfileApproved, NULL AS RegisterConfirmGUID,
aspnet_Membership.IsApproved AS ApprovedForForums, 0 AS Trusted, CASE
aspnet_Roles.RoleName WHEN 'xg' THEN 0 ELSE 1 END AS DisplayInMemberList, NULL
AS WebsiteURL, NULL AS Country, NULL AS [State], NULL AS Occupation, NULL AS
Interests, NULL AS MSN, NULL AS Yahoo, NULL AS AIM, NULL AS ICQ, 0 AS
TotalPosts, NULL AS AvatarURL, 0 AS TimeOffsetHours, NULL AS [Signature],
aspnet_Membership.CreateDate AS DateCreated, aspnet_Membership.UserId AS
userGUID, NULL AS Skin, 0 AS IsDeleted, aspnet_Users.LastActivityDate AS
LastActivityDate, aspnet_Membership.LastLoginDate AS LastLoginDate, NULL AS
LastPasswordChangedDate, NULL AS LastLockoutDate, 0 AS
FailedPasswordAttemptCount, NULL AS FailedPwdAttemptWindowStart, 0 AS
FailedPwdAttemptCount, NULL AS FailedPwdAnswerWindowStart,
aspnet_Membership.IsLockedOut AS IsLockedOut, NULL AS MobilePin, NULL AS
PasswordSalt, NULL AS Comment, NULL AS OpenIDURI, NULL AS WindowsLiveID,
'77C33D82-D6F0-49ED-95A7-84C11919AD94' AS SiteGUID, NULL AS TotalRevenue,
userInfo.ForeName AS FirstName, userInfo.Surname AS LastName,
aspnet_Users.Username as Pwd, 1 AS MustChangePassword, NULL AS NewEmail, NULL
AS EditorPreference, '00000000-0000-0000-0000-000000000000' AS EmailChangeGuid,
NULL AS TimeZoneID, '00000000-0000-0000-0000-000000000000' AS PasswordResetGuid
FROM %database%aspnet_Membership INNER JOIN %database %aspnet_Users ON
aspnet_Membership.UserId=aspnet_Users.UserId INNER JOIN %database%userInfo on
aspnet_Membership.UserId=userInfo.userId INNER JOIN
%database%aspnet_UsersInRoles ON
aspnet_Membership.UserId=aspnet_UsersInRoles.UserId INNER JOIN
%database%aspnet_Roles ON aspnet_UsersInRoles.RoleId =
aspnet_Roles.RoleId" queryout %dataDir%lharUsers.txt %switches% %login% -o
output/usersOutput.txt
bcp "select RoleName,UserId from %database%aspnet_Roles INNER JOIN
%database%aspnet_UsersInRoles on
aspnet_Roles.RoleId=aspnet_UsersInRoles.RoleId" queryout
%dataDir%lharUsersRoles.txt %switches% %login% -o output/userRolesOutput.txt
bcp "SELECT newid() AS PropertyID, UserId AS userGUID, [String to use
as MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo
UNION ALL
SELECT newid() AS PropertyID, UserId AS userGUID, [String to use as
MojoPortal PropertyName] AS PropertyName, Title AS PropertyValueString,
NULL AS PropertyValueBinary, GETDATE() AS LastUpdatedDate, 0 AS IsLazyLoaded
FROM %database%UserInfo" queryout %dataDir%lharUserProfiles.txt %switches%
%login% -o output/userPropertiesOutput.txt


ImportMojoPortalUserData.bat

set login=-U [Username] -P [Password] -S [SQL Server Instance]
set database=[Databasename].[Schema].
set dataDir=[Full path to data directory with trailing slash]

set switches= -k -R

set formatDir=[Full path to outputs directory with trailing slash]

bcp %database%mp_users IN %dataDir%lharUsers.txt %login% %switches% -f %formatDir%mojoUsers.xml -o output/importUsers.txt

bcp %database%mp_userProperties IN %dataDir%lharUserProfiles.txt %login% %switches% -f %formatDir%mojoUserProperties.xml -o output/importUserProperties.txt

bcp %database%mp_userRoles IN %dataDir%lharUsersRoles.txt %login% %switches% -f %formatDir%mp_userRoles.xml -o output/importUserRoles.txt


Next step is, create the following subdirectories in this folder: data, formats, output.
After create the CreateMojoUserTablesXMLFormats.bat file and the ExportASPNETUserData.bat file, run these program.
Don’t forget to check the output directory for any errors and check the data files have been created and contain the data you expect.
After that, run the ImportMojoPortalUserData.bat. Check the output directory for any errors and check the database tables have the data.
Switch MojoPortal back to using encrypted passwords and the last test a few logins.



ASP.NET Hosting Full Trust Mode

clock April 8, 2014 09:03 by author Diego

What’s ASP.NET shared hosting trust level?

You need to check many aspects before choosing a .Net hosting provider, those aspects should include .Net MVC framework, SQL Server, disk space, monthly bandwidth, hosting prices, but there’s one thing you may ignore really – “IIS Security Trust Level”.


If you’re not familiar with what’s asp.net shared hosting trust level, here I’d like to bring you a short introduction. The trust level is real important that could affect with your site secure and performance, and a full trust level means higher risk for hackers sneak into server to make destroy. Most of small .Net hosts only can give medium trust level on their servers. If your applications need to be run a full trust mode, then you’ve to look for a web host which can give full permission to you.


<system.web>
<securityPolicy>
<trustLevel name="High" policyFile="web_hightrust.config"/>
<trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
<trustLevel name="Low" policyFile="web_lowtrust.config"/>
<trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
</securityPolicy>
</system.web>

You can see there are 4 trust levels for web hosts to pre-set by default – Minimal trust, Low trust, Medium trust and High / Full trust. High trust means higher risk for hackers to sneak into server, most of Windows hosting companies doesn’t allow their customers to run full trust level by default.
- Full Trust allows the users to do everything of application pool on one Windows web server. Some of applications cannot work properly under a medium trust web server, full trust means more flexible and you’re also able to change to medium trust once your application don’t need full trust.
- High Trust, websites are limited to call unmanaged code, e.g. Win32 APIs, COM interop.
- Medium Trust level websites are limited to access the file system and not so flexible as full trust level web server.
- Low Trust & Minimal Trust level are 2 options to restrict the users heavily, it won’t allow users to connect to server actively. At present, there’s no Windows hosts offering such asp.net shared hosting plan yet.


With more and more people and companies developing websites by Microsoft .NET technology, ASP.NET shared web hosting comes to be the major solution provided by many web hosting companies. Most of people choose an ASP.NET web host considering about .NET framework version, ASP.NET MVC support, SQL Server database, disk space or bandwidth but they usually ignore the most important feature “IIS security level”. That determines whether the ASP.NET websites can run successfully on the shared web host. In result to, if you developing an ASP.NET website that works well in the local development environment and attempt to run it in the ASP.NET shared web host, you may get the following exception.


System.Security.SecurityException: That assembly does not allow partially trusted callers.


This is caused by the security level of the ASP.NET shared web host that your application is forced to run with the limited permission, by locking down the access to server file system, preventing the background threads, or interacting with COM interfaces, etc.
Full Trust and Medium Trust are two widely used levels in ASP.NET shared web hosting. The full trust provides best flexibility but it has potential security issues to the shared server, especially when the web hosting provider doesn't have rich experience on setting up Windows permission and IIS. Compared to Full Trust, you have to review the website carefully before you go with a web host only supports Medium Trust Level. You can refer to the following checkpoints for the review.
-The website shall not call unmanaged APIs.

-The website shall not access to file system, system registry, event logs and anything else related to the system.
-The website shall not generate code for execution dynamically using Code DOM.

-The website shall not use XslTransform to transform something from XML using XSLT.

-The website has to be signed with a Strong Name.

Check with the web page from Microsoft about which namespaces and classes are not supported in Medium Trust environment.
And here is quick way to confirm the compatibility of websites to Medium Trust Level, in the local environment.

1. Add partially trusted callers attribute into AssemblyInfo.cs file of the website project, as following code snippet,
[assembly: AllowPartiallyTrustedCallers]

2.Add the following line into the web.config,
<trust level="Medium" />

Medium Trust or Full Trust level? UP to Your choice:
If your website can be working fine under medium trust level, I suggest you don’t need a full trust asp.net hosting, most of popular .Net applications should be working fine under a medium trust level server, only when your application has to be run under a full trust level enviroment, then you can find an ASP.NET full trust hosting company.



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
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 = newSystem.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
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: Capture images using web camera in ASP.NET 4.5.1

clock March 25, 2014 09:11 by author Kenny

In this article, i'm going to explain about how to integrate a webcam into your web application using ASP.NET 4.5.1. A web camera can capture images at the server end and a web page can display them. It’s very simple for integrate a webcam and capture images in your website that using ASP.NET 4.5.1.

Before it, make sure that your device has Latest Flash player and Web camera.
Let's following these steps:

First, copy the “WebcamResources” into your new application.
After that, add the following code in to your Default.aspx page:
<object width="450" height="200"param name="movie1" value="WebcamResources/save_picture.swf"

embed src="WebcamResources/save_picture.swf" width="45
0"
height="200" >
</object>

This code will place your Flash object into your web page, used to capture the images from the web cam.
Add one more page there with the name ImageConversions.aspx.
Add the following code into ImageConversion.aspx at the page load event:
string str_Photo = Request.Form["image_Data"]; //Get the image from flash file
byte[] photo = Convert.FromBase64String(str_Photo);
FileStream f_s = new FileStream("C:\\capture.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter b_r = new BinaryWriter(f_s);
b_r.Write(photo);
b_r.Flush();
b_r.Close();
f_s.Close();


The above code will convert the bytes to an image and will save the image in the c drive.



ASP.NET 4.5.1 Hosting - with ASPHostPortal.com :: How to Load GMap Direction from Database in ASP.NET

clock March 11, 2014 06:45 by author Kenny

Well i am going to explain how to load GMap direction from database in ASP.NET.
Google maps is a web mapping service application and technology provided by Google, powering many map-based services, including the Google maps website, Google ride finder, Google transit, and maps embedded on third-party websites via the Google maps API. ASP.NET is a server-side web application framework designed for web development to produce dynamic web pages.
Let’s check the steps for run this program.

For the first: Go to file > new > project > select asp.net web forms application > entry application name > click ok.

And then add a database: Go to solution explorer > right click on app_data folder > add > new item > select sql server database under data > enter database name > add.


After that create table: Open database > right click on table > add new table > add columns > save > enter table name > ok.

This is the table sample:

Next, create a stored procedure in sql server: Open database > right click on stored procedure > add new stored procedure > write below sql code > save.

Next step, add a webpage: Go to solution explorer > right click on project name form solution explorer > add > new item > select web form/ web form using master page under web > enter page name > add.
Html code



Js code

Write this below js code for load gmap direction from database.

<script src="//maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abqiaaaaupsjpk3mbtdpj4g8cqbnjrragtyh6uml8madna0ykuwnna8vnxqczvbxtx2dyyxgstoxpwhvig7djw" type="text/javascript"></script><script language="javascript">
        var gmap;

        var directionpanel;
        var direction;
        function initialize() {
            gmap = new gmap2(document.getelementbyid("map"));
            gmap.setcenter(new glatlng(22.573438, 88.36293), 15);
// here i have set kolkata as center and 15 zoom level

            directionpanel = document.getelementbyid("route");
            direction = new gdirections(gmap, directionpanel);
        }
        $(document).ready(function ()
{
            initialize();

            $('#btngetdirection').click(function () {
                //here populate data from database and get to gmap direction
                populatedirection();
            });
        });
        function populatedirection() {
            var from = $('#<%=ddfrom.clientid%>').val();
            var to = $('#<%=ddto.clientid%>').val();

            $.ajax({
                url: "default.aspx/getdirectioin",
// here url for code behind function
                type: "post",
                data: "{from: '"+from+"', to: '"+to+"'}",
                datatype: "json",
                contenttype: "application/json; charset=utf-8",
                success: function (data) {
                    direction.load(data.d.tostring());

                },
                error: function () {
                    alert("error!");
                }
            });
        }
    </script>

And then: write following code in page_load event:
Protected void page_load(object sender, eventargs e)
{
    if (!ispostback)
    {
        populatelocation();
    }}


Here is the function...

Private void populatelocation(){

// populate location here
    datatable dt = new datatable();
    using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        string query = "select * from locations";
        sqlcommand cmd = new sqlcommand(query, con);
        if (con.state != connectionstate.open)
        {
            con.open(); }
        dt.load(cmd.executereader());}
    ddfrom.datasource = dt;
    ddfrom.datatextfield = "locname";
    ddfrom.datavaluefield = "locid";
    ddfrom.databind();
    ddto.datasource = dt;
    ddto.datatextfield = "locname";
    ddto.datavaluefield = "locid";
    ddto.databind();}


Don’t forget write this function into your page code behind for called from jquery code:

// this is the function is for called from jquery
[webmethod]
Public static string getdirectioin(string from, string to){
    string returnval = "";
    datatable dt = new datatable();
using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        sqlcommand cmd = new sqlcommand("getdirection", con);
        cmd.commandtype = commandtype.storedprocedure;
        cmd.parameters.addwithvalue("@locfrom", from);
        cmd.parameters.addwithvalue("@locto", to);
        if (con.state != connectionstate.open)
        {
            con.open();}
        dt.load(cmd.executereader());}
    returnval = "from: " + dt.rows[0]["fromloc"].tostring() + " to: " + dt.rows[0]["toloc"].tostring();
    return returnval;}


And the last, Just run your application



ASP.NET MVC 5.1.1 Hosting with ASPHostPortal.com :: Difference between ASP.NET Web Forms and ASP.NET MVC

clock March 5, 2014 09:53 by author Kenny

Now I wiil expose the main difference between ASP.NET Web Form and ASP.NET MVC.
ASP.NET Web Forms is a part of the ASP.NET web application framework. Web Forms are pages that your users request through their browser and that form the user interface (UI) that give your web applications their look and feel. These pages are written using a combination of HTML, server controls, and server code. When users request a page, it is compiled and executed on the server, and then it generates the HTML markup that the browser can render. Using Visual Studio, you can create ASP.NET Web Forms using a powerful IDE. For example, this lets you drag and drop server controls to lay out your Web Forms page. You can then easily set properties, methods, and events for controls or for the page in order to define the page's behavior, look and feel, and so on. To write server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. A model represents the state of a particular aspect of the application. A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view. A view accepts necessary information from the controller and renders a user interface to display that information.
ASP.NET developers have two options when building new Web projects: ASP.NET Web Forms or ASP.NET MVC framework.
There are the different
between ASP.NET Web Form and ASP.NET MVC:



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: Configuring BotDetect ASP.NET CAPTCHA Options

clock February 18, 2014 06:08 by author Ben

1. BotDetect CAPTCHA ASP.NET Configuration

BotDetect Captcha properties can be set in several different ways, depending on the type of value you are customizing.

2. BotDetect CAPTCHA Web.Config Configuration Section

BotDetect configuration options which apply to all Captcha instances within a particular ASP.NET application can be specified in the web.config file. This approach can be seen in the Captcha customization code sample coming with the BotDetect installation.

This configuration section first needs to be registered at the top of the web.config file:

<configuration>

  <configSections>

    <!-- Register the BotDetect configuration section -->

    <section name="botDetect" requirePermission="false"

      type="BotDetect.Configuration.BotDetectConfigurationSection,

        BotDetect" />

  </configSections>

 

 

You can then create the <botDetect> section just below the closing </configSections> element, and (for example) disable all audio Captcha sounds in the application by specifying:

<botDetect>

  <captchaSound enabled="false" />

</botDetect>

3. BotDetect CAPTCHA .aspx / Visual Studio Designer Instance Settings

When adding the BotDetect:Captcha control to the .aspx file defining your form (either by using the Visual Studio Designer or editing the source directly), you can specify various attributes in the element declaration. For example, the simplest way to specify Captcha image size is:

<BotDetect:Captcha ID="SampleCaptcha" runat="server" ImageSize="200, 50" />

However, it's not recommended to use this method to set all Captcha instance properties. Page source declarations are processed when the page is loaded, and since they have to be applied to Captcha images and sounds (which come as separate Http requests), they have to be saved in ASP.NET Session state. It's better not to take up Session space if it's not necessary.

4. BotDetect CAPTCHA Code-Behind Instance Settings

It's also possible to specify various Captcha object settings in your page code-behind code. For example, code type and length can be set in the Page_PreRender override:

protected void Page_PreRender(object sender, EventArgs e)

{

  // initial page setup

  if (!IsPostBack)

  {

    // Captcha code properties

    SampleCaptcha.CodeLength = 4;

    SampleCaptcha.CodeType = BotDetect.CodeType.Numeric;

}

The same caveat applies to this method as with .aspx settings: this code is executed when the form is loaded, but since Captcha images and sounds are loaded in separate Http requests (which don't result in this code being executed), all values set this way have to be saved in ASP.NET Session state. Since different visitors will use separate Sessions, the amount of state used is multiplied by the number of active visitors / Sessions, and it's better not to use a lot of it.

5. BotDetect CAPTCHA Event Handler Property Setting and Randomization

This is the recommended approach to Captcha instance property setting. It's the most complex method, since it requires setting up an event handler. But since this handler is going to be executed for all Captcha requests (including separate Captcha image and sound Http requests), there is no need to persist the values in ASP.NET Session state.

Randomizing Captcha properties significantly improves Captcha security, and it should always be performed in this event handler instead of Page_Load or Page_PreRender, because the Captcha control event is also fired for direct Captcha image and sound requests (which skip the page events since the page is never loaded) – for example when clicking the Captcha reload button repeatedly.

You can see this approach to BotDetect Captcha property setting implemented in the Captcha randomization code sample coming with the BotDetect installation.

First, a InitializedCaptchaControl event handler needs to be registered in the Page_Init override:

protected void Page_Init(object sender, EventArgs e)

{

  SampleCaptcha.InitializedCaptchaControl +=

    new EventHandler<InitializedCaptchaControlEventArgs>(

      SampleCaptcha_InitializedCaptchaControl);

}

Then, randomization rules can be declared in the event handler:

void SampleCaptcha_InitializedCaptchaControl(object sender,

  InitializedCaptchaControlEventArgs e)

{

  if (e.CaptchaId != SampleCaptcha.CaptchaId)

  {

    return;

  }

  CaptchaControl captcha = sender as CaptchaControl;

  // randomize code generation properties

  captcha.CodeStyle = CaptchaRandomization.GetRandomCodeStyle();

  captcha.CodeLength = CaptchaRandomization.GetRandomCodeLength(4, 5);

  captcha.ImageStyle = CaptchaRandomization.GetRandomImageStyle();

  captcha.SoundStyle = CaptchaRandomization.GetRandomSoundStyle();

}

The CaptchaRandomization helper allows easy randomization of Captcha parameters.

 



ASP.NET MVC 5.1 Hosting :: ASPHostPortal.com Proudly Launches ASP.NET MVC 5.1 Hosting

clock January 28, 2014 07:48 by author Ben

ASPHostPortal.com officially launches ASP.NET MVC 5.1  hosting at affordable prices. Instant Setup, Fast and Friendly Support!

ASPHostPortal.com, a leading innovator in Windows Hosting, announces the launch of ASP.NET MVC 5.1 Hosting. The ASP.NET MVC 5.1 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET.

ASP.NET MVC 5.1 contains a number of advances over previous versions, including the ability to define routes using C# attributes and the ability to override filters,Enum support in Views, Support for current Context in Unobtrusive Ajax, Filter Overrides and etc. The user experience of building MVC applications has also been substantially improved.

The company believes in providing top-notch service at affordable price. They offer ASP.NET MVC 5.1 hosting with the following features such as Unlimited Domain, Unlimited Subdomain, 5 GB Disk Space, 2 SQL Database and Unlimited Email Account.
 
“Our customers have been asking us about MVC 5.1 and we are happy to deliver a hosting platform that supports all the latest in the Microsoft Web Stack.” said said Dean Thomas, Manager at ASPHostPortal.com.  "And it proves that we remain at the forefront in Microsoft technology".

Where to look for the best ASP.NET MVC 5.1 hosting service? How to know more about the different types of hosting services? Read more about it on http://www.asphostportal.com.


About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET 4.5 Hosting :: Regex (Regular Expressions) Time Out In ASP.NET 4.5

clock November 13, 2013 07:13 by author Ben

One of new features from ASP.NET 4.5 is Regex. Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it.



Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.



Now this works exactly the same as the previous one. Here the Regex(new feature of ASP.NET 4.5) constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.



This is the actual code that runs in background and generates the timeouts. Infact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  I hope you like it. More to come shortly.



Free Trial ASP.NET 4.5.1 Hosting :: ASPHostPortal.com Proudly Launches ASP.NET 4.5.1 Free Trial Hosting

clock October 28, 2013 06:26 by author Ben

ASP web hosting specialist ASPHostPortal.com announced this week that it has launched a hosting package with support for Microsoft’s ASP.NET 4.5.1.
The company, which says it specializes in hosting for projects based on Windows, Microsoft SQL Server, ASP.NET, along with various other Microsoft products, launched the service this week, just a few month after the release candidate for ASP.NET 4.5.1 was issued by Microsoft.

Specialization in a certain development technology is one of the more common ways for a hosting provider to distinguish itself in a very commoditized market. ASPHostPortal.com has obviously intentionally narrowed its market to developers using Microsoft technologies.

One of the keys to focusing on a market based around a certain technology is quickly instituting support and expertise around new and emerging elements of that technology
The latest update to Microsoft’s popular .NET technology, ASP.NET 4.5.1. Here are some new features of ASP.NET 4.5.1:

  1. CLR Improvements
  2. multi-core JIT improvements
  3. Async-aware debugging
  4. Managed return value inspection
  5. ADO.NET idle connection resiliency
  6. ASP.NET app suspension
  7. On-demand large object heap compaction
  8. Better discoverability of Microsoft .NET NuGet packages
  9. Supporting large scale deployment of .NET NuGet packages


According to ASPHostPortal.com, its ASP.NET 4.5.1 offerings are distinguished by their low cost, with many of the hosting services supporting the technology being of the more expensive variety. ASPHostPortal.com’s offerings 7 Day Free Trial Hosting to all new customers.

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET4.5.1 hosting services, we hope that developers and our existing clients can try this new features.Now, you don’t need to spend a lot of money to get ASP.NET 4.5.1 hosting.”

For more information about new ASP.NET 4.5.1, please visit http://www.asphostportal.com.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in