File Uploader in ASP.NET and ASP.NET MVC

A class to upload files in ASP.NET and ASP.NET MVC.

Introduction

Uploading files is a common scenario and an essential part of many web applications. Here I have created a class which can be used to upload files easily. The uploader class automatically validate all the necessities i.e. validation of upload directory, file extensions etc.

Background

There are plenty of resources on uploading a file in ASP.NET. But I have felt to have a class which would be easier and customizable as well as can perform validation, add prefix and/or suffix to file, encrypt filename, allow choice to overwrite existing file or not and so on. You have to just set the necessary properties you need. You can use it in your ASP.NET as well as ASP.NET MVC application.

Using this Class

Here I am giving an example to use this class.

    Uploader uploader = new Uploader();
 
    uploader.UploadPath     = Server.MapPath("~\Content\Uploads");
    uploader.IsLowerName    = true;
    uploader.IsEncryptName  = false;
 
    uploader.Prefix = "Hello_";
    uploader.Suffix = "_Boom";
 
    uploader.AllowedExtensions.Add(".jpg");
    uploader.AllowedExtensions.Add(".jpeg");
    uploader.AllowedExtensions.Add(".gif");
    uploader.AllowedExtensions.Add(".png");
 
    bool success = uploader.DoUpload("MyFile");
 
    if (success)
    {
        //TODO: Code to handle success
    }
    else
    {
        //TODO: Code to handle failure
    }

Here MyFile is the name of file input type.

 <!-- In Html -->
<input type="file" name="MyFile" id="MyFile" />
<%--In tradition ASP.NET --%>
<asp:FileUpload ID="MyFile" runat="server" />

There is an overload of DoUpload() method. You can either pass the name of the file input as above or HttpPostedFile file object as follows.

HttpPostedFile postedFile = HttpContext.Current.Request.Files["MyFile"] as HttpPostedFile;
uploader.DoUpload(postedFile);

There is also a method by which you can get the HttpPostedFile object by supplying the name of the file input.

HttpPostedFile postedFile = uploader.GetHttpPostedFile("MyFile");
uploader.DoUpload(postedFile);

Configuration Settings

General Settings
UploadPath Full path where file should be uploaded exculding the filename. (Mandatory).
UploadName The name which should be used to save the uploaded file with extension. (Optional).
Prefix The prefix to the filename. (Optional).
Suffix The suffix to the filename. (Optional).
Conditional Settings
MinSize The minimum size of the file in bytes.
MaxSize The maximum size of the file in bytes.
IsOverwrite Whether a file is to overwrite or not.
IsEncryptName Whether a file name is to encrypt or not.
IsLowerName Whether a file name is to lower or not.
IsRemoveSpace Whether space is to be removed from a file name or not.
AllowedExtensions The allowed file extensions with period.
IsRemoveSpace The allowed mime types.
Object Properties
UploadError The object of UploadError class. This class holds error code and error message.
PostedFile The object of PostedFile class. This class holds different informations of posted file.
UploadedFile The object of UploadedFile class. This class holds different informations of uploaded file.
Properties of UploadError Class
Code The error code.
Message The error message.
Properties of PostedFile and UploadedFile Class
FileName The file name with extension.
RawName The file name excluding extension.
FileExtension The file extension with period.
MimeType The file MIME type.
FullPath The absolute path including the file name.
FilePath The absolute path to the file excluding the file name.
FileSize The size of the file in bytes.
IsImage Whether the file is image or not.

If your upload is not succeded then you can get the error code and message by UploadError property. For example:

strring erroCode    = uploader.UploadError.Code;
string errorMessage = uploader.UploadError.Message;

Remember, here error code is not actual http error number. I have used numbers from 1 to 10 so that corresponding message can be customized.

On the other hand, if your upload attempt is succeeded, then you can use information related to the posted file as well as uploaded file by PostedFile and UploadedFile. For example:

string previousFilename = uploader.PostedFile.FileName;
string previousFilePath = uploader.PostedFile.FilePath;
 
string uploadedFilename = uploader.UploadedFile.FileName;
string uploadedFilePath = uploader.UploadedFile.FilePath;

Enjoy this!

Downloads

Download Uploader class here. Uploader Class

Download Uploader Sample In ASP.NET here. Uploader Sample In ASP.NET

Download Uploader Sample In ASP.NET MVC here. Uploader Sample In ASP.NET MVC

Here is the .Net 2.0 version of Uploader class. Uploader Class For ASP.NET 2.0 Application

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Using Asirra in ASP.Net MVC

A simple helper to integrate and validate Asirra in ASP.Net MVC.

People use CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) to prevent their websites from automatic posting. Asirra is such a technique which can be used to protect websites from automatic posting.

What is Asirra

Asirra is a human interactive proof that asks users to identify photos of cats and dogs. It’s powered by over three million photos from Petfinder.com.

Asirra (Animal Species Image Recognition for Restricting Access) is a HIP that works by asking users to identify photographs of cats and dogs. This task is difficult for computers, but people can accomplish it quickly and accurately. You can learn more about Asirra here MSR Asirra: A Human Interactive Proof.

How to use it

You can easily use it in your website. You can find details of how to use it from MSR Asirra Project – Installation.

I have prepared a helper to use it in ASP.Net MVC application and I will show how to use this helper in your website. First look at the following sample pictures of user registration form.

Integrate Asirra challenge

Import the namespace at the top of your view aspx page.

<%@ Import Namespace="Valentica.Helpers" %>

Then call the GenerateAsirra() method of the helper where you like to put the Asirra challenge. For example:

<%= AsirraHelper.GenerateAsirra() %>
 
// Or
// You can control where the big version of the photos appear by
// changing EnlargedPosition to Top, Bottom, Left, or Right
<%= AsirraHelper.GenerateAsirra(EnlargedPosition.Right) %>
 
// Or
// You can control the aspect ratio of the box by changing rowsPerCell value 
<%= AsirraHelper.GenerateAsirra(4) %>
 
// Or
<%= AsirraHelper.GenerateAsirra(EnlargedPosition.Right, 4) %>

Perform client side validation

To validate Asirra in client side use the following steps.

Step 1:

Call MySubmitForm() method in onsubmit properties of your form. For example:

<form id="mainForm" action="/Account/Register" method="post"
         onsubmit="return MySubmitForm();">

Step 2:

Then simply use the following javascript code.

<script type="text/javascript">
    var passThroughFormSubmit = false;
 
    function MySubmitForm()
    {
         if (passThroughFormSubmit) {
              return true;
         }
         // Do site-specific form validation here, then...
         Asirra_CheckIfHuman(HumanCheckComplete);
         return false;
    }
 
    function HumanCheckComplete(isHuman)
    {
         if (!isHuman)
         {
              alert("Please correctly identify the cats.");
         }
         else
         {
              passThroughFormSubmit = true;
              formElt = document.getElementById("mainForm");
              formElt.submit();
         }
    }
</script>

Server side validation

In your action field together with other validation use IsValidate() method of AsirraHelper.

// Validate Assira Here
if (AsirraHelper.IsValidAsirra(Request.Form["Asirra_Ticket"]))
{
    ModelState.AddModelError("Asirra_Ticket", "Asirra Invalid");
}

Try it now!

References

1. MSR Asirra: A Human Interactive Proof
2. MSR Asirra Project – Installation

Source Codes

You can download full source code from here. Asirra Sample

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Creating Custom FCKeditor Combo Plugin

A simple demonstration on how to create custom FCKeditor combo plugin.

Introduction:

FCKeditor is a widely used html based text editor. In an earlier post I have shown how to integrate FCKeditor in ASP.Net. You can easily create and install custom plugin for FCKeditor.

Here I have prepared a custom month combo plugin. User can select month from January to December and insert the selected month into the editor.

