ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: JavaScript style setTimeout and setInterval in C#

clock January 31, 2017 05:05 by author Armend

I found JavaScript setTimeout and setInterval functions quite handy for timer like functionality and some time wish I could use that in C# too. In an earlier post I create a C# like timer functionality in JavaScript. Now, I want to do opposite i.e. implement JavaScript setTimeout and setInterval like functionality in C#.
This is can be done very easily using Lamda expressions and Timer. Look at the below utility class -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DailyCoding.EasyTimer
{
    public static class EasyTimer
    {
        public static IDisposable SetInterval(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }

        public static IDisposable SetTimeout(Action method, int delayInMilliseconds)
        {
            System.Timers.Timer timer = new System.Timers.Timer(delayInMilliseconds);
            timer.Elapsed += (source, e) =>
            {
                method();
            };

            timer.AutoReset = false;
            timer.Enabled = true;
            timer.Start();

            // Returns a stop handle which can be used for stopping
            // the timer, if required
            return timer as IDisposable;
        }
    }
}

To use setTimeout this you can simply do -

EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms delay

}, 1000);

The code will run after 1000 ms delay similarly like JavaScript setTimeout. The function also returns a handle. If you want clearTimeout like functionality, then the simply dispose off the handle.

var stopHandle = EasyTimer.SetTimeout(() =>
{
    // --- You code here ---
    // This piece of code will once after 1000 ms

}, 1000);


// In case you want to clear the timeout

stopHandle.Dispose();
Similarly you can use setInterval as -
EasyTimer.SetInterval(() =>
{
    // --- You code here ---
    // This piece of code will run after every 1000 ms

}, 1000);

and SetInterval also returns a stop handle which you can use for clearInterval like functionality. Just dispose off the handle -

var stopHandle = EasyTimer.SetInterval(() =>
    {
        // --- You code here ---
        // This piece of code will run after every 1000 ms
        // To stop the timer, just dispose off the stop handle

    }, 1000);


// In case you want to clear the interval
stopHandle.Dispose();

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its 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. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.




ASP.NET Hosting - ASPHostPortal.com :: Creating Help Desk Web Application using ASP.NET Core

clock January 17, 2017 05:28 by author Armend

Suppose you work for a small to midsize company that employs 50-100 workers. The Help Desk -- a subsidiary of the Information Services Division -- is in charge of trouble tickets regarding general PC issues such as email, viruses, network issues, etc. Initially, the Help Desk team stored this information in Excel spreadsheets, but as the company has grown, managing these spreadsheets has become tedious and time consuming.

The Help Desk has asked you to devise a more efficient solution that could be developed internally, saving the company money. As you start to think about it, the following requirements are apparent: fields for the submitter's first and last name, as well as their email address. You'll also need combo boxes for indicating ticket severity (low, medium, high), department, status (new, open, resolved), employee working on the issue, as well as an area for comments. Of all the solutions available, creating an internal help desk Web application with ASP.NET is relatively simple.

In the following article, we'll see how to implement these features in an ASP.NET help desk Web application using a database-driven approach,
Creating the JavaScript File
Because creating the JavaScript file is the easiest of the work left, we'll do this next. From the Solution Explorer, follow these steps:

Creating the Help Desk Class

Now that we have our data coming in, we need to be able to record a help desk ticket submission. We need to create an event handler in a class to handle it. Let's first create a help desk class by doing the following:

  •     Right click the project solution.
  •     Choose Add>New Item.
  •     In the Add New Item window, select Class.cs.
  •     In the name text field, type "HelpDesk" and then click Add.

Double click HelpDesk.cs from the Solution Explorer, which will show the empty class as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

We need to import three libraries as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace HelpDesk
{
    public class HelpDesk
    {
    }
}

The first library (System.Data) allows us to work with stored procedures in ADO.NET, the second (System.Configuration) allows us to reference a connection key from configuration file and the last (System.Data.SqlClient) one allows us to connect to SQL Server.


About ASPHostPortal.com:


ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: Repair Dropdown Boxes in ASP.NET Datagrids

clock December 6, 2016 07:43 by author Armend

Introduction

Today, I will explain Step by Step to Repair Dropdown Boxes in ASP.NET Datagrids. Alright, this issue isn't silverlight, yet I did experience it in my day work. Truth be told, I've experienced it a few times, so I thought I would compose it up so I can discover it once more.

 

Error

You compose a page that contains an updatable datagrid, which, when in Editmode, contains a dropdown rundown containing lookup things. The Dropdownbox does not populate, and (later when you get it working) the correct listitem is not chosen.

