Windows 2012 Hosting - MVC 4 and SQL 2012 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

Windows Reseller Hosting - ASPHostPortal.com :: Best Practices windows cloud server security

clock April 27, 2016 20:57 by author Armend

More and more we are helping people get set up on  Windows cloud servers here at windows2008hosting.asphostportal.com .  While dedicated server solutions are the right choice for certain situations, clients are finding the benefits of cloud servers or, in many cases, a hybrid hosting solution to be the perfect fit for their hosting needs. With all this cloud talk, there are several technologies supported on Windows cloud servers that you may not have realized. These options can make the difference when configuring a cloud server solution that will best optimize your site or application.

 

Firewalls, VPN & SSL in the Cloud

The best practices of leveraging Virtual Private Networks (VPN), Secure Sockets Layers (SSL) and Firewalls to protect sensitive information on a Windows Cloud Server are recommend and also supported just as they would be with a physical dedicated server. If you’re unsure as to what any of these are and why they are necessary, the following will serve as a summary of each and their benefits.

What is VPN?

Virtual Private Networking is a secure and controlled method of connecting remote networks and users for the purpose of dealing with sensitive information. When using a VPN, all data is encrypted at the source, sent securely to the destination, then decrypted at the destination – assuring that only the previously approved source and destination people or systems can access the data. This is often a necessary element to incorporate in your hosting solution if you are an eCommerce company accessing sensitive back-end data like credit cards or orders, require PCI compliance, or simply need to securely work with remote clients or coworkers regarding sensitive information. A VPN connection allows you to guarantee identity through point-to-point connections and user authentication. While Windows cloud servers are virtual, they retain all the same VPN encrypting capabilities as a dedicated server, giving you complete control over security and privacy of your data. (For more information on Virtual Private Networking.

What is an SSL Connection?

The Secure Socket Layer protocol (SSL) ensures secure transactions between Windows cloud servers and browsers. This is particularly important anytime sensitive information must be transmitted over the open Internet. For example, any sign-up process where personal information is needed, (credit card information, personal data, etc.) would justify use of an SSL connection. You can recognize the use of an SSL connection when you see an “S” included in the URL (https://).
While the technical breakdown of an SSL can be somewhat complicated, it’s important to understand the basic concept of an SSL connection and how important it is inmaintaining security with sensitive information.

What is a Firewall?

A firewall is a security solution designed to only allow safe and trusted connections to whatever it is set to protect. It does this by identifying several pieces of information for all incoming connections, thus blocking access to any unfamiliar or unauthorized sources looking to access that data. The difference between a firewall and an SSL connection is that SSL is used to ensure your sensitive information can be securely sent from a webpage to a server, while a firewall is designed to control direct access to the cloud server itself. A firewall can be used to lock down ports and allow only certain information to be accessible, while keeping other information secure.

Firewall in a Windows Cloud Server

In order to set up a firewall in a Windows cloud server configuration, various steps must be taken to optimize the firewall for the cloud – but depending on your hosting provider, these steps will be covered for you. Once these steps are taken, it is no different than a firewall configured for a dedicated physical server.
Note: In addition to base intrusion detection and firewall protection offered at our network core, our Windows Cloud Servers come with free built-in Windows Firewall service that can be used to lock down ports and restrict access with a focus on the specific needs of your server – assuring that only the ports needed are opened and only available to the users or systems that need the sensitive access.

Cloud Server Security Best Practices

The above security steps are important in and of themselves, but they also serve as a baseline for achieving PCI Compliance, something in which we at ASPHostPortal.com are well versed. So, whether you’re looking to sure up your security as a best practice, or find yourself needing to implement the above steps in accordance with the PCI Security Standard Council, Windows cloud server hosting offers all the tools available on a dedicated server configuration, but often with several added benefits.

Best Windows Server 2008 Hosting Recommendation

ASPHostPortal.com

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server 2008. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows server 2008 Hosting, we should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: How to Bind Data to a Label From a SqlDataSource

clock April 25, 2016 21:24 by author Dan

Label controls in ASP.NET don't have a smart tag that allows you to select a data source, so at first glance, it is not easy to see how to bind a value returned from a SqlDataSource or AccessDataSource control to the label. Here's how to programmatically access the data returned by such a DataSource and apply it to a non-databound control.

To programmatically access the contents of a SqlDataSource or AccessDataSource control you need to explicitly call its Select() method. This method accepts a single input parameter of type DataSourceSelectArguments. This parameter can contain information regarding the filters to apply or the column to Order By. For example, when working with a sortable GridView, sorting a column calls the Select() method, and passes in a DataSourceSelectArguments instance with its SortExpression property set to the column name the user chose to sort by. If you don't want the DataSource to sort or filter, you pass in DataSourceSelectArguments.Empty.

Depending on the DataSourceMode of the DataSource control, one of two objects are returned when the Select() method is called. If the DataSourceMode is set to DataReader, a DataReader object is returned. The type of DataReader (SqlDataReader, OleDbDataReader, OdbcDataReader etc) that is returned depends entirely on the provider type used - in other words, whether you are using the OleDb provider, SqlClient provider etc. It has nothing to do with the type of DataSource control. The examples below both query an Access database, but one uses the AccessDataSource control, and the other uses the SqlDataSource control. Both return OleDbDataReaders, because it is the OleDbProvider library that is used for the connection.

If the DataSourceMode is set to Dataset, or not set at all (which means that the default setting of Dataset is used) the object that is returned is a DataView. A DataView is like a DataTable on steroids. It exposes methods that allow you to filter and sort data, for example, and bind it. A DataView contains a collection of DataRowView objects, which represent each row in the returned results.

So, with a DataReader, you would access the values during the DataReader.Read() operation, in very much the same way as if you are using plain ADO.NET code, whereas with the DataSet, you would need to create an object of the appropriate type - DataView, then iterate the DataRowView collection to access the values. In this, the code is remarkably similar to accessing values directly from a DataSet's table collection using plain ADO.NET.

The code below shows the contents of an aspx file, which contains two label controls, and two SqlDataSource controls. Each SqlDataSource control has its DataSource mode set to alternative values - DataSet and DataReader, and both of them have an OnSelecting event defined in which the value of the EmployeeID parameter is assigned:

<asp:Label ID="Label1" runat="server" /> <asp:Label ID="Label2" runat="server" />

<asp:SqlDataSource
    ID="SqlDataSource1"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataSet"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource
    ID="SqlDataSource2"
    runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
    DatasourceMode="DataReader"
    SelectCommand="SELECT [LastName], [FirstName] FROM [Employees] WHERE ([EmployeeID] = ?)"
    OnSelecting="SqlDataSource2_Selecting">
    <SelectParameters>
        <asp:Parameter Name="EmployeeID" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>


The following code snippet shows the aspx.cs file contents, where the parameter values are set in the Selecting event handler. In the Page_Load method, the data returned by each of the Sql DataSource controls is accessed and a value consigned to a label. The method of access depends on the DataSource mode, but is identical for both SqlDataSource and AccessDataSource:

[C#]
protected void Page_Load(object sender, EventArgs e)
{

    DataView dvSql = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    foreach (DataRowView drvSql in dvSql)
    {
        Label1.Text = drvSql["FirstName"].ToString();
    }

    OleDbDataReader rdrSql = (OleDbDataReader)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
    while (rdrSql.Read())
    {
        Label2.Text = rdrSql["LastName"].ToString();

    }
    rdrSql.Close();
}



protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["EmployeeID"].Value = 2;
}

[VB]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim dvSql As DataView =
    DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    For Each drvSql As DataRowView In dvSql
        Label1.Text = drvSql("FirstName").ToString()
    Next

Dim rdrSql As OleDbDataReader =
    DirectCast(SqlDataSource2.Select(DataSourceSelectArguments.Empty), OleDbDataReader)
    While rdrSql.Read()

        Label2.Text = rdrSql("LastName").ToString()
    End While
    rdrSql.Close()
End Sub

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub

Protected Sub SqlDataSource2_Selecting(ByVal sender As Object,
    ByVal e As SqlDataSourceSelectingEventArgs)
    e.Command.Parameters("EmployeeID").Value = 2
End Sub


When using this technique with Sql Server - or more specifically the SqlClient provider, change OleDbDataReader to SqlDataReader in the above code. Happy Coding.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



Windows Reseller Hosting - ASPHostPortal.com :: How to Choose Shared Web Hosting Service?

clock April 25, 2016 20:43 by author Armend

How to Choose Shared Web Hosting Service?

Shared web hosting is the most popular hosting solution for launching websites over the Internet. To help you pick a good option, we have introduced the most important aspects that should be considered when choosing web hosting service, including hosting features, customer service, cancellation policy, free marketing credits, and price. These are transparent checkpoints that you can evaluate a web host by yourself easily before signing up.

 

What Is Shared Web Hosting?

In order to have your business more visible for billions of internet users, you need to rent a web server which has fast connection to Internet and allows people to read your information. There are many options for hosting your websites. Usually the reasonable solutions are dedicated server, virtual private server, cloud hosting, and shared web hosting. If you're new to the internet or the estimated daily traffic of the website in the coming year is less than 800 page views or 300 unique visits, the shared web hosting shall be the best choice.

Shared web hosting means that the hosting company sells a dedicated server to thousands of customers. All of these customers share the server resources with each other. Each customer's data and files are protected to be invisible to others hosted with the shared server by some software or technology. Each customer has the complete access to the hosting account and shall be allocated with appropriate system resources.
What Is Shared Web Hosting The shared web hosting provider is responsible for the server maintenance, including both hardware and software.

  • Hardware: upgrade CPU, add memory, replace hard disk, setup backup system such as RAID 0/1/5, network routing and internet connection.
  • Software: upgrade OS or hosting solution software, install security patch, manage firewall, etc.

Meanwhile, as a customer, you have a web based control panel to manage your websites and services. You can view your website uptime or traffic statistics, exception logs, email accounts, and installation of applications. Most of companies don't help you maintain your website as the part of the hosting package unless you pay the additional money which may be more expensive than the hosting service itself.

Why Choose Shared Web Hosting?

Right Expectation on Customer Service For Shared Web Hosting Absolutely, it's the most budget and affordable web hosting solution that can promote your websites over the Internet. Generally, a good shared web hosting works flexibly for websites with less than 800 daily page views.
Another reason is that you don't need to take time maintaining the web server by yourself or hiring IT professionals. The hosting provider takes all of the work. Even some excellent providers perform data backups daily or weekly.

How to Choose Shared Web Hosting?

Pricing & Features

How to Choose Shared Web Hosting The reasonable price of shared web hosting is between $4 and $8 a month. This is the best range that well balances your cost and the web hosting service. It is suspected that some web hosts offer cheap web hosting under $3/month. In that case, it's highly possible that they cut off the customer service or oversell the server.
The best features of a web hosting are the things you require to launch your websites. So what you need to do is to create a list of features on what you need today and tomorrow, and check whether these are included by the hosting plan.

Reliability & Downtime Frequency

Reliability correlates to downtime. The downtime here doesn't mean 5 or 10 minutes down for server maintenance or scheduled operation. As I known, almost all web hosts have been hacked/attacked, down by hardware, or broken by OS/software upgrade. The key is the frequency and how they deal with the problem.
Right Expectation on Customer Service For Shared Web Hosting Basically, have one or twice downtime in a year is reasonable for web hosting in my opinion, not only shared web hosting, but also VPS hosting and dedicated server hosting. The reliability is determined by hardware, software and human maintenance.
As running a computer on hand, no one can guarantee there is no downtime caused by the damage of CPU, memory, motherboard or other hardware. How you can expect a server running for 24/7/365 with high working load without any problems.

Meanwhile, the system holes exist anywhere at all the time, so the hacks and attacks are endless. The FBI site had been hacked before, how you can think the web hosting is 100% secure perfectly.
What's more, most web hosts guarantee more than 99.9% uptime. To be frank, this number is extremely high. As we monitored dozens of web hosts , ASPHostPortal.com is the only host that completely provides such a reliable solution consistently. Read the uptime in the past 30 days below,



ASP.NET Hosting - ASPHostPortal.com :: How to Rank the Windows Hosting

clock April 19, 2016 20:01 by author Armend

How to Rank the Windows Hosting

To choose the really reliable Windows hosting, we follow the below guidelines.

#Operation System

The web hosting based on Windows server 2012 edition is ranked higher than the previous editions. Windows server 2012 has better performance, better stability, less consumption of system resources and high security. And it supports the best web server IIS 8.0 in Windows platform so far, which integrates with the ASP.NET pipeline much better than IIS 8.5/7.0

 

#Database System

ASP.NET applications work better with MSSQL than MySQL or PostgreSQL database. And the Windows web hosting supported MSSQL 2008 R2 gets a higher grade than MSSQL2005 and MSSQL2000. Feature and benefits in MSSQL2008 are better than the previous version of MSSQL, such as encrypt to enhance security, data compression to save disk space, parallel computing to accelerate speed, less consumption of system resource, and so on.

#DotNET Framework

The Windows hosting with support to multiple .NET framework versions especially .NET Framework V4 has a higher score in the ranking. The more versions supported the less compatible problems you may encounter, which also provides you more scalability to upgrade the websites later.

#Control Panel

Plesk is ranked as the No.1 control panel for Windows web hosting, and DotNETPanel, H-Sphere and other types have its advantage and disadvantage. We graded these types of control panels with different scores.

#Reliability

Reliability is the factor must be considered. It is evaluated by different criteria, we list these indicators below.

  • Uptime
  • Pre-install anti-virus software
  • Pre-install firewall
  • Network
  • Stable Datacenter

The best Windows web hosting listed above are ranked on these criteria, and all the 3 best windows web hosting truly meet the highest standards, which can powerful enough to run your website.

Pros and Cons of Windows Web Hosting

In fact, the Windows hosting solution is not as popular as the Linux hosting service. To give you a better understanding about this hosting type, we have listed some strong points and weak points of Windows web hosting.

The Strong Points

If your web host is a reliable and quality hosting provider, this hosting type can even achieve a more stable running than the normal Linux hosting solution.
It is surely multilingual that supports multiple scripting languages we have covered nowadays.
This hosting type is surely easy-to-use due to the immense popularity of Microsoft technologies. With it, there is no need to for you run the command line.
If you do not have enough experiences and knowledge of hosting, this type of hosting solution is arguably easier for you for the management tasks.

The Weak Points

Windows hosting is surely expensive. After all, the system of Windows is not free to use, but requires you to pay for the license fee. In addition, Windows can only be got from the official site or a few appointed agents, so there are almost no chances for you to get some lower charges or the attractive promotional campaign.
If you want to install some PHP based plugins, extensions and modules, the Windows hosting may fail to work well due to the compatibility issue.
Generally, PHP cannot work effectively with IIS as compared with Apache. For webmasters who are running a PHP based application, the 500 error might occur constantly.
Your web hosts may give you little flexibility for customizing and configuring your web servers.
If you want to use WordPress to set up and control your website, the Windows hosting service may fail to ensure you a good experience.



ASP.NET Hosting - ASPHostPortal.com :: How to solve page html getting wrongly appended to file being downloaded

clock April 18, 2016 21:24 by author Dan

Today while writing a small web application where I needed to download a datatable as csv file. I faced issue of page html getting wrongly appended to file being downloaded. I was using Response.Write to download file on client machine.

Solution to my problem was easy, I just needed to add an extra line telling content-length. Below is method that I finally ended up using.

        private void DownloadDataAsCsv(DataTable dt)
        {
            string tab = "";
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn dc in dt.Columns)
            {
                sb.Append(tab + dc.ColumnName);
                tab = ",";
            }
            sb.Append("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(tab + dr[i].ToString());
                    tab = ",";
                }
                sb.Append("\n");
            }
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.AddHeader("Content-Length", sb.ToString().Length.ToString());
            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



ASP.NET MVC - ASPHostPortal.com :: Internet & Web How to Fix Only One <configSections> Element Error in Web.Config

clock April 11, 2016 19:44 by author Armend

In this article you will learn the solution to the common error "Only one <configSections> element allowed".
Today I was working on Entity Framework and trying to add the connection string to the Web.Config to specify the database. I wrote the connection string like this: 

  <?xml version="1.0" encoding="utf-8"?>     
    <configuration>   
       <connectionStrings>  
          <add name="SQLConnect"
               connectionString="Data Source=SAHIL; Initial Catalog=Demo; Integrated Security=SSPI"
               providerName="System.Data.SqlClient" />  
       </connectionStrings>    
       <configSections>  
          <sectionnamesectionname="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
              Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
       </configSections>    
       :  
       :  
       :  
       :  
       :  
       :  
       :  
    </configuration>

When I run the application, I experienced a strange error that says: "Only one <configSections> element allowed. It must be the first child element of the root <configuration> element".

It took me some time to determine the cause of the error and how to fix it.
Error: "Only one <configSections> element allowed. It must be the first child element of the root <configuration> element".

If you read the error carefully, it states that only one <configSections> element is allowed inside the Web.config and it should be the first child element and placed at the top. The reason for the error is that I accidentally placed the <connectionStrings></connectionStrings> at the top over the <configSections></configSections> and by conventions this is a violation. So, to fix the error, I rearranged the elements and the error was fixed.

<?xml version="1.0" encoding="utf-8"?>   
<configuration>  
   <configSections>  
      <sectionnamesectionname="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
       Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
   </configSections> 
   <connectionStrings>  
      <add name="SQLConnect"
           connectionString="Data Source=SAHIL; Initial Catalog=Demo; Integrated Security=SSPI"
           providerName="System.Data.SqlClient" />
   </connectionStrings>   
   :  
   :  
   :  
   :  
   :  
   :  
   :  
</configuration>

Conclusion

Your feedback and constructive criticism is always appreciated, keep it coming. Until then try to put a ding in the Universe. 



ASP.NET Hosting - ASPHostPortal.com :: Adding Facebook Share Functionality to an ASP.NET Website with a Master Page

clock April 4, 2016 23:13 by author Armend

This article assumes the reader has experience developing web sites using ASP.NET, specifically using Master Pages. It also assumes a familiarity with Facebook. All sample code is in C#. After reading this article, you should be able to integrate Facebook Share with an ASP.NET web site, whether or not it contains a Master Page. I've chosen to illustrate this using a Master Page because it's a little more involved, and once you can do it with a Master Page, you should be able to do it without one as well.

 

What is Facebook Share, and how does it work?

First, let's review what Facebook Share actually is. Adding a Share widget to a web page allows a user to click on an icon which launches a Facebook Share dialog. If the user has a Facebook account, they can then share the web page on their Facebook "wall" with their friends on Facebook, adding comments if they so choose. Their friends will have the opportunity to share with their friends, and so on. In this way, a web page's exposure can increase dramatically in a very short time.
According to the Facebook web site's documentation there are five steps you need to take in order to integrate Share with a web page:

Step 1: Add a link to the Facebook Share application hosted by Facebook:

<a name="fb_share" type="button" href="http://www.facebook.com/sharer.php">Share</a>

Step 2: Add a script tag that points to a Javascript component hosted by Facebook:

<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>

Step 3: Add a meta tag containing the title of the page:

<meta name="title" content="This is the Title" />

Step 4: Add a meta tag containing a description of the page:

<meta name="description" content="This is a short summary of the page." />

Step 5: Add a link tag pointing to an image to be used as a logo:

<link rel="image_src" href="http://www.murrayhilltech.com/images/LogoColorNoText.jpg" />

The Problem

All well and good, but we were talking about doing this while using a Master Page. See the problem yet? Well, if all the pages in our site use a common Master Page, which presumably contains the head tag, which in turn contains all the meta tags and link tags, how do we specify different tag values for different pages? Therein lies the problem. The solution lies in the code-behind file.

The Solution

I've chosen to place the code for Steps 1 and 2 in the actual web page as opposed to the Master Page, since that will allow us the flexibility to place the Share widget in varying locations on each page should we care to do so. However, I'm going to accomplish this by inserting an empty asp:Label component in the desired location in the aspx file, and assigning the appropriate value to it in the Page_Load event in the code-behind file. I'm going to use the same asp:Label component to hold the code for both Steps 1 and 2:

// This code for the asp:Label component goes in the aspx file
<asp:Label ID="labelSteps_1_2" runat="server" Text=""></asp:Label>
// The code to populate the asp:Label component with the html and script code
// for Steps 1 and 2 should go in the code-behind file
labelSteps_1_2.Text = "<a name=\"fb_share\" type=\"button\"></a>" +
"<script src=\"http://static.ak.fbcdn.net/connect.php/js/FB.Share\" " +
"type=\"text/javascript\"></script>";

Next, we'll instantiate a couple of HtmlMeta objects to handle the meta tags in Steps 3 and 4, also in the Page_Load event:

HtmlMeta tag = new HtmlMeta();
tag.Name = "title";
tag.Content = "This is the Title";
Page.Header.Controls.Add(tag);
HtmlMeta tag = new HtmlMeta();
tag.Name = "description";
tag.Content = "This is a short summary of the page.";
Page.Header.Controls.Add(tag);
Finally, we'll add the logo in Step 5 in the same Page_Load event using an HtmlLink object:
 HtmlLink link = new HtmlLink();
link.href="http://www.murrayhilltech.com/images/LogoColorNoText.jpg";
link.Attributes["rel"] = "image_src";
Page.Header.Controls.Add(link);

Creating these elements dynamically in the code-behind file allows us to add them to the head element of the Master Page without ever actually modifying the Master Page. You can use this same method for pages and/or sites that don't make use of Master Pages.

Putting It All Together

The complete listing for the code-behind file is shown below. The only other change we made was to add that asp:Label control to the aspx file. Here's the code behind file:

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
namespace MHT_Web_Site
{
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
labelSteps_1_2.Text = "<a name=\"fb_share\" type=\"button\"></a>" +
"<script " +
"src=\"http://static.ak.fbcdn.net/connect.php/js/FB.Share\" " +
"type=\"text/javascript\"></script>";
HtmlMeta tag = new HtmlMeta();
tag.Name = "title";
tag.Content = "This is the Title";
Page.Header.Controls.Add(tag);
HtmlMeta tag = new HtmlMeta();
tag.Name = "description";
tag.Content = "This is a short summary of the page.";
Page.Header.Controls.Add(tag);
HtmlLink link = new HtmlLink();
link.href="http://www.murrayhilltech.com/images/LogoColorNoText.jpg";
link.Attributes["rel"] = "image_src";
Page.Header.Controls.Add(link);
}
catch (Exception ex)
{
// Handle the exception
}
}
}
}

