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 :: Protect Web Pages Using .htaccess Files

clock January 8, 2017 13:47 by author Armend

A .htaccess file (pronounced ‘dot aitch tee access’ or simply ‘aitch tee access’) is aspecial configuration file used on web servers running the Apache httpd web server software. When someone visits a page that is sitting in a directory alongside, or in the same branch as, a .htaccess file then that configuration file will be loaded by the server and processed.

.htaccess files are used to reconfigure the web server without needing to restart it. These files can be used to enable or disable additional functionality and features, such as creating redirects, disabling directory listings and password protecting directories.

If you want to password protect some of your web pages, then you need to use a .htaccess file with a .htpasswd password file. This tutorial will tell you step-by-step what you need to do.


Step By Step Instructions
Let's suppose you want to restrict files in a directory called members to username memberone with password memberonepassword. Here's what to do:
1. Create a file called .htaccess in directory members that looks like this:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd
require valid-user


Notes
:

  • In the AuthUserFile line, replace USERNAME with your ftp username.
  • The .htaccess file must be an ASCII text document.
  • A .htaccess file can be created in any word processor but must be saved as text only.
  • IF you upload your .htaccess file via FTP, the FTP client must be set to ASCII mode for transfer.
  • For security reasons, the .htaccess file on the server cannot be seen in a directory listing. If you don't see it after uploading it, don't worry.
    Also note that AuthName can be anything you want. The AuthName field gives the Realm name for which the protection is provided. This name is usually given when a browser prompts for a password, and is also usually used by a browser in correlation with the URL to save the password information you enter so that it can authenticate automatically on the next challenge.

2. Use the htpasswd command, from your home directory, to create a password file called .htpasswd in your home directory:
SSH to your home directory. This is simply done by connecting with your SSH client and NOT entering any path, and NOT changing directories after connecting. After connecting to your home directory via SSH, enter:

# htpasswd -c .htpasswd memberone

Type the password -- memberonepassword -- twice as instructed.
3. That's the setup done. Now test by trying to access a file in the directory members; your browser should demand a username and password, and not give you access to the file if you don't enter memberone and memberonepassword.


Multiple Usernames/Passwords

If you want to give access to a directory to more than one username/password pair, follow the steps above to create the .htaccess file and to create the .htpasswd file with one user. Then, add additional users to the .htpasswd file by using the htpasswd command without the -c:

# htpasswd .htpasswd membertwo
New password:
Re-type new password:
Adding password for user membertwo


Changing Passwords

If you want to change the password for an existing user, simply issue the same command as when you added the user. You will then be prompted for a new password. For example, if the user membertwo already exists and you want to change the password, just SSH to your home directory and enter:

# htpasswd .htpasswd membertwo


Password Protecting Multiple Directories
If you want to password protect multiple directories, and allow all users access to all password protected directories, then all you need to do is put the same .htaccess file in each directory that you want to password protect.

However, if you want to password protect multiple directories, and only allow certain users access to each directory, then you can create a different password file (all in your home directory) for each password protected directory.

Let's say you have 3 different directories (members, admins, board) you want password protected, and each one has a different set of users that you want to allow access. Then just do the following:

Create three .htaccess files and put them in their appropriate directory:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.members
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.admins
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.board
require valid-user

Remember to replace USERNAME with your ftp username (in lower case).

Create three .htpasswd files in your home directory:

# htpasswd -c .htpasswd.members memberone
# htpasswd -c .htpasswd.admins adminone
# htpasswd -c .htpasswd.board boardmemberone

That's it. Now when you need to add a user to one of the directories, just issue the htpasswd command on the appropriate .htpasswd file.

 

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 :: How to Check Duplicate User Names In ASP.NET Web Pages Sites

clock October 5, 2015 11:39 by author Kenny

How to Check Duplicate User Names In ASP.NET Web Pages Sites

The Web Pages Starter Site template provides a useful starting point for developing a Razor Web Pages site that includes membership. But it doesn't include any mechanism for preventing duplicate user names. This article offers one solution to the problem that uses jQuery.