Complete Scenario

Description:

Step 1:

Create a folder named “monthcombo” in “\editor\plugins” folder. Create a javascript file named “fckplugin.js” in the folder “monthcombo”. Now open the “fckplugin.js” file by any editor.

Step 2:

Inititalize the month combo as follows.

// Initialize the Month Combo
var monthCombo = function (name)
{
  this.Name = name;
}

Step 3:

Create function for executing the command.

// Execute the Command
monthCombo.prototype.Execute = function(itemText, itemLabel) 
{
    if (itemText != "")
        FCK.InsertHtml("<span>" + itemText + "</span>");
}

Step 4:

Create function for managing the plugin behavior.

// Manage the plugin behavior
monthCombo.prototype.GetState = function()
{
    return FCK_TRISTATE_OFF; // FCK_TRISTATE_OFF or  FCK_TRISTATE_ON
}

Step 5:

Register the month combo command.

// Register the command.
FCKCommands.RegisterCommand( 'MonthCombo' ,  new  monthCombo('Month Combo') ) ;

Step 6:

Create the toolbar button and set its prototype as follows.

// Create the toolbar button.
var monthComboToolbar = function(tooltip,  style)
{
    this.CommandName   = 'MonthCombo';
    this.Label         = this.GetLabel();
    this.Tooltip       = tooltip?  tooltip : this.Label;
    this.Style         = style;  //FCK_TOOLBARITEM_ICONTEXT OR FCK_TOOLBARITEM_ONLYTEXT
}
 
// Set the toolbar prototype.
monthComboToolbar.prototype = new  FCKToolbarSpecialCombo;

Step 7:

Create function for the label of the toolbar that is to be appeared on the toolbar.

// Label to appear in the FCK toolbar
monthComboToolbar.prototype.GetLabel  = function()
{
    return "Month Combo";
}

Step 8:

Add items to the combo list.

//Add the items to the combo list
monthComboToolbar.prototype.CreateItems  =  function(A)
{
    var months = Array("January", "February", "March",  "April",
                       "May", "June", "July",  "August",
                       "September", "October", "November",  "December");
 
    for (var i = 0; i < months.length; i++)
    {
        this._Combo.AddItem(months[i],  months[i]);
    }
}

Step 9:

Register the combo with the FCKeditor.

//Register the combo with the FCKeditor
FCKToolbarItems.RegisterItem('MonthCombo' , new monthComboToolbar( 'Month Combo', FCK_TOOLBARITEM_ICONTEXT ) ) ; // FCK_TOOLBARITEM_ONLYICON or FCK_TOOLBARITEM_ONLYTEXT  or  FCK_TOOLBARITEM_ICONTEXT

Step 10:

Save the “fckplugin.js”. We are near the end. Now open the “fckconfig.js” file located in the root directory. Add the month combo plugin as follows:

//Add Month Combo Plugin
FCKConfig.Plugins.Add( 'monthcombo' );

Step 11:

Finally, add this combo [‘MonthCombo’] to FCKConfig.ToolbarSets["Default"] or FCKConfig.ToolbarSets["Basic"] settings as follows.

FCKConfig.ToolbarSets["Basic"] = [
	['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About', 'MonthCombo']
] ;

Reference:

Creating & Installing a Plugin in FCKeditor

Conclusion:

Download the plugin here. MonthCombo

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Recovered My Hacked Site

I was in my village for Eid vacation and out of internet. After a one week leave, I came to the capital and have found my site had been hacked. I was surprised to see that. Below the picture of my hacked site.

MyHackedSite

MyHackedSite

First I thought, my htaccess file was made changed. But I noticed only the index file was changed. I have opened a supporting ticket to my hosting site and got the following reply, which I think may be helpful for others:

Here’s some information you can use to help to identify what may have happened and how to rectify it and possibly prevent it from happening again.