I hope that this article helps you get started integrating Facebook with ASP.NET web sites. For more information, check Facebook's web site. The documentation there is not organized very well, but it's there if you dig for it.

 



ASP.NET Hosting - ASPHostPortal.com :: SEO Tips For ASP.NET URL’s

clock March 14, 2016 20:37 by author Armend

If you are building a new ASP.NET application, SEO has become a big factor in how you plan the structure / code of the site.  But quite an important part of the site which are often overlooked are the URL’s, and a lot of people do the basics which I’ll show below but there are a few common things people tend to miss or never thought could be a problem. I use ISAPI rewrite for most of my sites, which is an amazingly effective tool for sorting duplicate content and SEO issues which I’ll show below

 

  • Rewrite your URL’s to be useful / descriptive and stick away from using the old dynamic way

i.e. mypage.aspx?e=54&b=99
Google even tell you this is not ideal in the webmaster guidelines (See bottom of Design & Content Guidelines section) - http://www.google.co.uk/support/webmasters/bin/answer.py?answer=35769&hlrm=en_uk More...



ASP.NET MVC - ASPHostPortal.com :: 7 Tips for Developing a Secure ASP.NET Web Application

clock March 7, 2016 20:07 by author Armend

As the usage of the internet and the number of web applications over the internet have gone exponentially high there are bad people who continuously work around the clock to hack them. It may be for personal gain or just as an amateur act. Despite the intention of the bad guy the damage caused to the organization hosting the site or its users should be taken into account. As a professional web application developer it is a must to be aware of the best practices to follow in order to make the application more secure. In this article I will be listing and explaining my top 7 tips for developing a secure asp.net application.