Cause

Since the Dropdownbox down not existing when the page loads, there is nothing to tie.

Step by Step

You need to append your occasions to some non-standard page occasions to get it to work. The pertinent piece of the .aspx page is underneath (placed this in your datagrid)

<asp:TemplateColumn HeaderText=”Tactic Category”>

<HeaderStyle Font-Size=”Large” Font-Bold=”true” />
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,”TacticCatName”)%>
</ItemTemplate>
<EditItemTemplate>
<%–Notice the GetCat() routine here as the datasource.–%>
<asp:DropDownList id=”ddTacticCatList” runat=”server” DataSource=”<%# GetCat() %>” DataTextField=”TacticCatName” DataValueField=”TacticCatID”>
</asp:DropDownList>
</EditItemTemplate>

</asp:TemplateColumn>

Your code-behind page should look like this (in C#)


private void MainCode()
{
string strID = Request.QueryString["id"].ToString();
//custom code to get the relevant dataset for the entire datgrid
DataSet ds = LMR.TacticSubCatList(strID);
//custom code to bind to the datagrid
Utility.DGDSNullCheck(ds, dgTacticSubCatList, lblTacticSubCatList, “There are no tactic subcategories in the database at this time.”);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MainCode();
}
}

protected void dgTacticSubCatList_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//grab the index
dgTacticSubCatList.EditItemIndex = e.Item.ItemIndex;
MainCode();
}

protected void dgTacticSubCatList_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//get the id value of the selected datagrid item
int intTacticSubCatID = (int)dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex];

//this gets our textbox, also in the datagrid
TextBox EditText = null;
EditText=(TextBox)e.Item.FindControl(“tbTacticSubCatName”);
string strEditText = Convert.ToString(EditText.Text);

//get the value of our dropdown list
DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
string strTacticCatID = dd.SelectedValue.ToString();
//do our database update
LMR.TacticSubCatEdit(intTacticSubCatID.ToString(),strTacticCatID,strEditText);
//reset the datagrid
dgTacticSubCatList.EditItemIndex = -1;
//give feedback and rebind
lblFeedback.Text = “Your changes have been applied.”;
MainCode();
}

protected void dgTacticSubCatList_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dgTacticSubCatList.EditItemIndex = -1;
MainCode();
}
protected DataTable GetCat()
{
//here is where we get the dataset to populate the dropdown list – it does have to go in an independant function
DataSet ds = LMR.TacticCatList();
return ds.Tables[0];
}

protected void dgTacticSubCatList_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
//we set the selcted index in the ItemDataBound event
string strID = Request.QueryString["id"].ToString();
string strSubCatID = dgTacticSubCatList.DataKeys[(int)e.Item.ItemIndex].ToString();
Holder.TacticSubCat tsc = LMR.GetTacticSubCat(strSubCatID);
DropDownList dd = (DropDownList)e.Item.FindControl(“ddTacticCatList”);
dd.SelectedIndex =dd.Items.IndexOf(dd.Items.FindByValue(strID));
}
}

 

It's as simple as that. Hopefully this article will be usefull for you.

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its 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. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice



ASP.NET Hosting - ASPHostPortal.com :: Using select tag helper in ASP.NET MVC 6

clock October 11, 2016 20:12 by author Armend

Using select tag helper in ASP.NET MVC 6

Tag Helpers were introduced in ASP.NET MVC 6, and one the tag helper is Select tag helper. Select tag helper is used to generate dropdown list and it’s an alternative for Html.DropDownList. In this post, we will see how to use select tag helper and how to bind select tag helper to model data or enum values. Also read How to use image tag helper in ASP.NET Core MVC 1.0

How to use select tag helper in ASP.NET MVC 6?

Select tag helper uses asp-for which extracts the name of the specified model property into the rendered HTML. For example,

<select asp-for="TimeZone"></select>

Then your model should have a property defined “TimeZone”.

public class RegisterViewModel
{
    [Display(Name = "TimeZone")]
    public string TimeZone { get; set; }
}

But this will be a empty list without any option as we didn’t define any options for the select list. There are couple of ways to add options to select tag helper.

Define directly in Markup

You can directly define your options in markup.

<select asp-for="TimeZone">
   <option value="-12">(UTC-12:00)</option>
   <option value="-11">(UTC-11:00)</option>
</select>

And selected option will be marked as “selected” when the page will be rendered.

Define using a data source