The two most common entry points for a compromised website are (1) vulnerable, typically out-of-date web scripts (blogs, forums, CMS, etc.) or (2) a compromised FTP/SSH user password.
1) All web scripts you have installed under your domain should always be kept up-to-date with the most recent version available from the vendors’ website, as these often contain security patches for known issues. Older versions of well-known and popular web software (including Wordpress, phpBB, PHPNuke, PostNuke, etc.) are known to have vulnerabilities that can allow injection and execution of arbitrary code. Also make sure not to store ‘archive’ versions of old software in an open web directory — if you intend to keep these they should be stored under your FTP user’s home directory, not under a domain directory. Finally, some plugins for popular software (such as Expose for Joomla) have been found to introduce similar vulnerabilities. It’s a good idea to search the internet for information about a plugin and ensure it doesn’t have any known issues before installing.

After updating your software, it is imperative that you go through all files under all directories for the user which has been compromised and ensure that any files which have been written to / modified have been removed. It is common for ‘hackers’ that exploit web scripts to upload nocuously-named scripts which they can use to further compromise the site more easily, even after the initial vulnerability is closed — including scripts to send spam mail or execute arbitrary shell commands under your account via a simple web page interface. A helpful tip for finding files of this nature is to look for files or directories that have timestamps that occurred since you last modified your site, or that occurred around the time that the ‘hack’ took place; still it is best to examine all files as even a single missed file can allow the site to be re-compromised.

2) A bit less frequently, FTPs password can be compromised and used to modify files. The most important part of securing your account in this case is to change your FTP user’s password via the (USERS > MANAGE USERS) -> “Edit” area of the control panel. Passwords should not contain dictionary words and should be a string of at least 8 mixed-case alpha characters, numbers, and symbols. The best option for selecting a new password is to use our “Pick a password for me” feature. Check that box near the bottom of the page then click on the “Save Changes” button. The system will generate a very strong random password for this account. It will be displayed on the next page. It is recommended to always use Secure FTP (SFTP) or SSH rather than regular FTP, which sends passwords over the internet in plaintext. You should not use any passwords that you’ve used with other services, and ideally you should never use the same password for email, control panel, and FTP/SSH. Finally, you should always ensure that you’ve got up-to-date virus/malware screening on your computer to ensure that it is not compromised itself.

I have updated my webscripts to latest version and thus found my site got back. Still now, I don’t know how my site had been hacked. Have you any idea? :)

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Pagination Class for ASP.NET MVC

A class for creating different types of pagination link in Asp.Net Mvc.

Pagination For Asp.Net Mvc

Pagination For Asp.Net Mvc

Introduction

I was looking for a pagination class to use in Asp.Net Mvc. I found ASP.NET MVC: PagedList<T> and ASP.NET MVC – Pagination View User Control. But I felt for an easier and customizable pagination class. I have developed many projects using CodeIgniter framework and that time I found their pagination class is pretty better and easier. So, I have decided to prepare a pagination class like this for Asp.Net Mvc.

Using the Code

Controller

In your controller, to get your current (i.e. selected) page number put this code snippet.

string pageString = "";
 
try
{
    pageString = Request.Url.Segments[3];
}
catch (Exception)
{
    pageString = null;
}
 
int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);

Here 3 is the segment which holds the page number. It can vary as per your URL.

Then use the pagination class as shown in the following example.

Pagination pagination = new Pagination();
 
pagination.BaseUrl      = "/Users/List/";
pagination.TotalRows    = totalRows;
pagination.CurPage      = page;
pagination.PerPage      = 10;
 
string pageLinks = pagination.GetPageLinks();
 
int start   = (page - 1) * pagination.PerPage;
int offset  = pagination.PerPage;

In BaseUrl you can write full path like "http://www.sitename.com/Controller/Action/" or relative path like "/Controller/Action/". Here "start" is the number from which row should be counted and "offset" is the number of rows should be returned. “totalRows” is the total number of rows.

Now you can use this "pageLinks" string which is the generated page link.

Next, set your data in the ViewData like the following.