If you ask how to prevent duplicate user names in forums, one of the suggestions that is often put forward is to apply a unique constraint in the database column that holds the user name. Any attempt to submit a duplicate value will result in an exception being raised in the relevant database provider. You can catch this exception and show the user an appropriate message. This works but it's a fairly clunky solution. And many people feel that you should not use exceptions as a means to manage your business rules.

The solution featured in this article uses AJAX to query the database and to give the user immediate feedback when they enter their chosen user name. The AJAX call requests a page that exists purely to query the database to see if the selected user name is already in use. The solution also includes a server side chekc to ensure that users who have disabled JavaScript so not slip through the net. The solution requires a couple of amendments to the Register.cshtml file in the Starter Site, and the addition of 3 files. But first, the changes to the Register.cshtml page. The first change is in the inclusion of a JavaScript file called dupecheck.js.

@* Remove this section if you are using bundling *@
@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/dupecheck.js"></script>
}

And the second is the server side check to see if the username is in use:

if(Functions.IsDuplicate(email)){
    ModelState.AddError("email", "User name is already taken");
}

I placed this in the if(IsPost) section just after the initial variables that represent the submitted values (email, password and confirmPassword) are declared. The code calls a function named IsDuplicate. The function is declared in a file called Functions.cshtml which is placed in a folder called App_Code:

@functions {
    public static bool IsDuplicate(string username){
        var db = Database.Open("StarterSite");
        var commandText = @"SELECT COUNT(Email) FROM UserProfile WHERE Email = @0";
        return (int)db.QueryValue(commandText, username) > 0;
    }
}

Note that the name of the folder is important. The function returns a bool. The value of the bool is determined as a result if the SQL query which gets a count of the rows containing the provided user name. By default, the Starter Site uses a column called Email in the UserProfile table for the storage of user names. This function is also called in a separate file named DupeCheck.cshtml. This file is placed in the root of the site:

@{
    Layout = null;
    if(IsAjax){
        var username = Request["username"];
        var result = Functions.IsDuplicate(username);
        Json.Write(new { isDupe = result }, Response.Output);
    }
}

DupeCheck.cshtml is designed to work exclusively with AJAX. The code includes an instruction to nullify any layout pages that might have been set in a _PageStart file, and then it uses the IsAjax property to determine if the page has been requested via an AJAX call. If it has, it uses the IsDuplicate method to check the availability of the posted username and returns the result to the calling code. The result is an anonymous type that has one propery: isDupe, which is a boolean. The anonymous type is serialised to JSON by the Json helper.

The final part of the solution is the dupecheck.js file. This uses jQuery:

$(function () {
    $('#email').change(function () {
        $.post(
            '/DupeCheck',
            { username: $(this).val() },
            function (data) {
                var emailValidation = $('span[data-valmsg-for="email"]');
                if (data.isDupe) {
                    if (emailValidation.hasClass('field-validation-valid')) {
                        emailValidation.removeClass('field-validation-valid');
                        emailValidation.addClass('field-validation-error');
                        emailValidation.text('That name is already taken!');
                    }
                } else {
                    if (emailValidation.hasClass('field-validation-error')) {
                        emailValidation.removeClass('field-validation-error');
                        emailValidation.addClass('field-validation-valid');
                        emailValidation.text('');
                    }
                }
            },'json'
        );
    });
});

An event handler is attached to the change event of the user name input (which has an id if email in the Starter Site). The current value is posted to the DupeCheck.cshtml page via AJAX. The code above checks the response from the server to see if the value is a duplicate, and if it is, an appropriate error message is displayed to the user.

Best ASP.NET 4.6 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 MVC 6 Hosting - ASPHostPortal :: Remote Validation in ASP.NET MVC

clock August 24, 2015 08:07 by author Kenny

Remote Validation in ASP.NET MVC

ASP.NET is an open-source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat. 

Using the Code