Don’t Let Your Users be Victims of Click Jacking

Have you ever thought about someone framing your website onto theirs, making your users to be the victims of click jacking? Yes, the attackers can load your website onto their site in an iframe. They can then skillfully place their transparent controls over your website and fetch the PII information, user credentials, make them perform an unwanted task like exposing their financial information, etc.
In order to prevent that you will have to use a frame busting technique. The following script will not allow your website to be iframed. This can be placed in your master pages.

<script type="text/javascript" language="javascript">
        //Check if the top location is same as the current location
        if (top.location.hostname != self.location.hostname) {
            //If not then set the top to you current
            top.location.href = self.location.href;
        }
    </script>

In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
The header should be added in the global.asax application start event.  

protected void Application_Start(object sender, EventArgs e)
    {
                HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    }    

White List the Request URL

Though we have many techniques to perform the security preventions inside the application it is most important to prevent the bad data from being entered into your website at the first place. Most attacks happen through the query string values passed through the URL. It is a best security practice to define a common place like an HttpModule to white list the URL, i.e. sanitize the entire URL with a set of white listed characters and drop all the bad ones. It means you will not encourage any other characters apart from a white listed set defined in your application.
It is important for you to know that black listing is not a foolproof mechanism and it can be broken by the hackers easily.

Practice of Encoding the Data