It’s a most common scenario when you want to bind your select list options either from any database table or any server side list. In such case, asp-items tag helper attribute should be used.

<select asp-for="TimeZone" asp-items="ViewBag.TimeZoneList"></select>

Now, we need to put TimeZoneList in ViewBag. Let’s first create a List and add options to it.

public List<SelectListItem> TimeZoneList { get; private set; }
public RegisterViewModel()
{
     TimeZoneList = new List<SelectListItem>();
     TimeZoneList.Add(new SelectListItem
     {
         Text = "Select",
         Value = ""
     });
     foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
     {
          TimeZoneList.Add(new SelectListItem
          {
               Text = z.DisplayName,
               Value = z.Id
          });
     }
}

And from your controller, add the list to ViewBag.

// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
    RegisterViewModel rs = new RegisterViewModel();
    ViewBag.TimeZoneList = rs.TimeZoneList;
    return View();
}

Bind enum values

You can also bind enum values to select list.

public List<SelectListItem> PriorityList { get; private set; }
public RegisterViewModel()
{
    PriorityList = new List<SelectListItem>();
    PriorityList.Add(new SelectListItem
    {
       Text = "Select",
       Value = ""
    });
    foreach (ePriority eVal in Enum.GetValues(typeof(ePriority)))
    {
      PriorityList.Add(new SelectListItem { Text = Enum.GetName(typeof(ePriority), eVal), Value = eVal.ToString() });
    }
}

You can also use a static function to bind the select list, instead of using ViewBag.

public static List<SelectItemList> GetTimeZoneList()
{
    List<SelectListItem> TimeZoneList = new List<SelectListItem>();
    TimeZoneList.Add(new SelectListItem
    {
       Text = "Select",
       Value = ""
    });
    foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
     {
          TimeZoneList.Add(new SelectListItem
          {
               Text = z.DisplayName,
               Value = z.Id
          });
     }
    return TimeZoneList;
}

As static functions can be accessed only via classname. So in our case, it would be RegisterViewModel.GetTimeZoneList()

<select asp-for="TimeZone"
   asp-items="RegisterViewModel.GetTimeZoneList()"></select>

Summary

In this post, I demonstrated how to use select tag helper and how to bind it using enum values as well as other data source. And that covers all the functionality provided by the select tag helper in MVC 6.

 

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its 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. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Asp.net Export Excel Show/Hide Loading image

clock August 2, 2016 19:58 by author Armend

This Tip will explain how to hide the loading gif image after the file is downloaded . It  will be helpful when we are using  Response Object to export the excel or any other file format.

 

Sometimes while  downloading an excel or any file from an Asp application, it might take some time to Generate the File, the delay  depends on many factors( file size, loops, server bandwidth etc ). So we repesent the File Generation process using a rotating GIF image next to the button.
But when we are using Response object we wont get the event after the file is downloaded to the browser, in this case it will be difficult to hide the loading gif which is being shown on the screen

The below steps will guide how to  Show the Gif while Generating and hide it once the file is completly downloaded.