ViewData["title"]       = "Pagination in Asp.Net Mvc";
ViewData["totalRows"]   = totalRows;
ViewData["result"]      = result;
ViewData["pageLinks"]   = pageLinks;

Here, "totalRows" is the total number of rows and "result" is the desired resultset.

View

In view page, you can show the page link as follows:

<% if ((string)ViewData["pageLinks"] != "")
   { %>
   <%= ViewData["pageLinks"] %>
   <br /><br />
<% } %>

Model

You can create a model and make two methods to get total rows and the data from table using LINQ, as shown in the following example.

public int GetTotalUsers()
{
    return new MyDataContext().Users.Count();
}
 
public List GetUsers(int start, int offset)
{
    var users = new MyDataContext().Users.Skip(start)
                                                 .Take(offset);
 
    return users.ToList();
}

Configuration Settings

General Properites
BaseUrl Full or relative URL to the controller/action (Mandatory).
TotalRows Total number of rows in your resultset (Mandatory).
CurPage Current page number, default 1 (Mandatory).
PerPage Number of items you want to show per page (Optional).
NumLinks Number of “digit” links before and after the current page number (Optional).
ItemType Item type enumeration value (Optional).
Link Properites
FirstLink The text to be shown in the “first” link on the left.
NextLink The text to be shown in the “next” page link.
PrevLink The text to be shown in the “previous” page link.
LastLink The text to be shown in the “last” link on the right.
Tag Properties
FullTagOpen The opening tag placed on the left side of the entire result.
FullTagClose The closing tag placed on the right side of the entire result.
FirstTagOpen The opening tag for the “first” link.
FirstTagClose The closing tag for the “first” link.
LastTagOpen The opening tag for the “last” link.
LastTagClose The closing tag for the “last” link.
CurTagOpen The opening tag for the “current” link.
CurTagClose The closing tag for the “current” link.
NextTagOpen The opening tag for the “next” link.
NextTagClose The closing tag for the “next” link.
PrevTagOpen The opening tag for the “previous” link.
PrevTagClose The closing tag for the “previous” link.
NumTagOpen The opening tag for the “digit” link.
NumTagClose The closing tag for the “digit” link.
ItemTagOpen The opening tag for the “Item”.
ItemTagClose The closing tag for the “Item”.

You can set configuration settings in three ways.

1. Set as regular property is set. Example:

objPagination.PerPage  = 10;
objPagination.PrevLink = "Prev";
objPagination.NextLink = "Next";

2. Put a Pagination.xml file in "Content" folder and create object of Pagination class as:

Pagination objPagination = new Pagination(true);

Pagination.xml file should be as following pattern as example.

<?xml version="1.0" encoding="utf-8" ?>
<Pagination>
    <NumLinks><![CDATA[5]]></NumLinks>
    <FullTagOpen><![CDATA[<p class='pagination'>]]></FullTagOpen>
    <FullTagClose><![CDATA[</p>]]></FullTagClose>
    <CurTagOpen><![CDATA[<span class='current'>]]></CurTagOpen>
    <CurTagClose><![CDATA[</span>]]></CurTagClose>
</Pagination>

3. Create a any xml file like the above Pagination.xml file and call the method LoadPaginationXml with the file full path as argument. Example:

objPagination.LoadPaginationXml("C:\MyProject\MyPagination.xml");

Different types of pagination

By this pagination class you can build different types of page link for your page. Just call the method GetPageLinks with your desired PaginationType as argument. Example:

objPagination.GetPageLinks(PaginationType.FirstPreviousNextLastItemRight);

If you want to display item set item type as follows:

objPagination.ItemType = ItemTypes.Page;

Conclusion

I think thats enough to use this pagination class easily. Bye for this time.

Download

You can download the Pagination class from here.

PaginationClass

You can download sample project from here.

PaginationInAspNetMvc

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Integrating FCKeditor in ASP.Net

Introduction