While processing and sending, the data in the response that is fetched from outside the trust boundary should always be encoded. The type of encoding may differ based on the usage of the non-trusted data. For example perform an HtmlEncode for the data that is sent to the client page.

Label1.Text = Server.HtmlEncode(Request.QueryString["BadValue"]);

Encoding the data will make the XSS scripts inactive and prevent them from being executed. Microsoft has provided the AntiXss library, which provides more sophisticated encoding methods including the JavascriptEncode.
Using Cookies
As a web developer you should take utmost care while using cookies, which may open a back door for the hackers to get into your applications. Following are the best practices while using a cookie to store information.

1. Is your website is hosted under SSL? Then be sure to mark your cookies as secure. This will make them available only in the SSL transmissions.

             HttpCookie cookie = new HttpCookie("MySecureCookie");
        cookie.Value = "This is a PII information";
        cookie.Secure = true;

2. If your website is not SSL enabled then always encrypt the values using a strong encryption mechanism like AES 256 and then store them in the cookies.

Secure the Service Calls (WCF / Web Service)

Are you exposing WCF services through basicHttpBinding? Then think again because the messages transmitted over will be plain text and any intruder will be able to trap the requests and even simulate them easily. Use wsHttpBinding, which will transport the messages in an encrypted format, which makes the life of the intruder hard.
Though you make lots of protections for your WCF or web services it is a best practice to host the services under an SSL layer.

