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 :: Tips to to using Microsoft Enterprise Library in ASP.NET for data access

clock August 23, 2016 19:37 by author Armend

Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from http://entlib.codeplex.com/ URL.

Step 2: Now extract the project to get

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll


And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

<add name="ASPHostPortalConnection" providerName="System.Data.SqlClient" connectionString="DataSource=ASPHostPortalSQLEXPRESS;Initial Catalog=ASPHostPortal;User ID=sa;Password=admintest;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>

Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.


Write the below 2 lines in the using block.

using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

Here I am writting some examples how to work on:

public DataTable Read()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetStoredProcCommand("[Topics_Return]");
            DataSet dataSet = db.ExecuteDataSet(dbCommand);
            return dataSet.Tables[0];
        }
        catch
        {
            return null;
        }
    }


The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.

But if the stored procedure is taking parameter then the code will be like:

 public int Save()
    {
        Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
        DbCommand dbCommand = db.GetStoredProcCommand("Topics_Save");

        db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");
        db.AddInParameter(dbCommand, "@Description", DbType.AnsiString, "Here is the Descriptiont");      
        db.AddInParameter(dbCommand, "@PostedBy", DbType.Int32, 4);       
        db.AddOutParameter(dbCommand, "@Status", DbType.AnsiString, 255);
        try
        {
            db.ExecuteNonQuery(dbCommand);
            return Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));
        }
        catch
        {
            return 0;
        }
    }

As the code explained above ASPHostPortalConnection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  "Here is the subject", "Here is the Descriptiont" or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

int returnValue=Convert.ToInt32(db.GetParameterValue(dbCommand, "Status"));

you can pass input parameter as below

db.AddInParameter(dbCommand, "@Subject", DbType.AnsiString, "Here is the subject");

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.
The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

public DataSet GetID(string title)
    {
       DataSet ds=new DataSet();

        try
        {
            Database db = DatabaseFactory.CreateDatabase("ASPHostPortalConnection");
            DbCommand dbCommand = db.GetSqlStringCommand("Select * FROM Topics where UserID=1 and
IsDeleted=0");          
            ds= db.ExecuteDataSet(dbCommand);
           return ds;         
        }
        catch
        {
            return ds;
        }
         return ds;
    }


Happy coding!!


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 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP 5. x, etc. Their service include 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 :: 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