European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 5 Hosting - HostForLIFE.eu :: Json Files Configuration

clock April 29, 2016 23:12 by author Anthony

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use standard JavaScript functions to convert JSON data into native JavaScript objects.

Much Like XML Because

  • Both JSON and XML is "self describing" (human readable)
  • Both JSON and XML is hierarchical (values within values)
  • Both JSON and XML can be parsed and used by lots of programming languages
  • Both JSON and XML can be fetched with an XMLHttpRequest

Much Unlike XML Because

  • JSON doesn't use end tag
  • JSON is shorter
  • JSON is quicker to read and write
  • JSON can use arrays

The biggest difference is:

XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function.

Visual Studio 2015 with ASP.NET 5 is a sweet surprise for developers. ASP.NET 5 has various JSON files to play with. These files handles global settings for solution, project specific settings, client side packages and node modules packages. In the post, we will take a close look at every JSON file and its code.

Solution Explorer in ASPNET 5 RC1


As seen from the above image, there are mainly 6 configuration json files.

  • Global.json
  • appsetting.json
  • Project.json
  • launchsetting.json
  • bower.json
  • package.json
  • hosting.json: Though this file is not present in solution explorer till RC 1 release but you can add it manually.


Global.json

As the name suggests, the settings defined in the file should work for the solution as whole. The settings defined in global.json implies to all the projects in the solution. If you open the file, by default you will see the following code.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The projects property defines the locations of your solution’s source code. VS 2015, specifies two location for projects in the solution src and test. While the src contains the actual application and test project contains any test (if you have selected option of creating test project while creating the solution for first time].

The team has also made a very interesting and useful change. If you recollect, when you build your application, then all your .dll are placed in bin directory in the same path, where your project is. And we have to handle bin folder very carefully while check-in the code in source control and at the time of deployment. But good news is that it is moved to another location. So you don’t have to worry now. The build artifact is now placed in “Artifact” folder (at the same location), which makes life easy while excluding things from source control.

Artifact folder

And the second property sdk specifies the version of the DNX (.Net Execution Environment) that Visual Studio will use when opening the solution. Specifying the version has an advantage as while working on multiple projects, you can target different versions of ASP.NET 5.

appsettings.json

appsettings.json file is used to define application related settings like connection string, logging settings, or any other custom key which we used to define in web.config file.

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-FirstApp-0ed2f710-6535-4c4e-b080-c26601fbb414;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}


Project.json

This file is used to define project settings and server side dependencies. It largely replaces the web.config file from previous versions of ASP.NET. Read “What is Project.json in ASP.NET 5 (vNext)”. Few things have changed in ASP.NET 5 RC1 release for project.json file.

launchSetting.json

This json file holds project specific settings associated with each profile Visual Studio is configured to use to launch the application, including any environment variables that should be used. You can define framework for your project for compliation and debugging for specific profiles.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:2137/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "Hosting:Environment": "Development"
      },
      "sdkVersion": "dnx-clr-win-x86.1.0.0-rc1-update1"
    },
    "kestrel": {
      "commandName": "kestrel",
      "sdkVersion": "dnx-clr-win-x86.1.0.0-rc1-update1"
    }
  }
}


ASP.NET 5 ships with support for 3 different servers:

  • Microsoft.AspNet.Server.IIS
  • Microsoft.AspNet.Server.WebListener (WebListener)
  • Microsoft.AspNet.Server.Kestrel (Kestrel)

So by default, there will be 3 different profiles. However, it also depends on the commands section of project.json. You can change settings for each profile via right click on the Project and then select properties. Read detailed post about launchsetting.json in ASP.NET 5

change launchsetting.json settings

Bower.json

Bower is a package manager for the web. Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else – it just installs the right versions of the packages you need and their dependencies. With ASP.NET 5 web projects jQuery and bootstrap packages are already installed and bower, gulp and NPM are already in place.
Client-side packages are listed in the bower.json file. As mentioned earlier, bootstrap, jQuery and jQuery validation are pre-configured with ASP.NET 5 project templates.