Never Deploy the Application with debug=”true”

It is strongly recommended not to deploy your applications in the production environment with compilation debug=”true” in your web.config. This will result in a big nightmare for performance and security of the application.
This may leak too much information for the attackers, for example the stack trace in the event of an unhandled exception and the debug trace information. Such exposure of the internals will be good bucks for the attackers.

<system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>

Thinking About Turning Off ViewStateMAC?

Turning off ViewStateMAC will create a security loophole in your asp.net application if you are using Viewstate on your web pages. The intruders will easily be able to intercept, read the 64 bit encoded values and modify them to do some bad things to your website. Having it turned on ensures that the viewstate values are not only encoded but also a cryptographic hash is performed using a secret key.

<pages enableViewStateMac="true"></pages>

I hope this article is useful for the developers who thrive at making their asp.net application an absolutely impossible place for the hackers to deal with.
Happy reading!



ASP.NET MVC - ASPHostPortal.com :: Simple Tips for ASP.NET MVC Model Binding

clock March 1, 2016 18:25 by author Armend

Tips for ASP.NET MVC Model Binding

Model binding in the ASP.NET MVC framework is simple. Your action methods need data, and the incoming HTTP request carries the data you need. The catch is that the data is embedded into POST-ed form values, and possibly the URL itself. Enter the DefaultModelBinder, which can magically convert form values and route data into objects. Model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment.    
Here are some tips on how to take advantage of model binding in your MVC projects.

 