Hide the GIF after download

  • When the download button is clicked, show the loading gif image using onclicentClick event and CSS properties
  • On the Client click event invoke a Javascript method which Contains a  Setinterval  object that moniters  for our cookie (created in c# Response object).
  • In the Server button click Event Create an HttpCookie and append it to the Respone object.
  • So when the File is downloaded completly the Cookie is added to the Page, Now the SetInterval function will capture the cookie and Hides the Loading Gif image.
  • Note: whenever the download button is clicked, previous cookie has to be deleted.

Using the code

protected void btnExportExcel_Click(object sender, EventArgs e)
          {
            DataTable dt = new DataTable();
            dt = GetDataFromDb();
            System.Threading.Thread.Sleep(3000); // for testing purpose to create 3 seconds delay
            //Create a temp GridView
            GridView gv = new GridView();
            gv.AllowPaging = false;
            gv.DataSource = dt;
            gv.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gv.RenderControl(hw);
            // Append cookie
            HttpCookie cookie = new HttpCookie("ExcelDownloadFlag");
            cookie.Value = "Flag";
            cookie.Expires = DateTime.Now.AddDays(1);
            Response.AppendCookie(cookie);
            // end
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }

HTML/ASPX Code

<table>
            <tr>
                <td>
                    <asp:Button Text="Download" ID="btnExportExcel" OnClientClick="jsShowHideProgress();" runat="server" OnClick="btnExportExcel_Click" />
                </td>
                <td>
                    <img style="display: none" id="imgloadinggif" src="Images/loading.gif" alt="loading.." />
                </td>
            </tr>
        </table>

Javascript Code:

function jsShowHideProgress() {
    setTimeout(function () { document.getElementById('imgloadinggif').style.display = 'block'; }, 200);
    deleteCookie();

    var timeInterval = 500; // milliseconds (checks the cookie for every half second )

    var loop = setInterval(function () {
        if (IsCookieValid())
        { document.getElementById('imgloadinggif').style.display = 'none'; clearInterval(loop) }

    }, timeInterval);
}

// cookies
function deleteCookie() {
    var cook = getCookie('ExcelDownloadFlag');
    if (cook != "") {
        document.cookie = "ExcelDownloadFlag=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    }
}

function IsCookieValid() {
    var cook = getCookie('ExcelDownloadFlag');
    return cook != '';
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: Tips To Use BackgroundWorker in C#

clock July 26, 2016 19:54 by author Armend

How To Use BackgroundWorker in C#

BackgroundWorker is the class in System.ComponentModel which is used when you need to do some task on the back-end or in different thread while keeping the UI available to users (not freezing the user) and at the same time, reporting the progress of the same.

Using the Code

Backgroundworker has three event handlers which basically takes care of everything one needs to make it work.

  • DoWork - Your actual background work goes in here
  • ProgressChanged - When there is a progress in the background work
  • RunWorkerCompleted - Gets called when background worker has completed the work.

I have created a sample WPF application which demonstrates how to use the background worker in C#.

<ProgressBar x:Name="progressbar"
 HorizontalAlignment="Left" Height="14"
 Margin="191,74,0,0" VerticalAlignment="Top"
 Width="133"/>
<Button x:Name="button" Content="Button"
 HorizontalAlignment="Left"
 Margin="249,97,0,0" VerticalAlignment="Top"
 Width="75" Click="button_Click"/>

On Window initialization, I am creating a new object of BackgroundWorker and registering the event handlers for the same.

BackgroundWorker bg;
public MainWindow()
{
InitializeComponent();
bg = new BackgroundWorker();
bg.DoWork += Bg_DoWork;
bg.ProgressChanged += Bg_ProgressChanged;
bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
bg.WorkerReportsProgress = true;
}

Here is the implementation of all three event handlers.

private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Task completed");
}
private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressbar.Value += 1;
//label.Content = e.ProgressPercentage;
}
private void Bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i &amp;lt;= 10; i++)
{
Thread.Sleep(1000); //do some task
bg.ReportProgress(0);
}
}

In order to make this stuff work, you need to trigger the DoWork event and for that, I am using button click event.

private void button_Click(object sender, RoutedEventArgs e)
   {
           progressbar.Value = 0;
           progressbar.Maximum = 10;
           bg.RunWorkerAsync();
   }

It is a very basic example of background worker, but it is good to start with. One must be wondering how it is updating the progress bar if it is working in the background.
Well, the ProgressChanged event handler runs on UI thread whereas DoWork runs on application thread pool. That's why despite running in the background on different thread, it is not freezing the UI and updating the progressbar upon making progress.

 

Best ASP.NET Core 1.0 Hosting Recommendation

ASPHostPortal.com provides its 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. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.

 



ASP.NET Hosting - ASPHostPortal.com :: ASP.NET Seo Tips

clock June 21, 2016 20:41 by author Armend

When running an online business, majority of our focus is on the design, architecture of the website and how efficiently it displays our product. These are not the only things that are required to target the infinite Internet audience. One need to keep in mind that the main source of audience come from search engines such as Google, Yahoo, Bing and others. So the application or the website should be able to follow simple rules and handle your business efficiently. ASP.NET application is spreading rapidly and if you are using an ASP.NET website few simple guidelines has to be considered. The below mentioned points need to be implemented:

 

Page Titles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  •     External stylesheets and not inline CSS
  •     -js files instead of inline JavaScript
  •     HTML comments is not encouraged
  •     Avoid massive line breaking
  •     Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed.

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.

 



ASP.NET Hosting - ASPHostPortal.com :: Tips to configure Kestrel URLs in ASP.NET Core RC2

clock June 10, 2016 19:44 by author Armend

How to configure Kestrel URLs in ASP.NET Core RC2

ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers. Additionally, developers and third party software vendors can create custom servers to host their ASP.NET Core apps.

Prior to the release of ASP.NET Core RC2 Kestrel would be configured as part of the command bindings in project.json:

"commands": {
  "web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://localhost:60000;http://localhost:60001;"
},

If no URLs were specified, a default binding of http://localhost:5000 would be used.

As of RC2 we have a new unified toolchain (the .NET Core CLI) and ASP.NET Core applications are effectively just .NET Core Console Applications. They have a single entry point where we programatically configure and run the web host:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

Here we're adding support for both Kestrel and IIS hosts via the appropriate extension methods.
When we upgraded SaasKit to RC2 we used the UseUrls extension to configure the URLs Kestrel would bind to:

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:60000", "http://localhost:60001")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

I didn't really like this approach as we're hard-coding URLs. Fortunately it's still possible to load the Kestrel configuration from an external file.
First create a hosting.json file in the root of your application with your required bindings. Separate multiple URLs with a semi-colon:

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Next update Program.cs to load your hosting configuration, then use the UseConfiguration extension to pass the configuration to the WebHostBuilder:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    host.Run();
}

If you're launching Kestrel with Visual Studio you may also need to update launchSettings.json with the correct launchUrl:

"RC2HostingDemo": {
  "commandName": "Project",
  "launchBrowser": true,
  "launchUrl": "http://localhost:60000/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
}

Now the web application will listen on the URLs configured in hosting.json:

Hosting environment: Development
Content root path: C:\Users\ben\Source\RC2HostingDemo\src\RC2HostingDemo
Now listening on: http://localhost:60000
Now listening on: http://localhost:60001
Application started. Press Ctrl+C to shut down.



ASP.NET Hosting - ASPHostPortal.com :: ASP.NET MVC vs ASP.NET - Which is better?

clock June 3, 2016 22:54 by author Dan

When developers start to build new web projects they face two options- either using ASP.NET MVC framework or ASP.NET web forms. These days, more and more companies are however choosing the MVC based framework to revise their existing sites significantly or to develop new ones. The framework has a multitude of benefits as well as technical goodies which have made it the darling among the developers.

MVC, short for Model-View-Controller is an architectural pattern that helps in division of an application into three basic components- the controller, the model and the view. This framework is a great alternative to the web forms pattern when creating applications since it is highly testable as well as lightweight presentation framework. It comes integrated with all current .NET features like authentication based on membership as well as master pages. Most developers are quite familiar with the pattern. Here is a low-down on the advantages that the MVC based framework offers over the web forms.

Separating application tasks or concerns- A huge advantage in the framework is that it clearly separates Business Logic, Data, Model, UI, test-driven development and testability. Core contracts of the framework are interface-based for which mock objects may be used for the testing. These mock objects are simulated objects imitating the behaviours of application's actual objects. The application can be unit-tested without making the controllers run, making the testing more flexible as well as fast. Any framework may be used for the testing.

Clientcaching

Silverlight makes this available to us. When we integrate Silverlight full advantage may be taken of the feature. This leads to faster application loading; in fact some part of processing may be done through web browsers, this makes the execution of client site as well as the server side a lot faster. You can even integrate JQuery and MVC so that the code written runs in browser, taking away a huge load away from the server.

HTML size

In ASP.NET there is a huge problem in the HTML size of view state as well as controls. All data rendered is stored by view state with the final result being the final HTML getting too large. For those on slow internet connections, the loading time will be slow as well as delayed. The current framework takes care of that problem since the view state concept is absent here.

Supporting ASP.NET routing

This URL-mapping component is very powerful, letting you build applications with searchable and comprehensible URLs. Through this there is no need for URLs to include extensions of file-names since the design supports patterns of URL naming and these work good enough for SEO or search engine optimization as well as REST or representational state transfer addressing.

Pluggable as well as extensible framework

The design of MVC's components makes them easily customizable or replaceable. Individual view engine, action-method parameter serialization, URL routing policy as well as other components can be plugged in. The use of DI or Dependency Injection and IOC or Inversion of Control container models is also supported. With DI you can inject objects into classes and it does not rely on class for creation of object itself. The testing is made easier by the condition imposed that when an object is required by another object then another object should be sourced from an external source like configuration file.

The biggest advantage of ASP.NET MVC platform is that it contains all the features as well as advantages of .NET since the basis is the same for both. However, some disadvantages are that understanding codes during the process of customization may not be an easy process. Another problem is the cost- the start-up costs are much higher in the MVC platform when compared to the web form based one. But looking at the benefits that are enjoyed by the developers and the end result, this is but a small price to pay for. You can get in touch with a asp.net application development company who can help you develop web apps that are stable, scalable and secure.

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: New Ways To Organize Razor Views in ASP.NET Core