{
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.5",
    "jquery": "2.1.4",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.4"
  }
}


Visual Studio watches the bower.json file for changes. Upon saving, the bower install command is executed. There is another file named “ .bowerrc” which defines the location at which bower package needs to be installed. Open it, and notice that the directory property is set to “wwwroot/lib”.

Package.json

npm is another package manager like bower. But npm is used for installing Node js modules where bower is used for managing front end components like html, css, js, etc. As mentioned earlier, the ASP.NET 5 project template pre-configures NPM, Gulp and bower. Gulp is JavaScript task runner which is used to automate various tasks like minification and bundling of js and css, checking errors in js etc… Since Gulp is a node.js module so npm is used. So node.js modules are listed in package.json.\

{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

You can see the installed bower and npm modules by expanding src -> dependencies option.

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Handle Error 404?

clock April 22, 2016 23:19 by author Anthony

404 is a frequently-seen status code that tells a Web user that a requested page is "Not found." 404 and other status codes are part of the Web's Hypertext Transfer Protocol ( HTTP ), written in 1992 by the Web's inventor, Tim Berners-Lee. He took many of the status codes from the earlier Internet protocol for transferring files, the File Transfer Protocol ( FTP .)

What to Do If You Get a 404

If the site no longer exists, there's nothing you can do. However, it only takes one mistyped character to result in a 404. See whether the ".htm" should be an ".html" or vice versa. If you're linking from a Web site, you can do a "View source" to make sure it wasn't miscoded. Whether or not it is, you may want to send a note to the Webmaster so that the link can be fixed for the next users.

In this tutorial, I will show you how to handle 404 error in ASP.NET Core 1.0. Prior versions of ASP.NET Core 1.0, have custom errors for error handling. With ASP.NET Core 1.0 and MVC, you can do the error handling via Middlwares. HTTP 404 is a very common error which comes when server can’t find the requested resource. In this post, we will see different ways to handle HTTP 404 error in ASP.NET Core 1.0 and MVC.

How to handle 404 error in ASP.NET Core 1.0


I found 2 ways to handle 404 error. In fact using these solution you can handle any HTTP status code errors. To handle the error, both the solution are using configure() method of Startup.cs class. For those who are not aware about Startup.cs, it is entry point for application itself. You can read this excellent post The Startup.cs File in ASP.NET Core 1.0. to know more about startup.cs. And within the startup.cs file, you will also find static void main() which generally you use with windows/console applications. Read my post Why static void main in ASP.NET 5 startup.cs

Now coming back to our solution 1, within configure method define a custom middleware via app.Use which checks for status code value in response object. And if is 404 then it redirects to Home controller.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
 
    app.UseApplicationInsightsRequestTelemetry();
    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home";
            await next();
        }
    });
 
    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();
    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Solution 2

The other solution is to use a built-in middlware StatusCodePagesMiddleware. This middleware can be used to handle the response status code is between 400 and 600. This middleware allows to return a generic error response or allows you to also redirect to another middle. See below all different variations of this middleware.

app.UseStatusCodePages();
 
// app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
// app.UseStatusCodePages("text/plain", "Response, status code: {0}");
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
// app.UseStatusCodePages(builder => builder.UseWelcomePage());
// app.UseStatusCodePagesWithReExecute("/errors/{0}");

Now to handle the 404 error, we shall use app.UseStatusCodePagesWithReExecute which accepts a path where you wish to redirect.

app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");

So we are redirecting here to Home Controller and Errors action method. The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.

public IActionResult Errors(string errCode)
{
    ViewData["ErrorID"] = "The following error " + errCode + " occured";
    return View("~/Views/Shared/Error.cshtml");
}

It adds the status code in ViewData and then returns to Error.cshtml shared view. You can also return to specific error page based on the error code.

public IActionResult Errors(string errCode)
{
  if (errCode == "500" | errCode == "404")
  {
    return View($"~/Views/Home/Error/{errCode}.cshtml");
  }
 
  return View("~/Views/Shared/Error.cshtml");
}