In Basic ASP.Net, FCKeditor can be easily integrated. Here is the link where I found that. http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Integration/ASP.NET

However, to integrate FCKeditor in ASP.Net MVC environment, we have to follow some tricky steps. Here I will show how to integrate using core javascript as well as using Jquery.

Using Javascript:

Step 1

Download the FCKeditor from http://www.fckeditor.net/download.

Step 2

Unzip the package and put in your project content directory. I liked to make a directory “Javascript” under “Content” directory and put “unzipped fckeditor” here. I have also put fckeditorapi.js in “Javascript” folder. You can get more information on FCKeditor API here

http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API

Step 3

I have added a MVC view file in Home folder and named it as “Fck.aspx”. To view this file, I included a method in HomeController, as follows.

/// <summary>
/// Show FCK Editor View Page
/// </summary>
public void Show()
{
    RenderView("Fck");
}

Step 4

In Fck.aspx, include the fckeditor.js and fckeditorapi.js file:

<script type="text/javascript" src="../../Content/Javascript/fckeditor/fckeditor.js"></script>
<script type="text/javascript" src="../../Content/Javascript/fckeditorapi.js"></script>

Include the following to replace textarea (named ‘content’) by FCKeditor. Here I have included InsertContent(), ShowContent() and ClearContent() methods to perform some extra actions.

<script type="text/javascript">
window.onload = function()
{
    var oFCKeditor = new FCKeditor( 'content' ) ;
    oFCKeditor.BasePath = "/Content/Javascript/fckeditor/" ;
    oFCKeditor.Height = 300;
    oFCKeditor.ReplaceTextarea() ;
}
 
function InsertContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content') ;
    var sample = document.getElementById("sample").value;
    oEditor.InsertHtml(sample);
}
 
function ShowContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content') ;
    alert(oEditor.GetHTML());
}
 
function ClearContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content');
    oEditor.SetHTML("");
}
</script>

Here is the html content:

<div>
  <input id="sample" type="text" />
  <input id="cmdInsert" type="button" value="Insert Content" onclick="InsertContent()" />

  <input id="cmdClear" type="button" value="Clear Content" onclick="ClearContent()" />
  <br /> <br />
  <textarea id="content" cols="30" rows="10"></textarea>
  <br />
  <input id="cmdShow" type="button" value="Show Content" onclick="ShowContent()" />
</div>

Step 5

Now build the application and run. Click the “FCK Editor” link and get the result.

FCKEditor in ASP.Net

Using JQuery

Step 1

Download jquery from http://www.jquery.com. I have put jquery-1.2.6.pack.js and jquery.FCKEditor.js in my “Javascript” folder”.

Step 2

I have added a MVC view file in Home folder and named it as “FckJquery.aspx”. To view this file, I included a method in HomeController, as follows.

/// <summary>
/// Show FCK Editor By JQuery
/// </summary>
public void View()
{
    RenderView("FckJquery");
}

Step 3

In FckJquery.aspx, include the jquery-1.2.6.pack.js, fckeditor.js and jquery.FCKEditor.js file:

<script type="text/javascript" src="../../Content/Javascript/jquery-1.2.6.pack.js"></script>
<script type="text/javascript" src="../../Content/Javascript/fckeditor/fckeditor.js"></script>
<script type="text/javascript" src="../../Content/Javascript/jquery.FCKEditor.js"></script>

Include the following to replace textarea (named ‘content’) by FCKeditor. Here I have included InsertContent(), ShowContent() and ClearContent() methods to perform some extra actions.

<script type="text/javascript">
$(document).ready(function(){
    $.fck.config = {path: '/Content/Javascript/fckeditor/', height: 300 };
    $('textarea#content').fck();
});
 
function InsertContent()
{
    var sample = document.getElementById("sample").value;
    $.fck.insertHtml('fck1', sample);
}
 
function ShowContent()
{
    alert($.fck.content('fck1', ''));
}
 
function ClearContent()
{
    $.fck.clearHtml('fck1');
}
</script>