Tip #1: Prefer Binding Over Request.Form

If you are writing your actions like this ..

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()

{
    Recipe recipe = new Recipe();
    recipe.Name = Request.Form["Name"];  
    // ...  
    return View();
}

Then you are doing it all wrong. The model binder can save you from using the Request and HttpContext properties – those properties make the action harder to read and harder to test. One step up would be to use a FormCollection parameter instead:
public ActionResult Create(FormCollection values)

{
    Recipe recipe = new Recipe();
    recipe.Name = values["Name"];               
    // ...        
    return View();
}

With the FormCollection you don’t have to dig into the Request object, and sometimes you need this low level of control. But, if all of your data is in Request.Form, route data, or the URL query string, then you can let model binding work its magic:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Recipe newRecipe)
{           
    // ...  
    return View();
}

In this example, the model binder will create your newRecipe object and populate it with data it finds in the request (by matching up data with the recipe’s property names). It’s pure auto-magic. There are many ways to customize the binding process with “white lists”, “black lists”, prefixes, and marker interfaces. For more control over when the binding takes place you can use the  UpdateModel and TryUpdateModel methods. Just beware of unintentional binding – see Justin Etheredge’s Think Before You Bind.

Tip #2: Custom model binders

Model binding is also one of the extensibility points in the MVC framework. If you can’t use the default binding behavior you can provide your own model binders, and mix and match binders. To implement a custom model binder you need to implement the IModelBinder interface. There is only method involved - how hard can it be?
public interface IModelBinder