So, if the error code is 500 or 404 then return to Home/Error/500.cshtml or 404.cshtml.

You must have seen on many websites, forums about app.UseErrorPage(); to handle the errors. But this is no longer available with RC1 release of ASP.NET Core 1.0. This was available until beta 5 or 6.


HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Check Record Availability using JOSN and jQuery?

clock April 20, 2016 00:10 by author Peter

In this tutorial, I will show you how to Check Record Availability using JOSN and jQuery. I will check user name available or not a table without refreshing the page using JOSN in ASP.NET. The followind code will explains how to check the user name that end user is entering already exist in database or not if it exist then message will show. In this entire process page is not refreshing.


I am using JOSN and Ajax as in the following example:   

<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>  
    <script type = "text/javascript"> 
    function ShowAvailability() { 
        $.ajax({ 
            type: "POST", 
            url: "CheckUserAvalibleusingJOSN.aspx/CheckUserName", 
            data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: OnSuccess, 
            failure: function (response) { 
                alert(response); 
            } 
        }); 
    } 
     
    function OnSuccess(response) { 
        var mesg = $("#mesg")[0]; 
        switch (response.d) { 
            case "true": 
            mesg.style.color = "green"; 
            mesg.innerHTML = "Available"; 
            break; 
            case "false": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Not Available"; 
            break; 
            case "error": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Error occured"; 
            break; 
        } 
    } 
     
    function OnChange(txt) { 
        $("#mesg")[0].innerHTML = ""; 
        ShowAvailability();//hide this function from here if we want to check avability by using button click 
    } 
    </script> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div > 
            UserName : <asp:TextBox ID="txtUserName" runat="server" onkeyup = "OnChange(this)"></asp:TextBox> 
            <%--<input id="btnCheck" type="button" value="Show Availability" onclick = "ShowAvailability()" />--%> 
            <br /> 
            <span id = "mesg"></span> 
            </div> 
        </form> 
    </body>


Code

    [System.Web.Services.WebMethod] 
    public static string CheckUserName(string userName) 
    { 
        string returnValue = string.Empty; 
        try 
        { 
            string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
            SqlConnection conn = new SqlConnection(consString); 
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
            conn.Open(); 
            returnValue = cmd.ExecuteScalar().ToString(); 
            conn.Close(); 
        } 
        catch 
        { 
            returnValue = "error"; 
        } 
        return returnValue; 
    }


SQL Query

    USE [manish_db] 
    GO 
    /****** Object: StoredProcedure [dbo].[spx_CheckUserAvailability] Script Date: 07/19/2014 02:17:13 ******/ 
    SET ANSI_NULLS ON 
    GO 
    SET QUOTED_IDENTIFIER ON 
    GO 
    ALTER PROCEDURE [dbo].[spx_CheckUserAvailability] 
    @UserName VARCHAR(50) 
    AS 
    BEGIN 
    SET NOCOUNT ON; 
    IF NOT EXISTS 
    (SELECT UserName FROM dbo.UserDetails 
    WHERE UserName = @UserName 
    ) 
    SELECT 'true' 
    ELSE 
    SELECT 'false' 
    END

Note: If we use web services just add webservices and replace the page path with *.asmx file path.

Code

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class CheckUserAvalible : System.Web.Services.WebService 
    { 
        [WebMethod] 
        public string CheckUserName(string userName) 
        { 
            string returnValue = string.Empty; 
            try 
            { 
                string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
                SqlConnection conn = new SqlConnection(consString); 
                SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
                cmd.CommandType = CommandType.StoredProcedure; 
                cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
                conn.Open(); 
                returnValue = cmd.ExecuteScalar().ToString(); 
                conn.Close(); 
            } 
            catch 
            { 
                returnValue = "error"; 
            } 
            return returnValue; 
        } 
    }


I Hope it works for you! Happy coding.

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to Make CAPTCHA?