Here is the html content:

<div>
  <input id="sample" type="text" />
  <input id="cmdInsert" type="button" value="Insert Content" onclick="InsertContent()" />

  <input id="cmdClear" type="button" value="Clear Content" onclick="ClearContent()" />
  <br /> <br />
  <textarea id="content" cols="30" rows="10"></textarea>
  <br />
  <input id="cmdShow" type="button" value="Show Content" onclick="ShowContent()" />
</div>

Step 4

In jquery.FCKEditor.js file, I have included two functions. Function insertHtml() inserts html content into fckeditor and clearHtml() clears the content.

// insert Html Content
insertHtml: function(i, v) {
  try{
    var x = FCKeditorAPI.GetInstance(i);
 
    if(v) x.InsertHtml(v);
    else return '';
  }
  catch(e) { return ''; };
},
 
// clear Html Content
clearHtml: function(i) {
  try{
    var x = FCKeditorAPI.GetInstance(i);
 
    x.SetHTML('');
  }
  catch(e) { return ''; };
},

Step 5

Now build the application and run. Click the “FCK Editor By JQuery” link and get the result. Enjoy It!

Source Code

Here is the source code FCKeditorMvcDemo

References

http://docs.fckeditor.net

http://www.jquery.com

http://www.fyneworks.com/jquery/FCKEditor

Conclusion

Next I will try to give some demonstration on how to build plugins in FCKeditor. Till then bye.

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

Captcha Plugin in CodeIgniter

CAPTCHACompletely Automated Public Turing test to tell Computers and Humans Apart. It is used in webpages to protect your page from automatic posting from outside of the site. CodeIgniter framework has a plugin named “captcha_pi.php” in plugins folder. Here I’ve demonstrated an example how to use this captcha plugin in your website built in CodeIgniter framework.

Make a controller named "captcha.php" and place in “controllers” folder. This controller is as follows:

<?php
class Captcha extends Controller
{
  public function __construct()
  {
    parent::Controller();
 
    $this->load->model('captcha_model');
 
    session_start();
  }
 
  public function index()
  {
    if(empty($_POST))
    {
      $captcha = $this->captcha_model->generateCaptcha();
 
      $_SESSION['captchaWord'] = $captcha['word'];
 
      $data['captcha'] = $captcha;
 
      $this->load->view('show_view', $data);
    }
    else
    {
      //check captcha matches
      if(strcasecmp($_SESSION['captchaWord'],
                   $_POST['confirmCaptcha']) == 0)
      {
        $this->load->view('success_view');
      }
      else
      {
        $this->load->view('failure_view');
      }
    }
  }
}
?>

Here I’ve made a model named "captcha_model" that has a method generateCaptcha(), which generates the captcha using CodeIgniter captcha plugin and returns the array. Captcha word is saved in session and after submitting the form this session word is compared with the posted word for matching.

If matches which is in (strcasecmp($_SESSION['captchaWord'], $_POST['confirmCaptcha']) == 0), then success is shown. Otherwise failure is shown. Here I’ve used strcasecmp() function of php to compare the word as case-insensitively. If u want user to enter the captcha words as they are shown (i.e. capital letter in capital and small letter in small), then you can use strcmp() function.

The captcha_model.php is as follows:

<?php
class Captcha_model extends Model
{
  private $vals = array();
 
  private $baseUrl  = 'http://localhost/captchademo/';
  private $basePath = 'D:/apache2triad/htdocs/captchademo/';
 
  private $captchaImagePath = 'tmp/captcha/';
  private $captchaImageUrl  = 'tmp/captcha/';
  private $captchaFontPath  = 'c:/windows/fonts/verdana.ttf';
 