{
    object BindModel(ControllerContext controllerContext,
                     ModelBindingContext bindingContext);
}

Once you get neck deep into model binding, however, you’ll discover that the simple IModelBinder interface doesn’t fully describe all the implicit contracts and side-effects inside the framework.  If you take a step back and look at the bigger picture you’ll see that model binding is but one move in a carefully orchestrated dance between the model binder, the ModelState, and the HtmlHelpers. You can pick up on some of these implicit behaviors by reading the unit tests for the default model binder.

If the default model binder has problems putting data into your object, it will place the error messages and the erroneous data value into ModelState. You can check ModelState.IsValid to see if binding problems are present, and use ModelState.AddModelError to inject your own error messages. See this very simple tutorial for more information on how ModelState and HtmlHelpers can work together to present validation errors to the user. 
If you scroll down the comments to post you’ll see code. If a conversion fails, the code will use ModelState.AddModelError to propagate the error. Both the controller action and the view can look in ModelState to see if there was a binding problem. The controller would need to check ModelState for errors before saving stuff into the database, while the view can check ModelState for errors to give the user validation feedback. One important note is that the HtmlHelpers you use in a view will require ModelState to hold both a value (via ModelState.SetModelValue) and the error (via AddModelError) or you’ll have runtime errors (null reference exceptions). The following code can demonstrate the problem:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection Form)
{
    // this is the wrong approach ...
    if (Form["Name"].Trim().Length == 0)
        ModelState.AddModelError("Name", "Name is required");
    return View();
}