clock April 15, 2016 21:42 by author Anthony

A CAPTCHA (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart") is a type of challenge-response test used in computing to determine whether or not the user is human. The term was coined in 2003 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford.

The technology is used mostly to block spammers and bots that try to automatically harvest email addresses or try to automatically sign up for or make use of Web sites, blogs or forums. CAPTCHA, whose users include Yahoo and Google, blocks automated systems, which can't read the distorted letters in the graphic.

The algorithm for CAPTCHA is public, as the "P" in the name implies. The test was developed in various forms around 1996, but it got its distinctive name in 2000 from researchers at Carnegie Mellon University and IBM. Cracking the algorithm won't make the CAPTCHA vulnerable, since the algorithm is only used for generating the random series of letters and numbers in the image. The system works because humans and computers process strings of characters differently.

One of the problems with CAPTCHA is that sometimes the characters are so distorted that they can't even be recognized by people with good vision, let alone visually handicapped individuals. Depending on local regulations for handicapped access to Web sites, this can also be a compliance issue for some Web-based businesses.

CAPTCHA technology is easy to implement, but requires some knowledge of hypertext preprocessor (PHP) or other Web scripting languages. For more information and links to extensive resources, check the How to use CAPTCHA Web site and The CAPTCHA Project. Both sites also have examples of CAPTCHAs and in-depth tutorials on how to develop and implement CAPTCHA for your Web site.

So, in this article, I will explain how to make basic CAPTCHA.

You can set the height and width of the CAPTCHA image while initializing the CAPTCHA class. The CAPTCHA image generated from the class can be set to the image control directly or it can be save to the local path and then set to the image control. For this example I am saving it to the local path and then set to the image control. And the CAPTCHA image code generated by the class is automatically set to the session variable named CaptchaCode.

Time to get some hand on it

On the page get an image control to display CAPTCHA image, a textbox where user will enter the CAPTCHA text and a button when clicked, we can check and validate if the code entered is correct or not. Plug the DLL in your ASP.NET project and go to the Page_Load event. Here we will generate the image of the height and width we wish to have for out CAPTCHA image and then save the image to the CaptchaImages folder with the random image code generated. The code on the Page_Load event goes like this:
protected void Page_Load(object sender, EventArgs e)
{
        if (!Page.IsPostBack)
        {
            CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 140, 40);
            cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg);
            CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg";
            cImage.Dispose();
        }
        CaptchaCode = Convert.ToString(Session["CaptchaCode"]);
}

Before you can use the above code, declare a public variable which I have used to hold the value of the CAPTCHA code. I named it CaptchaCode. You can name it whatever you like it. We will be using this variable later to check it against the user input. Hit F5 to start and test your application. If everything is in place and you will be able to see the below output.

To check if the user enters the correct CAPTCHA code, we must have an event on button click which will validate the user input and prompt the user if CAPTCHA code is correct or incorrect. The code on the button click is:

protected void btn_Validate(object sender, EventArgs e)
{
        if (CaptchaCode == txt_ccode.Text)
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered Correct CAPTCHA Code!');</script>");
        }
        else
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered INCORRECT CAPTCHA Code!');</script>");
        }
}

The above code will check the CAPTCHA code entered by the user and check against the CAPTCHA code we previously saved in the session variable (CaptchaCode). If the validation is a success, user will get the message notifying him that he enters correct CAPTCHA code or the error message otherwise.

And that's it, we have successfully implement a CAPTCHA in our ASP.NET application. So, here are few things we can do with this CAPTCHA library:

Set image height and width.
Saves the image to the local path.
Automatically sets the generated CAPTCHA code to the application session.

 


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Select Data Tree View in ASP.NET ?

clock April 12, 2016 20:44 by author Peter