To implement remote validation in an application we have two scenarios, one is without an additional parameter and the other is with an additional parameter. First we create an example without an additional parameter. In this example we check whether a username exists or not. If the username exists then that means the input user name is not valid. We create a view model class "UserViewModel" under the Models folder and that code is:

using System.Web.Mvc;  
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

 

Now we create a static data source, in other words we create a static list of UserViewModel in which we could check whether a username exists or not. You can also use the database rather than a static list. The following code snippet is for StaticData.

using RemoteValidation.Models;  
using System.Collections.Generic;  
 
namespace RemoteValidation.Code   
{  
    public static class StaticData   
    {  
        public static List < UserViewModel > UserList   
        {  
            get {  
                return new List < UserViewModel >   
                {  
                    new UserViewModel   
                    {  
                        UserName = "User1", Email = "[email protected]"  
                    },  
                    new UserViewModel   
                    {  
                        UserName = "User2", Email = "[email protected]"  
                    }  
                }  
            }  
        }  
    }  

 

Now we create a controller "ValidationController" in which we create an action method to check whether a user name exists or not and return a result as a JSON format. If the username exists then it returns false so that the validation is implemented on the input field. The following code snippet shows ValidationController under the Controllers folder.

using RemoteValidation.Code;  
using System.Linq;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class ValidationController: Controller   
    {  
        [HttpGet]  
        public JsonResult IsUserNameExist(string userName)   
        {  
            bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower())).FirstOrDefault() != null;  
            return Json(!isExist, JsonRequestBehavior.AllowGet);  
        }  
    }  
}

 

Now we add remote validation on the UserName of the UserViewModel property as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  

 

As in the preceding code snippet, the IsUserNameExist is a method of ValidationController that is called on the blur of an input field using a GET request. Now we create UserController under the Controllers folder to render a view on the UI.

using RemoteValidation.Models;  
using System.Web.Mvc;  
 
namespace RemoteValidation.Controllers   
{  
    public class UserController: Controller   
    {  
        [HttpGet]  
        public ActionResult AddUser()   
        {  
            UserViewModel model = new UserViewModel();  
            return View(model);  
        }  
    }  

Now we add jquery.validate.js and jquery.validate.unobtrusive.js to the project and create a bundle as in the following code snippet.

using System.Web.Optimization;  
 
namespace RemoteValidation.App_Start   
{  
    public class BundleConfig   
    {  
        public static void RegisterBundles(BundleCollection bundles)   
        {  
            bundles.Add(new StyleBundle("~/Content/css").Include(  
                "~/Content/css/bootstrap.css",  
                "~/Content/css/font-awesome.css",  
                "~/Content/css/site.css"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
                "~/Scripts/jquery-{version}.js"));  
 
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
                "~/Scripts/jquery.validate*"));  
        }  
    }  

Thereafter we add the following keys in the web.config file.

<add key="ClientValidationEnabled" value="true" />   
<add key="UnobtrusiveJavaScriptEnabled" value="true" />  
 
 

Thereafter we create a view for the AddUser action method. The following code snippet is for the AddUser view.

@model RemoteValidation.Models.UserViewModel  
 