  public function __construct($configVal = array())
  {
    parent::Model();
 
    $this->load->plugin('captcha');
 
    if(!empty($config))
      $this->initialize($configVal);
    else
      $this->vals = array(
                 'word'             => '',
                 'word_length'   => 6,
                 'img_path'       => $this->basePath
                                 .  $this->captchaImagePath,
                 'img_url'        => $this->baseUrl
                                 . $this->captchaImageUrl,
                 'font_path'      => $this->captchaFontPath,
                 'img_width'      => '150',
                 'img_height'     => 50,
                 'expiration'      => 3600
               );
  }
 
  /**
   * initializes the variables
   *
   * @author     Mohammad Jahedur Rahman
   * @access     public
   * @param     array     config
   */
  public function initialize ($configVal = array())
  {
    $this->vals = $configVal;
  } //end function initialize
 
  //---------------------------------------------------------------
 
  /**
   * generate the captcha
   *
   * @author     Mohammad Jahedur Rahman
   * @access     public
   * @return     array
   */
  public function generateCaptcha ()
  {
    $cap = create_captcha($this->vals);
 
    return $cap;
  } //end function generateCaptcha
}
?>

You have to change the $baseUrl, $basePath, $captchaImagePath, $captchaImageUrl and $captchaFontPath etc. To store the captcha images at first I’ve created a folder “tmp” and sub-folder “captcha” in the main directory where index.php exists. If u run on server be sure this two folder are given write permission.

By default, Captcha plugin generates 8 words in length. But I desire to very this length. So, I’ve made a little change in this plugin. In line 156 of "captcha_pi.php" there was

$defaults = array('word' => '', 'img_path' => '',
                 'img_url' => '', 'img_width' => '150',
                 'img_height' => '30', 'font_path' => '',
                 'expiration' => 7200);

which I made

$defaults = array('word' => '', 'word_length' => 8,
                 'img_path' => '', 'img_url' => '',
                 'img_width' => '150', 'img_height' => '30',
                 'font_path' => '', 'expiration' => 7200);

Next, in line 226, there was

for ($i = 0; $i < 8; $i++)

which I made

for ($i = 0; $i < $word_length; $i++)

Now if u pass word_length as parameter then it will generate captcha image of word length as you specify.

Captcha

You can download the whole package from here.

captchademo

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis

CakePHP – How to Run “Hello World” Program

I found that, novice programmers always face problem while trying to run CakePHP for the first time. So, here I’m describing a “Hello World” program in CakePHP.

1. First download the CakePHP from http://www.cakephp.org. You can download Stable: 1.1.19.6305 package or Beta: 1.2.0.6311 package.

2. Make a folder in your htdocs folder named “hello” and unzip the CakePHP package in that folder. Your files and folders will be like:

htdocs/hello
           /app
           /cake
           /docs
           /vendors
           /index.php
           .htaccess

3. Now copy app_controller.php file from .cakelibscontrollerapp_controller.php to .app folder (.appapp_controller.php).

4. Copy .cakelibsmodelapp_model.php to .app folder (.appapp_model.php).

5. Make a controller hello_controller.php in .appcontrollers. Content of this controller.

<?php
 
class HelloController extends AppController {
  function index () {}
  function show () {
    $this->set('test', 'Hello World');
  }
}
?>

5. Make a model hello.php in .appmodels. Content of this model.

<?php
 
class Hello extends AppModel {
 
  function index () { }
}
?>

6. Create a folder “hello” in .appviews. Then make a view file "show.ctp". Content of this file.

<html>
<head><title>Hello World Program</title>
<head>
<body>
<h1><?php echo $test; ?></h1>
</body>
</html>

7. Open database.php in .appconfig folder and provide login, password, database etc. as your settings. Be sure that you have a table named “hello” in your provided database.

8. Enable mod_rewrite in your httpd.conf file. Uncomment (remove #).

LoadModule rewrite_module modules/mod_rewrite.so

Then restart your apache service.

Now you are ready to run this program. http://localhost/hello/hello/show

It will show “Hello World” in your browser.

convert this post to pdf.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • DotNetKicks
  • DZone
  • Furl
  • email
  • TwitThis