Today, let me show you how to select data tree view in ASP.NET. The ASP.NET TreeView control is a powerful server-control for rendering TreeView UI, as shown in the figure below. It supports a variety of programming models, from statically-defined trees, to dynamically constructed trees, to databound trees. The TreeView's rendering is fully customizable, allowing for a wide-range of look-and-feels for the control. The TreeView supports both postback-style events and simple hyperlink navigation, as well as a unique event handling model that allows data to be retrieved directly from a client without requiring a server postback. It also supports rendering on a variety of browsers, and can take advantage of up-level capabilities, such as client-script on later desktop browser versions.


Now, it's time to write the following code:
    public void fill() 
    { 
        con.Open(); 
        SqlCommand cmd = new SqlCommand("select sr_no,rank_no,emp_name,emp_code,rank_name,doj from empregistration where emp_code='" + TextBox4.Text + "' ", con); 
        SqlDataReader dr = cmd.ExecuteReader(); 
        if (dr.Read())  
        { 
            no = Convert.ToInt32(dr["rank_no"].ToString()); 
            Label20.Text = dr["emp_name"].ToString(); 
            Label21.Text = dr["emp_code"].ToString(); 
            Label22.Text = dr["rank_name"].ToString(); 
            Label23.Text = dr["doj"].ToString(); 
            no13 = Convert.ToInt32(dr["sr_no"].ToString()); 
            dr.Read(); 
        } else  
        { 
            Response.Write("<script>alert('Employee Code Is Not Correct')</script>"); 
        } 
        for (int i = no; i >= 1; i--)  
        { 
            if (i == 12) 
            { 
                no12 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 11) 
            { 
                no11 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 10)  
            { 
                no10 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 9) 
            { 
                no9 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 8)  
            { 
                no8 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 7) 
            { 
                no7 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 6)  
            { 
                no6 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 5)  
            { 
                no5 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 4) 
            { 
                no4 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 3) 
            { 
                no3 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 2) 
            { 
                no2 = Convert.ToInt32(i.ToString()); 
            } 
            if (i == 1) 
            { 
                no1 = Convert.ToInt32(i.ToString()); 
            } 
        } 
        con.Close(); 
        // SqlCommand cmd1 = new SqlCommand("select rank_no from empregistration where ", con); 
    } 
    protected void Button1_Click(object sender, EventArgs e)  
    { 
        Label14.Visible = true; 
        Label8.Visible = true; 
        Label15.Visible = false; 
        Label7.Visible = false; 
        fill(); 
        con.Open(); 
        SqlCommand cmd = new SqlCommand("select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no12 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no11 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no10 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no9 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no8 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no7 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no6 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no5 + "'and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no4 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no3 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no2 + "' and sr_no >'" + no13.ToString() + "' union select rank_no,rank_name,emp_code,emp_name,doj,int_code,int_name,int_rank from empregistration where rank_no <='" + no1 + "' and sr_no >'" + no13.ToString() + "' order by emp_code asc ", con); 
        SqlDataAdapter da = new SqlDataAdapter(cmd); 
        DataSet ds = new DataSet(); 
        da.Fill(ds); 
        if (ds.Tables[0].Rows.Count > 0) 
        { 
            gvProducts.DataSource = ds; 
            gvProducts.DataBind(); 
        } 
        con.Close(); 
    } 


I hope this code is work for you. Good luck!

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Make Ext.NET in ASP.NET?

clock April 11, 2016 23:29 by author Anthony

In this article, I want to share about Ext.Net. Before we begin to learn Ext.net, we need to know what it Ext.net, according to the official web ext.net of are.

Ext.Net is ported to .Net Programming Ext JS, Ext JS is actually also be used in .Net programming, but this Ext.Net easier for developers because it has been created controls can be drag directly to the webform.

Things need to be prepared are:

  • IDE for .Net Programming, here I am using Visual Studio 2010
  • Ext.Net, which can be downloaded on the official website download ext.net, in sharing this time I used ext.net 2.0.0.rc2 community edition version.
  • Extract the downloaded ext.net, in which there Ext.net.dll.
  • ASP.Net with C # code behind.

When you get all the things that needed to be prepared:

  • Create a project, select Visual C # => Web, and then select ASP.Net Web Application
  • Give the name of this project ext.net
  • In the ToolBox window, usually on the left side of the screen, or if no can press Ctrl + Alt + X, right-click the toolbox and select Add Tab, named Ext.Net
  • Right-click the Toolbox Ext.Net, select Choose Items.
  • On the .Net Framework Components, click Browse, find Ext.net.dll then click OK
  • Now the ToolBox Ext.Net already charged components Ext.net.
  • The next step is to create a webform, named WebForm1.aspx
  • Add a ResourceManager to WebForm1.aspx (ResourceManager can be found in the ToolBox Ext.net). ResourceManager is needed by each component Ext.net.
  • Add Ext: Button, set property looks like this:
    <ext:Button ID="Button1" runat="server" Text="Direct Event">
          <DirectEvents>
              <Click OnEvent="Button1_Click" />
          </DirectEvents>
    </ext:Button>

    Button1 DirectEvents method to perform the action.
  • Then, we move on Code Behind of Webform1.aspx, open webform1.aspx.cs or by pressing the F7 key or you can also select the menu View => Code.
  • On Windows Code Behind, on the declaration using (top) add using Ext.Net;
  • Then, add the following method Button1_Click
    protected void Button1_Click(Object sender, DirectEventArgs e)
    {
       X.Msg.Notify("DirectEvent", DateTime.Now.ToLongTimeString()).Show();
    }
  • Back again to WebForm1.aspx by pressing the Shift + F7 keys or select menu View => Designer.
    Add an Ext: Button again into Webform1.aspx, set its properties as follows.
    <ext:Button ID="Button2" runat="server" Text="Direct Method">
          <Listeners>
              <Click Handler="Ext.net.DirectMethods.DoSomething();" />
          </Listeners>
    </ext:Button>
  • Then, add Method Do Something in Code Behind (press F7 to switch to Code Behind window.
    [DirectMethod]
    public void DoSomething()
    {
       X.Msg.Notify("DirectMethod", "Akhirnya bisa Ext.Net").Show();
    }
  • When finished, open the Web.Config the solution Explorer, add the following script.
    <httpModules>
       <add name="DirectRequestModule" type="Ext.Net.DirectRequestModule, Ext.Net" />
    </httpModules>
  • Run the Project by Press F5 or select Debug menu => Start Debugging

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 5 Hosting - HostForLIFE.eu :: Root Of ASP.NET 5

clock April 8, 2016 19:00 by author Anthony

Today we will discuss about the root of ASP.NET 5, which is WWWroot. When you take a closer look at the ASP.NET 5 project, you will see that there are many things which are carry forwarded like Model, View, Controller, clean separation of concerns and may more.

But, there are also some significant changes around ASP.NET 5. Now, the root of the website is no longer the root of the project. By default, root will be WWWroot folder. The idea behind this to maintain the clean separation between the files at the web-server retrieved and sent to the client and the files which contains the logic and configuration. Static files like JS, CSS, HTMLs can live in WWWroot folder.

15th

Now, lets suppose when i run the app and tried to see the image which i have placed in My Imgaes folder, then it will give me 404 error. On the other hand, if i go ahead and add the same folder in WWWroot folder and try to navigate the same then it will produce me the result.

18th

so, the point is all static files are served by root folder and logical stuffs served by project space as we initially saw, when i added controller in the controller’s folder and it took effect. One more thing you might have observed that there is no web.config file now in the solution. Also now there is no Global.asax file; however the same is replaced by startup.cs file. But, we’ll see this later. 1st let’s see project.json file. This file now manages many aspects of website.

19th

First thing which you will notice here that root folder is set to WWWroot here. So, this is the place which is telling website that this is the root folder. So begin the show from here. This you can change as well or rename if you like to. Now, this configuration file is in JSON format. This is also telling the ASP.NET runtime what dependencies project is going to need. In this new ASP.NET 5 system there is a new way to manage dependencies. No need to reference assemblies and store the lists of referenced assemblies in the project file. Instead we refer to nuget packages as dependencies and these dependencies are listed in our project.json file. Now, there are couple of reasons for this change. One reason is to simplify the dependency management. Another good reason for this is that ASP.NET is moving away from VS dependency. So, in future i can use any text editor to build the ASP.NET App.

Now, these dependencies can be both the ways. One way which we used already shown below in the screen shot.

20th

21th

Now, the UI of this also changed. Initially we used to have Modal window. Now, this is more like complete screen giving wider visibility. I can also see the installed templates like

22nd

Also, i still have the flexibility of different nuget source. 2nd Option is via project.json file. Let’s suppose i am planning to install some custom package. Then i can do like shown below as well

24th

However, whatever package you install; you can find its references under “References“. Below, in the screen shot you can see that there are two versions of runtime here. 1st one is the core version and 2nd one is the cloud optimized version.

25th

Let’s collapse the same and drill into it. Now, here dependency management system will keep your assemblies in nice tree structure. So, it nicely tells which package are dependent on which package.

27th

Now, as far as Framework and runtime is concerned as you can see below in the screen shot; i have both frameworks listed here.

28th

So, whenever i am building the solution i am building against both of these frameworks. By building against both i am actually ensuring that it will work well against both the frameworks. This also means whenever i am switching platform my code won’t break there.

But, let’s go ahead and break something here. You remember in the last segment i created one new controller with a notepad. Now, let’s modify the same and refresh the app.

29th

As you can see that it says that GetCallingAssembly() which is part of System.Reflection is not supported in the cloud optimized version. But, let’s suppose i overlooked this error and refresh the app.So, it actually produced me desired result.

31th

But, when i explicitly build the project and checked the output window, then it gave me below error message.

32nd

So, building with error but application is working fine with full blown CLR. Now, if you have decided that you don’t want CORE CLR version. so, you can just comment the Core CLR section in the project.json file as shown below in the screen shot.

33th

As soon as i commented the above section, below references got refreshed automatically.

34th

Now, when i build the app then it will build fine. But, suppose you want the other way means you would like to keep the cloud optimized version also and build should also succeed. For this scenario i need to refer the conditional build as shown below.

36th

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How To Prevent XSS Attacks in ASP.NET?

clock April 6, 2016 19:17 by author Anthony

In this article, I will explain about how to prevent XSS Attacks. XSS (Cross-Site Scripting) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. For sites that allow user input to be displayed in the browser, cross site scripting (XSS) attacks are a possibility that must be protected against.  These attacks are carried out by placing <script> tags pointing to malicious code in the public facing elements, which can be persisted elements such as comments or reviews, or more ephimeral examples such as query variables in the url.  The aim of these attacks varies, but some examples are stealing sensitive information (login credentials, personal data), forcing redirects, or just about anything else that can be accomplished with JavaScript.  These attackes can be prevented by encoding input. So instead of the literal string <script>bad script code</script>, it becomes &lt;script&gt;bad script code&lt;/script&gt;, and instead of running the code, it will simply display the text content of the script.

According to Microsoft, the primary purpose of the HttpUtility.HtmlEncode method is to ensure that ASP.NET output does not break HTML; it's purpose is not necessarily security.  However, the AntiXssEncoder class is primarily designed for security.  To this end, it uses a white-list approach rather than a black-list, only allowing known safe characters to remain unencoded.  The AntiXss method is slightly less performant, and will work in multiple languages.

It is possible to set the AntiXssEncoder as the default for your application, and this has gotten steadily easier.  Phil Haack wrote in 2010 about doing this using a the HttpEncoder abstract base class, and Jon Galloway wrote in 2011 about doing it with version 4.1 which already included an encoder, so it required little more than adding the assembly to the project and changing the web.config file.  Since AntiXss can now be had in NuGet, it's as simple as installing it and setting the httpRuntime encoderType property:

 <system.web>
    <httpRuntime targetFramework="4.5"
             encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary"/>
  </system.web>


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Use Entity Framework 7 To Persist Movie Data To a Database?

clock April 4, 2016 19:50 by author Anthony

Today I will explain about how to use entity framework 7 to presist movie data to a database. But before you start, you must add Entity Framework 7 NuGet packages to your project. Also make sure that your project.json file includes the following two dependencies (you’ll get Intellisense while entering the names of the packages and their versions).

"EntityFramework.SqlServer": "7.0.0-beta2",
"EntityFramework.Commands": "7.0.0-beta2",

 

After you complete this step, the Entity Framework packages should appear under References.

Creating the Model and DbContext

Next, we need to create our Movie model class. This class represents the entity that we want to store in the database. Add the following Movie.cs class to your Models folder:

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
 
        public string Title { get; set; }
 
        public string Director { get; set; }
    }
}