clock May 30, 2016 20:50 by author Armend

New Ways To Organize Razor Views in ASP.NET Core

Currently there are many ways to extend or to organize Razor views in ASP.NET Core. Let us start with the new more complex ways. If your are familiar with previous ASP.NET MVC Frameworks you’ll definitely know most. But not almost all of that “old” stuff is still possible in ASP.NET Core MVC. Some of the listed below is completely new in ASP.NET Core. With this post, we’re going to try to write down all options to organize MVC Views in ASP.NET Core.

 

How To Organize Razor Views in ASP.NET Core

1. ViewComponents

This is one of new way to organize Razor views in ASP.NET Core. Sometimes you need to have something like PartialView, but with some more logic behind. In the past there was a way to use ChildActions to render the results of controller actions into a view. In ASP.NET Core, there is a new way (which I already showed in this post about ViewCmponents) with ViewComponents. This are a kind of mini MVC inside MVC, which means they have an own Controller, with an own single action and a view. This ViewComponents are completely independent from your current view, but also can get values passed in from your view. To render a ViewComponent you need to call it like this:

@Component.Invoke("Top10Articles");

2.  TagHelper

This little helpers are extensions of your view, which are looking like real HTML tags. In ASP.NET Core, you should use this TagHelpers instead of the HtmlHelpers because they are more cleaner and easier to use. Another huge benefit is Dependency Injection, which can’t be used with the HtmlHelpers, because the static context of extension methods. TagHelpers are common classes where we can easily inject services via the constructor. A pretty simple example on how a TagHelper could look like:

[TargetElement("hi")]
public class HelloTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "p";
        output.Attributes.Add("id", context.UniqueId);
        output.PreContent.SetContent("Hello ");
        output.PostContent.SetContent(string.Format(", time is now: {0}", 
                DateTime.Now.ToString("HH:mm")));
    }
}

This guy defines a HTML Tag called “hi” and renders a p-tag and the contents and the current Time.
Usage:

<hi>armend</hi>

Result:
<p>Hello armend, time is now: 18:55</p>

ASP.NET Core MVC provides many built in TagHelpers to replace the most used HtmlHelpers. E. g. the ActionLink can now replaced with an Anchor TagHelper:

@Html.ActionLink(“About ��, “About”, “Home”)

The new TagHelper to create a link to an action looks like this:

<a asp-controller=”�� asp-action=”��>About me</a>

The result in both cases is a clean a-Tag with the URL to the about page:

<a href=”/Home/��>About me</a>

As you can see the TagHelpers feel more than HTML and they are easier to use and more readable inside the Views.

3. Dependency Injection

This is the biggest improvement to organize Razor views in ASP.NET Core. Yes, you are able to use DI in your View. Does this really make sense? Doesn’t it mess up my view and doesn’t it completely break with the MVC pattern? (Questions like this are currently asked on StackOverflow and reddit). We think, no. Sure, you need be careful and you should only use it, if it is really needed. This could be a valid scenario: If you create a form to edit a user profile, where the user can add its job position, the country where he lives, his city, and so on. We would prefer not to pass the job positions, the country and the cities from the action to the view. We would prefer only to pass the user profile itself and We only want to handle the user profile in the action. This is why it is pretty useful in this case to inject the services which gives me this look-up data. The action and the ViewModel keeps clean and easy to maintain.
Just register your specific service in the method ConfigureServices in the Startup.cs and use one line of code to inject it into your view:

@inject DiViews.Services.ICountryService CountryService;

Now you are able to use the ContryService in your View to fill a SelectBox with list of countries.

4. Global View Configuration

Last but not least, there is a separate razor file you can use to configure some things globally. Use the _ViewImports.cshtml to configure usings, dependency injections and many more which should be used in all Views.

Conclusion

There are many new ways to extend and organize Razor views in ASP.NET Core. But you are free to decide which feature you want to use to get your problems solved. While there are many programming languages out there for a web developer to choose from, one of the most successful programming language till this date is ASP.NET. It has matured over the years with the latest version, ASP.NET Core, having a number of new features and enhancements. You may already have heard that ASP.NET hosting is offered by several web hosting providers. However, choosing the best cheap ASP.NET hosting isn’t an easy task.

 



Cheap ASP.NET 4.5 Hosting

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

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


Author Link


 

Corporate Address (Location)

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

Tag cloud

Sign in