Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

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

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 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?



ASP.NET Hosting - ASPHostPortal.com : Paging with ASP.NET Web API OData

clock October 20, 2015 08:58 by author Kenny

Paging with ASP.NET Web API OData

What is OData?

OData, short for Open Data Protocol, defines a protocol for the querying and updating of data utilizing existing Web protocols. OData is a REST-based protocol for querying and updating data and is built on standardized technologies such as HTTP, Atom/XML, and JSON. It is different from other REST-based web services in that it provides a uniform way to describe both the data and the data model. It is considered to be a flexible technology for enabling interoperability between disparate data sources, applications, services and clients.

Step by Step

When the API call returns the list of repositories in the body of the response as a JSON array:

[
  {
    "id": 1234,
    "name": "domain.com",
    "full_name": "user/domain.com",
    ...
  },
  {
    "id": 1111,
    "name": "test",
    "full_name": "user/test",
    ...
  }
]

It does not state the total number of records anywhere in the resulting JSON, not does it return the current page or the number of records per page which you requested. What it does however is to return the pagination information in the Link header of the request. So in the case of my API call above it returns the following Link header:

Link: <https://api.github.com/user/repos?page=5&per_page=2>; rel="next",
      <https://api.github.com/user/repos?page=8&per_page=2>; rel="last",
      <https://api.github.com/user/repos?page=1&per_page=2>; rel="first",
      <https://api.github.com/user/repos?page=3&per_page=2>; rel="prev"

So it allows you to request subsequent pages by requesting the URL in the Link header with the relation type (rel parameter value) of “next”. Also to get the total number of pages you will need to extract the page query parameter from the link with the relation type of last.

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 Hosting - ASPHostPortal.com :: Simple Way to Upload File in ASP.NET MVC 4.0 Razor

clock October 19, 2015 19:00 by author Dan

In this tutorial I will show you how to upload a files in ASP.NET MVC 4.0. So how to do this?? Lets get start. Create a new MVC 4.0 application and add a new controller, name it as HomeController. We will use Index ActionMethod to write the code to upload the file.

We need two ActionMethod named Index, one is for HttpGet and another for HttpPost. Within the HttpGet ActionMethod we don't need to write anything.

Lets create the View first. To create the View right click on the ActionMethod Index and click on the Add View option.

In the View write down the code.

@{
    ViewBag.Title = "Upload file";
}