We also need to create an Entity Framework DbContext class. We create this class when using Entity Framework 7 in exactly the same way as we created this class for previous versions of the Entity Framework.

using Microsoft.Data.Entity;
namespace MovieAngularJSApp.Models
{
    public class MoviesAppContext:DbContext
    {
 
        public DbSet<Movie> Movies { get; set; }
 
    }
}

Registering the Entity Framework Services
Now that we have our DbContext class, we need to register the DbContext with our application services. Modify your Startup.cs file so it contains the code for registering the Entity Framework in the code below:

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MovieAngularJSApp.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
namespace MovieAngularJSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }
         public IConfiguration Configuration { get; set; }
         public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
 
            // Register Entity Framework
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<MoviesAppContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
 
    }
}

The database connection string is loaded up from the Config.json file (notice the constructor in the Startup.cs file). Here is what the Config.json file looks like:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MoviesDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    },
    "EntityFramework": {
        "MoviesAppContext": {
            "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
        }
    }
}

Updating the MoviesController

Because we registered our MoviesAppContext class as a service, we can take advantage of the built-in ASP.NET 5 Dependency Injection framework to use the MoviesAppContext in our MoviesController. Notice that the MoviesAppContext class is added to the MoviesController using constructor dependency injection in the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
namespace MovieAngularJSApp.API.Controllers
{
    [Route("api/[controller]")]
    public class MoviesController : Controller
    {
        private readonly MoviesAppContext _dbContext;
 