< div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Add User < /div>    
    <div class="panel-body">    
        @using (Html.BeginForm())    
        {    
            <div class="form-horizontal">    
                <div class="form-group">    
                    @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.UserName)    
                    </div > < /div>    
                <div class="form-group">    
                    @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })    
                    <div class="col-lg-9">    
                        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })    
                        @Html.ValidationMessageFor(model => model.Email)    
                    </div > < /div>                    
                <div class="form-group">    
                    <div class="col-lg-9"></div > < div class = "col-lg-3" > < button class = "btn btn-success"  
                     id = "btnSubmit"  
                     type = "submit" > Submit < /button>    
                    </div >
               < /div>    
            </div >  
} < /div>    
</div >   
@section scripts   
{  
    @Scripts.Render("~/bundles/jqueryval")  

Let's run the application and put values into the user name field to execute the remote validation as in the following image.

Figure 1: Remote validation on user name


Now we move to another option, we pass an additional parameter in the remote validation. We pass both the user name and email as a parameter and check whether the username and email combination exist or not on the email input. That's why we add one more method in ValidationController as in the following code snippet for it.

[HttpGet]  
public JsonResult IsUserExist(string email, string userName)   
{  
    bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower()) && u.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null;  
    return Json(!isExist, JsonRequestBehavior.AllowGet);  

Now we call this method on the Email property of UserViewModel as in the following code snippet.

using System.Web.Mvc;  
 
namespace RemoteValidation.Models   
{  
    public class UserViewModel   
    {  
        [Remote("IsUserNameExist", "Validation", ErrorMessage = "User name already exist")]  
        public string UserName   
        {  
            get;  
            set;  
        }  
        [Remote("IsUserExist", "Validation", ErrorMessage = "User already exist", AdditionalFields = "UserName")]  
        public string Email   
        {  
            get;  
            set;  
        }  
    }  
}

As in the preceding code snippet, we are passing an additional field using AdditionalFields in Remote. If we must pass more than one parameter then these will be comma-separated. Now run the application and the result will be as shown in the following image.  



Classic ASP Hosting - ASPHostPortal.com :: Cropping picture using jQuery, Jcrop with ASPJpeg

clock October 23, 2014 06:15 by author Ben

As we know the assorted websites like Facebook, LinkedIn, Google and so forth., are utilizing Impression Cropping instrument when we incorporate a brand new picture. I found many ways to do that perform but lately I received Jcrop for image cropping. Jcrop will be the quick and simple way to include impression cropping performance for your net software with all the jQuery help.


Jcrop is simply a device which lets you crop image with reside preview. But, after the cropping picture, you have to create a new picture using the picked X-Axis, Y-Axis, Width and Height. I found several tricks to produce new photo through Method.Drawing.Image but I could not get this better to use cropping impression. So I decided to utilize ASPJpeg for making new picture.

ASPJpeg is a server part which will assist your ASP.Net apps with all their image-management wants. With ASPJpeg, you can create high-quality thumbnails, logo-stamp images, extract metadata details from images, crop, improve, rotate, convert, and much much more. But, listed here we are going to use for CROPPING image.

How to begin? (Jcrop Set up)

Add the following files into your project

  • jquery.min.js
  • jquery.Jcrop.js
  • jquery.Jcrop.css


Now we'd like to include above documents into our <head> segment and some fashion courses for HTML factors also as create features inside the webpage with all the OnChange and OnSelect event handler. These occasions are utilized to update existing selection of coordinates within the Concealed Fields.

<head runat="server">
<style type="text/css">
h2.panelTitle { font-size: 18px; margin-bottom: 5px; }
p.content { color: #5f5f61; width: 50%; }
div.imgCrop { width: 330px; float: left; }
div.imgPreview { width: 140px; float: left; margin-top: 40px; }
div.previewOverflow { width: 115px; height: 115px; overflow: hidden; }
div.previewText { color: #333; text-align: center; width: 115px; font-size: 14px; margin-top: 5px; }
div.clear { clear: both; height: 0; }
</style>
 
<link href="/_assets/js/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<script src="/_assets/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/_assets/js/jcrop/jquery.Jcrop.js" type="text/javascript"></script>
 
<script type="text/javascript">
var imgWidth = 0;
var imgHeight = 0;
 
function getImageDimensions(w, h) {
imgWidth = w;
imgHeight = h;
}
 
// Initialize Jcrop
$(function() {
jQuery('#imgCrop').Jcrop({
    onSelect: storeCoords,
    onChange: storeCoords,
    minSize: [115, 115],
    setSelect: [0, 0, 115, 115],
    aspectRatio: 1
});
});
 
// Update every move of the cropping in the Hidden Fields and Live Preview
function storeCoords(c) {
  var rx = 115 / c.w;
  var ry = 115 / c.h;
 
  jQuery('#X1').val(c.x);
  jQuery('#Y1').val(c.y);
  jQuery('#X2').val(c.x2);
  jQuery('#Y2').val(c.y2);
  jQuery('#W').val(c.w);
  jQuery('#H').val(c.h);
 
  jQuery('#preview').css({
    width: Math.round(rx * imgWidth) + 'px',
    height: Math.round(ry * imgHeight) + 'px',
    marginLeft: '-' + Math.round(rx * c.x) + 'px',
    marginTop: '-' + Math.round(ry * c.y) + 'px'
  });
};
</script>
</head>


Add the following code in your <body> section


<body>
<form id="form1" runat="server">
  <div style="padding: 10px;">
    <!-- PANEL #1: Choose Upload File -->
    <asp:Panel runat="server" ID="step1">
      <h2 class="panelTitle"> Update a picture of yourself</h2>
      <asp:FileUpload ID="FileUpload1" runat="server" />
      &nbsp;
      <asp:Button runat="server" Text="Upload" ID="btnUpload" OnClick="btnUpload_Click" />
      <br />
      <asp:Label ID="lblError" runat="server" Visible="false" />
      <p class="content"> You can upload a JPG, GIF, or PNG file. (Do not upload pictures containing celebrities, nudity, artwork or copyrighted images.)</p>
    </asp:Panel>
 
    <!-- PANEL #2: Show the Image Corpping with Preview -->     
    <asp:Panel runat="server" ID="step2" Visible="false">
      <h2 class="panelTitle"> Crop this picture of yourself</h2>
      <p class="content"> You can drag the box to select the crop area, and use the handle to resize it.<br />
        <asp:LinkButton runat="server" ID="lbBackToUpload" Text="Back to upload" OnClick="lbBackToUpload_Click"></asp:LinkButton>
      </p>
      <div>
        <div class="imgCrop">
          <asp:Image ID="imgCrop" runat="server" />
        </div>
        <div class="imgPreview">
          <div class="previewOverflow">
            <asp:Image ID="preview" runat="server" />
          </div>
          <div class="previewText"> Preview</div>
        </div>
        <div class="clear"> </div>
      </div>
      <br />
      <asp:HiddenField ID="X1" runat="server" />
      <asp:HiddenField ID="Y1" runat="server" />
      <asp:HiddenField ID="X2" runat="server" />
      <asp:HiddenField ID="Y2" runat="server" />
      <asp:HiddenField ID="W" runat="server" />
      <asp:HiddenField ID="H" runat="server" />
      <asp:Button ID="btnCrop" runat="server" Text="Apply Changes" OnClick="btnCrop_Click" />
      &nbsp;
      <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
      <asp:Image ID="imgCropped" runat="server" />
    </asp:Panel>
  </div>
</form>
</body>


After added above snipts, we will work on the backend side. We have 5 methods to create on the backend side.
  • CancelCrop (Private Method)
  • btnUpload_Click
  • btnCrop_Click
  • btnCancel_Click
  • lbBackToUpload_Click

Add Reference of ASPJpeg

Ahead of the previously mentioned techniques we have to add ASPJpeg Reference into our Bin folder, follow the process to incorporate an ASPJpeg Reference File.

Step 1: Right click on the Bin Folder / Root Folder and select Add Reference


Step 2: Browse the AspJpeg.dll file from your Hard Drive and click OK to continue.


Lets have a look your added reference picture.


Lets have a look your added reference picture.

using System;
using System.IO;
using System.Web;
 
String tempPath = HttpContext.Current.Server.MapPath("uploads/temp/");
String savePath = HttpContext.Current.Server.MapPath("uploads/images/");
 
protected void btnUpload_Click(object sender, EventArgs e)
    {
        // Generate Random String
        String NewID = System.Guid.NewGuid().ToString("N").Substring(0, 10);
 
        // initialize variables
        String fileName = String.Empty;
        String fileExtension = String.Empty;
        Boolean fileOK = false;
        Boolean fileSaved = false;
 
        // Check: If file has been selected to upload
        if (FileUpload1.HasFile)
        {
            Session.Add("WorkingImage", FileUpload1.FileName);
            fileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
            String[] allowedExtensions = { ".jpg", "jpeg", ".png", ".gif" };
            for (int i = 0; i < allowedExtensions.Length; i++)
                if (fileExtension == allowedExtensions[i]) fileOK = true;
        }
 
        // Check: If fileOK variable is equest to true
        if (fileOK)
        {
            try
            {
                fileName = NewID + fileExtension;
                String tempLocation = tempPath + fileName;
                FileUpload1.PostedFile.SaveAs(tempLocation);
 
                ASPJPEGLib.IASPJpeg objJpeg = new ASPJPEGLib.ASPJpeg();
                objJpeg.Open(tempLocation);
                objJpeg.PreserveAspectRatio = 1;
 
                const int maxWidth = 300;
                if (objJpeg.OriginalWidth > objJpeg.OriginalHeight)
                {
                    objJpeg.Width = maxWidth;
                    objJpeg.Height = objJpeg.OriginalHeight * maxWidth / objJpeg.OriginalWidth;
                }
                else
                {
                    objJpeg.Height = maxWidth;
                    objJpeg.Width = objJpeg.OriginalWidth * maxWidth / objJpeg.OriginalHeight;
                }
 
                // Send generated image Width and Height to JavaScript for the Jcrop preview
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "getImageDimensions", "getImageDimensions(" + objJpeg.Width + "," + objJpeg.Height + ");", true);
 
                // Create new file with new width: 300
                objJpeg.Save(tempLocation);
 
                // Save Temprary Location and Filename into Session
                Session["TempLocation"] = tempLocation;
                Session["TempFileName"] = fileName;
                fileSaved = true;
            }
            catch (Exception ex)
            {
                lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                lblError.Visible = true;
                fileSaved = false;
            }
        }
        else
        {
            lblError.Text = "Cannot accept files of this type.";
            lblError.Visible = true;
        }
 
        // Check: if fileSaved variable is equest to true
        if (fileSaved)
        {
            step1.Visible = false; // Panel #1: Disappear
            step2.Visible = true; // Panel #2: Appear
 
            // Fill the Origial Image and Preview with the below source
            imgCrop.ImageUrl = "~/uploads/temp/" + fileName;
            preview.ImageUrl = "~/uploads/temp/" + fileName;
        }
 
    }
 
    protected void btnCrop_Click(object sender, EventArgs e)
    {
        String newFileName = savePath + Session["TempFileName"];
 
        // Create instance for AspJpeg
        ASPJPEGLib.IASPJpeg objJpeg1 = new ASPJPEGLib.ASPJpeg();
 
        // Open file from temprary location
        objJpeg1.Open(Session["TempLocation"].ToString());
 
        // Set Quality: 80
        objJpeg1.Quality = 80;
 
        // Image Cropped with selected area
        objJpeg1.Crop(int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(X2.Value), int.Parse(Y2.Value));
 
        // Save file into uploads/images
        objJpeg1.Save(newFileName);
 
        step2.Visible = false; // Panel #2: Disappear
        pnlCropped.Visible = true; // Active Panel Cropped Image
 
        imgCropped.ImageUrl = "~/uploads/images/" + Session["TempFileName"];
 
        // Delete temprary file
        CancelCrop();
    }
 
    protected void lbBackToUpload_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        CancelCrop();
 
        step1.Visible = true; // Panel appear #1
        step2.Visible = false; // Panel disappear #2
    }
 
    private void CancelCrop()
    {
        String tmpFileLocation = Session["TempLocation"].ToString();
 
        // Delete temprary files if exists
        if (File.Exists(tmpFileLocation))
            File.Delete(tmpFileLocation);
    }

Lastly, we've got finished the Jcrop Picture Cropping script. You'll be able to make use of your own FileUpload method for image uploading. I'm also impressed by a person who experienced developed great structural code. therefore, I followed him. Sorry to forgot reference website link.



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