The above code creates a model error without ever setting a model value. It has other problems, too, but it will create exceptions if you render the following view.

<%= Html.TextBox("Name", Model.Name) %>

Even though you’ve specified Model.Name as the value for the textbox, the textbox helper will see the model error and attempt to display the “attempted value” that the user tried to put in the model. If you didn’t set the model value in model state you’ll see a null reference exception.

Tip #3: Custom Model Binding via Inheritance

If you’ve decided to implement a custom model binder, you might be able to cut down on the amount of work required by inheriting from DefaultModelBinder and adding some custom logic. In fact, this should be your default plan until you are certain you can’t subclass the default binder to achieve the functionality you need. For example, suppose you just want to have some control over the creation of your model object. The DefaultModelBinder will create object’s using Activator.CreateInstance and the model’s default constructor. If you don’t have a default constructor for your model, you can subclass the DefaultModelBinder and override the CreateModel method.
Jimmy Bogard has an example of sub classing the DefaultModelBinder in his post titled “A Better Model Binder”.

Tip #4: Using Data Annotations for Validation

Brad Wilson explains everything beautifully in this post: DataAnnotations and ASP.NET MVC.
I encourage you to go read Brad’s post, but if you are in a hurry, here is a summary:

.NET 3.5 SP1 shipped a System.ComponentModel.DataAnnotations assembly that looks to play a central role as we move forward with the .NET framework. By using data annotations and the DataAnnotationsModelBinder, you can take care of most of your server-side validation by simply decorating your model with attributes.

public class Recipe
{
    [Required(ErrorMessage="We need a name for this dish.")]
    [RegularExpression("^Bacon")]
    public string Name { get; set; }

    // ...
}

The DataAnnotationsModelBinder is also a great sample to read and understand how to effectively subclass the default model binder.

Tip #5 : Recognize Binding and Validation As Two Phases

Binding is about taking data from the environment and shoving it into the model, while validation is checking the model to make sure it meets our expectations. These are different different operations, but model binding tends to blur the distinction. If you want to perform validation and binding together in a model binder, you can – it’s exactly what the DataAnnotationsModelBinder will do. You can also find samples like Automatic Model Validation with ASP.NET MVC, xVal, Castle, and a Custom Binder (John McDowall), and Enterprise Library Validation Application Block with MVC Binders (Steve Michelotti).  However, one thing that is often overlooked is how the DefaultModelBinder itself separates the binding and validation phases. If all you need is simple property validation, then all you need to do is override the OnPropertyValidating method of the DefaultModelBinder.

Tip #6: Binders Are About The Environment

Earlier I said that “model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment”. Generally, when we think of binder we think of moving data from the routing data and posted form values into the model. However, there is no restriction of where you find data for your model. The context of a web request is rich with information about the client. A good example is another Scott Hanselman post on automatically binding the user’s identity into a model see: IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing.

In Conclusion

Model binding is beautiful magic, so take advantage of the built-in magic when you can. I think the topic of model binding could use it’s own dedicated web site. It would be a very boring web site with lots of boring code, but model binding has many subtleties. For instance, we never even got to the topic of culture in this post.
Do you have any model binding tips?



About ASPHostPortal.com

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


Corporate Address (Location)

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

Sign in