        public MoviesController(MoviesAppContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        [HttpGet]
        public IEnumerable<Movie> Get()
        {
            return _dbContext.Movies;
        }
        [HttpGet("{id:int}")]
        public IActionResult Get(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            if (movie == null) {
                return new HttpNotFoundResult();
            } else {
                return new ObjectResult(movie);
            }
        }
        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
            if (movie.Id == 0)
            {
                _dbContext.Movies.Add(movie);
                _dbContext.SaveChanges();
                return new ObjectResult(movie);
            }
            else
            {
                var original = _dbContext.Movies.FirstOrDefault(m => m.Id == movie.Id);
                original.Title = movie.Title;
                original.Director = movie.Director;
                _dbContext.SaveChanges();
                return new ObjectResult(original);
            }
        }
        [HttpDelete("{id:int}")]
        public IActionResult Delete(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            _dbContext.Movies.Remove(movie);
            _dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }
 
 
    }
}

Performing Database Migrations

After we complete all of the steps above, our application still won’t work. If we run the Movies app then we will get an error message about not being able to open the MoviesDatabase.

The Entity Framework 7 does not support database initializers. Instead, you are encouraged to use Database Migrations.There are two ways to use Migrations with ASP.NET 5: from a Command Prompt or from the NuGet Package Manager Console. I used the Command Prompt approach and I executed the following two commands from the same directory that contains my project.json file:

k ef migration add initial
k ef migration apply

KPrompt

After you execute the two ef commands above, a new database named MoviesDatabase will be created. You can see the new database by opening up the Visual Studio SQL Server Object Explorer:

SQLExplorer

Executing the ef commands above will also add a new Migrations folder to your project.

Migrations

You now should be able to run the Movies app successfully.

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in