<h2>Upload File</h2>
<h3 style="color: green">@ViewBag.Message</h3>
@using (Html.BeginForm("Index", "Home", FormMethod.Post
            , new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary();

    <input type="file" id="fileToUpload" name="file" />
    <span class="field-validation-error" id="spanfile"></span>

    <input type="submit" id="btnSubmit" value="Upload" />
}


Here we have taken a simple HTML file up loader and a submit button. Within the form we are calling the ActionMethod Index, which is present in HomeController. A ValidationSummary to show all validation message.

Now get back to the ActionMethod. Within the Index ActionMethod (HttpPost) write down the code.

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
      if (ModelState.IsValid)
      {
           if (file == null)
           {
              ModelState.AddModelError("File", "Please Upload Your file");
           }
           else if (file.ContentLength > 0)
           {
              int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
              string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
           if (!AllowedFileExtensions.Contains
(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
           {
                 ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
           }
           else if (file.ContentLength > MaxContentLength)
           {
                 ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
            }
            else
            {
                 var fileName = Path.GetFileName(file.FileName);
                 var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                 file.SaveAs(path);
                 ModelState.Clear();
                 ViewBag.Message = "File uploaded successfully. File path :   ~/Upload/"+fileName;
             }
         }
     }
     return View();
}


Before run this project don't forget to create a Upload folder within root directory, otherwise you will get an error.

HttpPostedFileBase file getting the file which you are uploading.

file.ContentLength : Size of the file
file.FileName : file name with extension

Now run your project and enjoying your uploading.

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 Hosting - ASPHostPortal.com : Dynamically Create Meta Description Using ASP.NET

clock October 13, 2015 08:37 by author Kenny

Dynamically Create Meta Description Using ASP.NET

HTML “meta description” allows us to describe web pages with short and sometimes elaborated details. Descriptions written inside the <meta> tag, must always to specific and are often limited to very few characters. Using Asp.Net, we can easily create “meta” descriptions dynamically, through code behind procedures, describing the contents of the page.

We all know how important it is to use meta tags when you’re building an internet web site. Meta tags provide metadata about the HTML document. They are not rendered in the browser but are used by search engines to parse web pages. The following article demonstrates how to store meta tags for each page in an XML file and how to use LINQ to read the XML data and dynamically create meta tags for each page in your website.

Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.

Add a Master Page to the project. Once that is completed, add a Web Content Page and select the newly created Master Page as the Master Page.

The next step is to create a new folder in the web site to demonstrate all pages in the website will have dynamic meta tags at runtime. Right click the website and choose Add > New Folder. Name the new folder ChildFolder. After this add a new Web Content Page to this folder. Leave the default name as this is not important.

Now that we have two pages in different folders, it’s now time to create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:

<metaTags>
 <tags pageName="/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword"></tag>
    <tag name="description" value="This is a description"></tag>
    <tag name="author" value="malcolm sheridan"></tag>
 </tags>
 <tags pageName="/ChildFolder/WebForm1.aspx">
    <tag name="keyword" value="This is a keyword for the child pages"></tag>
    <tag name="description" value="This is a description for the child pages"></tag>
    <tag name="author" value="malcolm sheridan for this page too"></tag>
 </tags>
</metaTags>

In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.

Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:

C#

XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
              .Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
               .Select(o => new
               {
                    Value = o.Attribute("value").Value,
                    Name = o.Attribute("name").Value
               });

VB.NET

Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})

For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page.   Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values.

Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:

C#

foreach (var item in metaTags)
{              
     HtmlMeta meta = new HtmlMeta();
     meta.Name = item.Name;
     meta.Content = item.Value;
     Page.Header.Controls.Add(meta);
}

VB.NET

For Each item In metaTags
       Dim meta As New HtmlMeta()
       meta.Name = item.Name
       meta.Content = item.Value
       Page.Header.Controls.Add(meta)
Next item

The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded, view the HTML source and you’ll see the meta tags have been added to the website.

MetaTags

Browsing to the second page and viewing the HTML source, you’ll find the meta tags have been added to the page but they’re different values from the previous page.

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 6 Hosting - ASPHostPortal :: Bootstrap Tree View in ASP.Net MVC

clock August 24, 2015 07:42 by author Kenny

Bootstrap Tree View in ASP.Net MVC

The ASP.NET MVC is an almost open source web application framework that implements the model–view–controller (MVC) pattern. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NETfeatures, such as master pages and membership-based authentication. Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites.

We create two classes, one is AuthorViewModel and another is BookViewModel. AuthorViewModel is the main class that has an association with the BookViewModel class. In other words each AuthorViewModel class object has a list of BookViewModel class objects. The following is the code snippet for the BookViewModel class. 

namespace TreeView.Models   
{  
    public class BookViewModel   
    {  
        public long Id   
        {  
            get;  
            set;  
        }  
        public string Title   
        {  
            get;  
            set;  
        }  
        public bool IsWritten   
        {  
            get;  
            set;  
        }  
    }  
}  

The following is the code snippet for the AuthorViewModel class.

using System.Collections.Generic;  
 
namespace TreeView.Models {  
    public class AuthorViewModel   
    {  
        public AuthorViewModel()   
        {  
            BookViewModel = new List < BookViewModel > ();  
        }  
        public int Id   
        {  
            get;  
            set;  
        }  
        public string Name   
        {  
            get;  
            set;  
        }  
        public bool IsAuthor   
        {  
            get;  
            set;  
        }  
        public IList < BookViewModel > BookViewModel   
        {  
            get;  
            set;  
        }  
    }  
}

Now we create a controller “HomeController” that has two action methods for both GET and POST requests. The action method's name is “Index”. The Get request action method returns a tree view in the UI whereas the POST request method gets the posted data from the UI. The following is the code snippet for HomeController.

using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
using TreeView.Models;  
 
namespace TreeView.Controllers  
{  
    public class HomeController : Controller  
    {  
        [HttpGet]  
        public ActionResult Index()  
        {  
            List<AuthorViewModel> model = new List<AuthorViewModel>();  
 
            AuthorViewModel firstAuthor = new AuthorViewModel  
            {  
                Id = 1,  
                Name = "User1",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=1,  
                        Title = "JQuery",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=1,  
                        Title = "JavaScript",  
                        IsWritten = false  
                    }  
                }  
            };  
 
            AuthorViewModel secondAuthor = new AuthorViewModel  
            {  
                Id = 2,  
                Name = "User2",  
                BookViewModel = new List<BookViewModel>{  
                    new BookViewModel{  
                        Id=3,  
                        Title = "C#",  
                        IsWritten = false  
                    }, new BookViewModel{  
                        Id=4,  
                        Title = "Entity Framework",  
                        IsWritten = false  
                    }  
                }  
            };  
            model.Add(firstAuthor);  
            model.Add(secondAuthor);  
            return View("Index", model);  
        }  
 
        [HttpPost]  
        public ActionResult Index(List<AuthorViewModel> model)  
        {  
            List<AuthorViewModel> selectedAuthors = model.Where(a => a.IsAuthor).ToList();  
            List<BookViewModel> selectedBooks = model.Where(a => a.IsAuthor)  
                                                .SelectMany(a => a.BookViewModel.Where(b => b.IsWritten)).ToList();  
            return View();  
        }  
    }  

The preceding code shows how books are associated with an author in the GET action method and how to get a selected tree node (authors and books) in the POST request. 

Bootstrap CSS is already added to the application but we write a new custom CSS for the tree view design. The following is the code snippet for the tree CSS.

.tree li {  
    margin: 0px 0;    
    list-style-type: none;  
    position: relative;  
    padding: 20px 5px 0px 5px;  
}  
 
.tree li::before{  
    content: '';  
    position: absolute;   
    top: 0;  
    width: 1px;   
    height: 100%;  
    right: auto;   
    left: -20px;  
    border-left: 1px solid #ccc;  
    bottom: 50px;  
}  
.tree li::after{  
    content: '';  
    position: absolute;   
    top: 30px;   
    width: 25px;   
    height: 20px;  
    right: auto;   
    left: -20px;  
    border-top: 1px solid #ccc;  
}  
.tree li a{  
    display: inline-block;  
    border: 1px solid #ccc;  
    padding: 5px 10px;  
    text-decoration: none;  
    color: #666;      
    font-family: 'Open Sans',sans-serif;  
    font-size: 14px;  
    font-weight :600;  
    border-radius: 5px;  
    -webkit-border-radius: 5px;  
    -moz-border-radius: 5px;  
}  
 
/*Remove connectors before root*/  
.tree > ul > li::before, .tree > ul > li::after{  
    border: 0;  
}  
/*Remove connectors after last child*/  
.tree li:last-child::before{   
      height: 30px;  
}  
 
/*Time for some hover effects*/  
/*We will apply the hover effect the the lineage of the element also*/  
.tree li a:hover, .tree li a:hover+ul li a {  
    background: #dd4814; color: #ffffff; border: 1px solid #dd4814;  
}  
/*Connector styles on hover*/  
.tree li a:hover+ul li::after,   
.tree li a:hover+ul li::before,   
.tree li a:hover+ul::before,   
.tree li a:hover+ul ul::before{  
    border-color:  #dd4814;  
}  
.tree-checkbox{  
    margin :4px !important;  
}  
 
   
.tree:before {  
    border-left:  1px solid #ccc;  
    bottom: 16px;  
    content: "";  
    display: block;  
    left: 0;  
    position: absolute;  
    top: -21px;  
    width: 1px;  
    z-index: 1;  
}  
 
.tree ul:after {  
    border-top: 1px solid #ccc;  
    content: "";  
    height: 20px;  
    left: -29px;  
    position: absolute;  
    right: auto;  
    top: 37px;  
    width: 34px;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
*:before, *:after {  
    box-sizing: border-box;  
}  
.tree {  
    overflow: auto;  
    padding-left: 0px;  
    position: relative;  

Now we create an Index view that renders in the browser and shows the tree view for the author and book. The following is the code snippet for the Index view.

@model List  
<TreeView.Models.AuthorViewModel>  
@section head{  
@Styles.Render("~/Content/css/tree.css")  
}  
    <div class="panel panel-primary">  
        <div class="panel-heading panel-head">Author Book Tree View</div>  
        <div id="frm-author" class="panel-body">  
@using (Html.BeginForm())  
{  
            <div class="tree">  
@for (int i = 0; i < Model.Count(); i++)  
{  
                <ul>  
                    <li>  
                        <a href="#">  
@Html.CheckBoxFor(model => model[i].IsAuthor, new { @class = "tree-checkbox parent", @id = @Model[i].Id })  
                            <label [email protected]>  
                                <strong>Author:</strong>  
@Html.DisplayFor(model => model[i].Name)  
                            </label>  
                        </a>  
                        <ul>  
@for (int j = 0; j < Model[i].BookViewModel.Count(); j++)  
{  
int k = 1 + j;  
@Html.HiddenFor(model => model[i].BookViewModel[j].Id)  
                            <li>  
                                <a href="#">  
@Html.CheckBoxFor(model => model[i].BookViewModel[j].IsWritten, new { @class = "tree-checkbox node-item", @iid = i + "" + j })  
                                    <label [email protected]@j>  
                                        <strong>Book @(k):</strong> @Html.DisplayFor(model => model[i].BookViewModel[j].Title)  
                                    </label>  
                                </a>  
                            </li>  
}  
                        </ul>  
                    </li>  
                </ul>  
}  
            </div>  
            <div class="form-group">  
                <div class="col-lg-9"></div>  
                <div class="col-lg-3">  
                    <button class="btn btn-success" id="btnSubmit" type="submit">  
Submit  
</button>  
                </div>  
            </div>  
}  
        </div>  
    </div>  
@section scripts{  
@Scripts.Render("~/Scripts/tree.js")  

Thereafter we create an important part of this example. We create the JavaScript file tree.js with the following code.

(function($)   
{  
    function Tree() {  
        var $this = this;  
        function treeNodeClick()   
        {  
            $(document).on('click', '.tree li a input[type="checkbox"]', function() {  
                $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked'));  
            }).on('click', '.node-item', function() {  
                var parentNode = $(this).parents('.tree ul');  
                if ($(this).is(':checked')) {  
                    parentNode.find('li a .parent').prop('checked', true);  
                } else {  
                    var elements = parentNode.find('ul input[type="checkbox"]:checked');  
                    if (elements.length == 0) {  
                        parentNode.find('li a .parent').prop('checked', false);  
                    }  
                }  
            });  
        };  
        $this.init = function() {  
            treeNodeClick();  
        }  
    }  
    $(function() {  
        var self = new Tree();  
        self.init();  
    })  
}(jQuery)) 

As in the preceding JavaScript code, the create tree view has the following features.

  1. When we select an author parent node then all the associated books will be selected.
  2. When a book is selected the associated parent author will be selected automatically.
  3. When all child book nodes are selected for a parent author node then the parent node will be selected.
  4. When the parent node is unselected then the child books will be automatically unselected.

Figure 1 shows the parent child (author-book) tree view.



Why ASPHostPortal.com is the Best ASP.NET 4.5.2 Hosting in South Africa?

clock June 10, 2014 12:14 by author Ben

ASPHostPortal.com, a Microsoft Golden hosting partner has been offering well priced Windows and ASP.NET hosting plans for many years. Founded in 2008 and operated in New York, US. ASPHostPortal.com has become an important resource for cutting-edge, high-value hosting solutions. We're a proudly the company with over 35.000 satisfied customers and a reputation as one of the top internet service providers. We also offers low priced enterprise-level hosting plans by focusing their resources on needs by ASP.NET Windows’s developers.

ASPHostPortal.com claims to be proud of our management staff who have years of experience working in web hosting industry. ASPHostPortal’s aim is to offer the best web hosting value to our clients by offering products and solution in an efficient and effective way.

We support almost all the latest ASP.NET technology and provides plenty of server resources for every hosting account. Below are the list of key features, but definitely it provides more:

  • Unlimited Website
  • Latest MS SQL Server 2012 R2
  • ASP.NET 4.5.2/4.5.1/4.5/3.5/2.0
  • IIS 8 with Full trust allowed
  • SmarterMail email System
  • Web-based Plesk Panel hosting
  • Unlimited FTP, Sub domains, mail boxes
  • PHP, MySQL 5 Database

With ASPHostPortal.com, customers are always able to run websites with at least 99.9% uptime. ASPHostPortal has 3 top data centers located in New York, USA, Europe and Singapore both of which are equipped with hundreds of 100% Dell servers with 64 bit operating system, dual quad processors, 32 GB Ram and RAID 10 disk arrays. And also our system still reliable in South Africa. Part of our success is down to the fact that we've partnered with one of the biggest network providers in Africa to ensure the quickest and most reliable internet experience for our customers.

Why ASPHostPortal.com is the Best ASP.NET Hosting in South Africa?

Reliable Server and Data Center

We now operate 5 different data centers, namely Seattle data center, Houston data center, Washington DC data center, Amsterdam (The Netherland) data center and the newest Singapore (Asia) data center.

Fastest Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

World Class PLESK Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account.

Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business.

In addition, ASPHostPortal.com technicians are monitoring the data centers and server 24×7, so we are able to find and resolve sudden issues to avoid any sudden interruption. The following chart shows the real ASPHostPortal.com uptime in the past 30 days.

ASPHostPortal.com also provide our customers a chance to make some money by providing reseller hosting accounts. You can purchase our reseller hosting account, host unlimited websites on it and also have the chance to sell some of your hosting space to others. This can be one of the easiest ways of making some money online. You do not need to worry about hosting stuff as we will take care of all the hosting needs of your clients.



Cheap ASP.NET MVC 5.1.1 Hosting:: How to Integrated PayPal with ASP.NET MVC

clock June 9, 2014 11:26 by author Ben

This article discusses integration of PayPal payment gateway in asp.net MVC  web application. PayPal is an online payment service that allows you to pay for purchases, receive payments, or to send and receive money. To receive these services, a person must submit various financial details to PayPal, such as credit card number, transmission can be done by mail. Thereafter, transactions are conducted without having to disclose financial details, an email address and a password is sufficient.

We will look at a simple scenario of taking a user to a PayPal payment page to checkout.

1. Setting up the development tools

  • Creating a PayPal Account

You will need a sandbox account to test your transactions. The sandbox account is separate from a regular account and is all you need to sign up to before you develop and test your code.

  • PayPal Account Settings

It's good practice to put things like account settings in the web.config. The code in this article will access these settings. You must change the sandbox setting to False when using regular account details:

<appSettings>     
   <add key="PayPal:Sandbox" value="True" />
   <add key="PayPal:Username" value="*" />
   <add key="PayPal:Password" value="*" />
   <add key="PayPal:Signature" value="*" />
   <add key="PayPal:ReturnUrl" value="http://www.asphostportal.com" />
   <add key="PayPal:CancelUrl" value="http://www.asphostportal.com" />
</appSettings>


2. Creating the button
Now, you will have to create two Views in a Controller, one where you have the button and one where you have the validation mechanism. Let’s start with the button! Put the code below into any View. My View name is IPN in the User controller.
<!-- When you are done with all testing and want to change to the real PayPal, use following instead-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<!-- end of Real PayPal example-->
 
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
    <fieldset>
        <input class="full-width" type="hidden" name="business" value="<!--enter the Business account email here-->">
        <input type="hidden" name="cmd" value="_xclick">
        <input type="hidden" name="item_name" value="The unlimited music download subscription">
        <input type="hidden" name="amount" value="9">
        <input type="hidden" name="no_shipping" value="1">
        <input type=hidden name=RETURNURL
               value="http://example.com/User/IPN">
        <input type="hidden" name="return" value="http://example.com/User/IPN">
        <input type="hidden" name="notify_url" value="http://example.com/User/IPN">
 
        <button type="submit">Order now!</button>
    </fieldset>
</form>


3. Processing the information returned by PayPal

The example code is based on this code. Please take a look at it to see how it is done with several variables.

Now you need to create a new View in the controller, called IPN. Insert the following code:
public ActionResult IPN()
{
 
    var order = new Order(); // this is something I have defined in order to save the order in the database
 
    // Receive IPN request from PayPal and parse all the variables returned
    var formVals = new Dictionary<string, string>();
    formVals.Add("cmd", "_notify-synch"); //notify-synch_notify-validate
    formVals.Add("at", "this is a long token found in Buyers account"); // this has to be adjusted
    formVals.Add("tx", Request["tx"]);
 
    // if you want to use the PayPal sandbox change this from false to true
    string response = GetPayPalResponse(formVals, false);
 
    if (response.Contains("SUCCESS"))
    {
        string transactionID = GetPDTValue(response, "txn_id"); // txn_id //d
        string sAmountPaid = GetPDTValue(response,"mc_gross"); // d
        string deviceID = GetPDTValue(response, "custom"); // d
        string payerEmail = GetPDTValue(response,"payer_email"); // d
        string Item = GetPDTValue(response,"item_name");
 
        //validate the order
        Decimal amountPaid = 0;
        Decimal.TryParse(sAmountPaid, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out amountPaid);
 
        if (amountPaid == 9 )  // you might want to have a bigger than or equal to sign here!
        {
            if (orders.Count(d => d.PayPalOrderRef == transactionID) < 1)
            {
                //if the transactionID is not found in the database, add it
                //then, add the additional features to the user account
            }
            else
            {
                //if we are here, the user must have already used the transaction ID for an account
                //you might want to show the details of the order, but do not upgrade it!
            }
            // take the information returned and store this into a subscription table
            // this is where you would update your database with the details of the tran
 
            //return View();
 
        }
        else
        {
            // let fail - this is the IPN so there is no viewer
            // you may want to log something here
            order.Comments = "User did not pay the right ammount.";
 
            // since the user did not pay the right amount, we still want to log that for future reference.
 
            _db.Orders.Add(order); // order is your new Order
            _db.SaveChanges();
        }
 
    }
    else
    {
        //error
    }
    return View();
}
 
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
 
    string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
        : "https://www.paypal.com/cgi-bin/webscr";
 
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
 
    // Set values for the request back
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
 
    byte[] param = Request.BinaryRead(Request.ContentLength);
    string strRequest = Encoding.ASCII.GetString(param);
 
    StringBuilder sb = new StringBuilder();
    sb.Append(strRequest);
 
    foreach (string key in formVals.Keys)
    {
        sb.AppendFormat("&{0}={1}", key, formVals[key]);
    }
    strRequest += sb.ToString();
    req.ContentLength = strRequest.Length;
 
    //for proxy
    //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
    //req.Proxy = proxy;
    //Send the request to PayPal and get the response
    string response = "";
    using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
    {
 
        streamOut.Write(strRequest);
        streamOut.Close();
        using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
        {
            response = streamIn.ReadToEnd();
        }
    }
 
    return response;
}
string GetPDTValue(string pdt, string key)
{
 
    string[] keys = pdt.Split('\n');
    string thisVal = "";
    string thisKey = "";
    foreach (string s in keys)
    {
        string[] bits = s.Split('=');
        if (bits.Length > 1)
        {
            thisVal = bits[1];
            thisKey = bits[0];
            if (thisKey.Equals(key, StringComparison.InvariantCultureIgnoreCase))
                break;
        }
    }
    return thisVal;
 
}


Please note down the Activation token found in the Buyers account in Profile>My Selling Tools>Website preferences> Update. Then, enable auto return and payment data transfer. There, you will also find the Activation token which you should add to:
formVals.Add("at", "this is a long token found in Buyers account");

 

Why you should choose ASPHostPortal.com for your Cheap ASP.NET MVC 5.1.1 Hosting?

  1. Daily Backup Service

    We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it.

  2. Experts in ASP.NET MVC 5.1.1 Hosting

    Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostPortal.com

  3. Excellent Uptime Rate

    Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP.

  4. 24/7-based Support

    We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers.

  5. Advanced Technology

    ASPHostPortal.com provides various editions of the important ASP.NET MVC frameworks, including basic ASP.NET MVC, ASP.NET MVC 2, ASP.NET MVC 3, ASP.NET MVC 4, ASP.NET MVC 5, ASP.NET MVC 5.1 and the latest ASP.NET MVC 5.1.1 . All of these frameworks enable customers to have a high level of flexibility and avoid compatible issue.



Looking For Cheap and Best YetAnotherForum Hosting?

clock May 30, 2014 07:58 by author Ben

ASPHostPortal windows hosting is compatible with the YetAnotherForum.NET. We offer YetAnotherForum.NET based hosting plan from just $5/month (see our YetAnotherForum.NET Hosting Plan).

The ASPHostPortal.com ASP.NET hosting platform is compatible with YetAnotherForum (YAF) Forum application. YetAnotherForum.NET (YAF) is a Open Source discussion forum or bulletin board system for web sites running ASP.NET.
It is 100% written in C#, YAF is a combination of Open Source, Microsoft's .NET platform and an international collaboration of the .NET developer community. ASP.NET forum solutions are not so much on the market and YAF is absolutely the best solution.

The YAF project is lead by Jaben Cargman of Tiny Gecko and grows and changes daily. YAF runs on any hosting server that's configured with Asp.net 2.0+ and SQL Server service. Some key features for YetAnotherForum:

  • Licensed under GPL
  • Web Based Administration
  • Unlimited number of boards forums and categories
  • Template-based design
  • Unicode (UTF-8) encoding
  • DotNetNuke, Umbraco, MojoPortal Modules

YAF is actually a simple support by ASPHostPortal ASP.NET hosting service. Besides YAF, ASPHostPortal.com is golden partner over lots of asp.net projects. By powering thousands of popular .net web applications, ASPHostPortal.com is official recommendation for such softwares.

You can get YetAnotherForum.NET CMS Hosting installed with a click of a mouse at ASPHostPortal.com. Here are 5 reasons why we are the best:

Easy to Use Tools - ASPHostPortal.com use World Class Plesk Control Panel that help you with single-click YetAnotherForum.NET CMS installation.
Best Server Technology - The minimal specs of our servers includes Intel Xeon Dual Core Processor, RAID-10 protected hard disk space with minimum 8 GB RAM. You dont need to worry about the speed of your site.
Best Programming Support - ASPHostPortal.com hosting servers come ready with the latest PHP version. You can get access directly to your MySQL from our world class Plesk Control Panel.
Best and Friendly Support - Our customer support will help you 24 hours a day, 7 days a week and 365 days a year to assist you.
Uptime & Support Guarantees - We are so confident in our hosting services we will not only provide you with a 30 days money back guarantee, but also we give you a 99.9% uptime guarantee.



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