Store images on Flickr using Flickrnet.dll and ASP.NET MVC

Filed in ASP.NET MVC | C# 3 Comments

For one of my recent projects I had to use Flickr as an image repository, so this code just shows how I was able to do that with the help of the fantastic Flickrnet.dll library. You can download the latest Flickrnet library here: http://flickrnet.codeplex.com/. You can also download the article’s full working Flickr demo code.

Getting Started

Before we dive into the MVC portion, you have to make sure you have installed the flickrnet.dll file, referenced it, and added the appropriate web.config elements.

configSections element

Append the following element after the default sectionGroup:
<section name="flickrNet" type="FlickrNet.FlickrConfigurationManager,FlickrNet"/>

And setup your database connection strings

Flickrnet element

Add the following element before the appSettings element:
<flickrNet apiKey="YOUR_API_KEY" secret="YOUR_SECRET" cacheDisabled="true"/>

appSettings element

Add the following keys to the appSettings element:

<add key="FlickrAuthtoken" value="YOUR_FROB/TOKEN" />
<add key="FlickrUserId" value="YOUR_USERID"/>


Click on the thumbnail for a larger view


That is all you need to do in web.config. You get your apikey and secret through flickr. An awesome article off the flickrnet.codeplex site covers how to get your FROB/Token: http://blogs.msdn.com/coding4fun/archive/2006/11/22/1126978.aspx.

Database Setup

The images are going to be uploaded to Flickr, but we are going to keep references to the images in the database for later retrieval. Here is the table script if you are using MySQL:

CREATE TABLE  `sampledb`.`Image` (
  `ImageID` int(11) NOT NULL AUTO_INCREMENT,
  `ImageURL` varchar(250) DEFAULT NULL,
  `Tags` varchar(150) DEFAULT NULL,
  `FlickrID` varchar(50) DEFAULT NULL,
  `ImageURLThumbnail` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`ImageID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

or if you are using SQL Server:

CREATE TABLE  [SampleDB].[dbo].[Image] (
  ImageID int NOT NULL IDENTITY,
  ImageURL varchar(250) DEFAULT NULL,
  Tags varchar(150) DEFAULT NULL,
  FlickrID varchar(50) DEFAULT NULL,
  ImageURLThumbnail varchar(250) DEFAULT NULL,
  PRIMARY KEY (ImageID)
);

Once the database is setup, all we have left is the code for uploading, storing, and retrieving the images.

Uploading Images into Flickr

This part is easier than you think. We start out with a typical upload form. For this sample we are going to only have a file input control and a textbox to store our tags:

<form method="post" enctype="multipart/form-data" id="form1" action="/Home/Index">
        <b>Image</b><br />
        <input type="file" name="NewImageName" id="NewImageName" />
        <br /><br />
        <b>Tags</b><br />
        <input type="text" name="NewImgTags" id="NewImgTags" />
        <br />
        <input type="submit" value="Upload" />
    </form>

Nothing controversial there, moving on to the controller is where we find the meat. The first thing the controller needs is a reference to the Flirckrnet.dll and to System.Configuration, so you add your using statements:

using FlickrNet;
using System.Configuration;

Next up is creating the Index post method. Here, we reference the Flickrnet object and upload the photo. At this point, Flickr takes the image, and depending upon the size and dimensions, will resize it into any of five different sizes: square, thumbnail, small, medium, and large.

We then loop through the different sizes Flickr sends back, and store the thumbnail and large image urls into our table. Below is part of the controller method that uploads the image, and then loops through the sizes. You can download a full working sample here.

var flickr = new Flickr
{
    AuthToken = ConfigurationManager.AppSettings["FlickrAuthtoken"]
};

//
//  Upload the image, title, tags, security settings
//
var flickr_id = flickr.UploadPicture(file.InputStream, ImageTitle, ImageDescription, ImageTags, IsPublic,IsFamily,IsFriends);

//
//  Loop through links to resized images up on flickr
//  and store in the database
//
var flickrPhotos = flickr.PhotosGetSizes(flickr_id);

Image newImage = new Image();
newImage.FlickrID = flickr_id.ToString();

//
//  I only care about the thumbnail and the large image, but
//  you can store all of them (when applicable)
//
for (int i = 0; i < flickrPhotos.SizeCollection.Length; i++)
{
    switch (flickrPhotos.SizeCollection[i].Label)
    {
        case "Square":
            break;
        case "Thumbnail":
            newImage.ImageURLThumbnail = flickrPhotos.SizeCollection[i].Source;
             break;
        case "Small":
             break;
        case "Medium":
             break;
        case "Large":
             newImage.ImageURL = flickrPhotos.SizeCollection[i].Source;
             ViewData["NewUrl"] = flickrPhotos.SizeCollection[i].Source;
             break;
    }
}

newImage.Tags = ImageTags;
newImage.CreateAndFlush();

The code sample then sends the large image url from Flickr back down to the browser to preview. Below is a video of the code in action:

, ,

Check username availability with jQuery, ASP.NET MVC, C#

Filed in ASP.NET MVC | C# | jquery 5 Comments

This post shows how to add dynamic username availability lookup to an ASP.NET MVC view, using jQuery and C#. There are three parts to the solution: the html form, jQuery function, and the controller.

Html form

This part is pretty simple: a textbox for the username field with an onchange event, a div to hold the lookup results, and a lookup button.

    <h3>Username</h3>
    <%= Html.TextBox("Username", "", new { @onchange = "CheckAvailability()" })%>
    <div style="display:inline;" id="usernamelookupresult"></div><br/>
    <input type="button" value="Check Availability" onclick="CheckAvailability()" />
</code>

jQuery Username Lookup

This is where the magic happens. Well, nothing really magical, just a jQuery call to a controller, passing in the username value. In the example below, the function processing the result looks for a 0 to indicate the username is available. You can modify that to be whatever you want.


    function CheckAvailability() {
        $.post("/Home/CheckAvailability",
        { Username: $("#Username").val()},
            function(data) {
                var myObject = eval('(' + data + ')');
                var newid = myObject;
                if (newid == 0) {
                    $("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
                }
                else {
                    $("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
                }
        });
    }

Controller

This is where your business logic lives, and is where the lookup occurs. For this exercise, we are keeping it simple, but you can see where to add your database lookup.


    public ActionResult CheckAvailability(string Username)
    {
            int Taken = 0;
            //  This is where you add your database lookup
            if (Username == "username")
            {
                Taken = 1;
            }
            return Json(Taken);
    }

Download Sample Application

Below is a quick clip to show the code from the downloadable sample in action:

,

Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVC

Filed in ASP.NET MVC | C# | jquery 13 Comments

I recently had a requirement for a mapping application that required me to pass in longitude and latitude coordinates. It wasn’t realistic to have the user look those values up, so I had to figure out a way to automatically lookup the coordinates given a zip code.

There are tons of pay services (some of which I use), but for this project needed something free. I stumbled on http://www.geonames.org/ which has a great service. You can see their webservice documentation here: http://www.geonames.org/export/web-services.html.

Ok, let’s get started:

Web form

These are the input fields we will use to perform the lookup. We are going to have three textboxes, one which has an onchange event.

    Zip Code<br/>
    <%= Html.TextBox("Zip", "", new { @onchange = "LookupCoordinates(this.value)" })%>
    <br/><br/>
    Latitude: <%= Html.TextBox("Lat") %>,
    Longitude:<%= Html.TextBox("Lon") %>

jQuery Function

This function is responsible for looking up the latitude and longitude coordinates, and populating the results into the textboxes. Note that I’m wiring in US as the country below. The country is an optional parameter, when entered gives you more relevant results. Otherwise you are going to have to write some kind of loop.

    function LookupCoordinates(zip) {
            $.post("/Home/LookupCoordinates",
            { Zip: zip, Country: "US" },
            function(data) {
                var result = eval('(' + data + ')');
                var coordinates = result.split(",");
                $("#Lat").val(coordinates[0]);
                $("#Lon").val(coordinates[1]);
            });
        }

Call Geonames.org

In this sample, the call to geonames.org is wired into the controller. In real life, you probably want to wrap it in some kind of helper or service class. There are a few using statements you will need:

using System.IO;
using System.Net;
using System.Xml;

The above namespaces are important because we are going to make a WebRequest, and then parse the Xml results. The webservice method we are going to call is:

http://ws.geonames.org/postalCodeSearch?postalcode=78702&maxRows=10&country=US

Since we know the Zip and the Country, we should in theory only get 1 result. Below is a screenshot of the elements returned for our 78702 search (Austin):

Onto the method:

    public ActionResult LookupCoordinates(string Zip, string Country)
    {
        string Lat = "";
        string Lon = "";
        string PostUrl = "http://ws.geonames.org/postalCodeSearch?postalcode=" + Zip + "&maxRows=10&country=" + Country;
        WebResponse webResponse = webRequest.GetResponse();
        if (webResponse == null)
        { }
        else
        {
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string Result = sr.ReadToEnd().Trim();
            if (Result != "")
            {
                // Load the response into an XML doc
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(Result);
                //  Navigate to latitude node
                XmlNodeList name = xdoc.GetElementsByTagName("lat");
                if (name.Count > 0)
                {
                    Lat = name[0].InnerText;
                }
                //  Navigate to longitude node
                name = xdoc.GetElementsByTagName("lng");
                if (name.Count > 0)
                {
                     Lon = name[0].InnerText;
                }
            }
        }
        return Json(Lat + "," + Lon);
    }

From there, the method returns the latitude and longitude in a comma separated string, the javascript call splits the results and populates each respective text box. Below is a video preview – really short, really lame, but you get to see the code in action:

,

Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures

Filed in ASP.NET MVC | C# | jquery 1 Comment

This post extends an earlier post I wrote for a basic auto complete/auto suggest textbox.

In this version, we are going to return a list of our favorite social media websites, by adding a new method to the prior post’s controller which allows thumbnail pictures to appear in the auto-suggest list.

New MVC Controller Method

We are going to create another JsonResult method in the controller to lookup the websites. For demo purposes, we are going to hardcode the list. In real life, you probably will be pulling the list from a database, which is covered in the earlier post.

public JsonResult GetWebsites(string searchString)
        {
            StringBuilder sb = new StringBuilder();

            //
            //  Creating a static list here for demo purposes. In your system, you probably
            //  will have images generated from the database, disk, flickr, etc.
            //
            List<string> sites = new List<string>();
            sites.Add("Blogger");
            sites.Add("Delicious");
            sites.Add("Digg");
            sites.Add("Facebook");
            sites.Add("Flickr");
            sites.Add("FriendFeed");
            sites.Add("Friendster");
            sites.Add("LinkedIn");
            sites.Add("MySpace");
            sites.Add("StumbleUpon");
            sites.Add("Technorati");
            sites.Add("Twitter");
            sites.Add("Yahoo");
            sites.Add("Yelp");
            sites.Add("YouTube");

            for (int i = 0; i < sites.Count; i++)
            {
                if (sites[i].ToLower().StartsWith(searchString.ToLower()))
                {
                    string ImageUrl = "/images/" + sites[i].ToString() + ".png";
                    sb.Append("<li onClick=\"fill('" + sites[i].ToString() + "');\"><img src=\"" + ImageUrl + "\" border=\"0\">&nbsp;" + sites[i].ToString() + "</li>");
                }
            }
            return Json(sb.ToString());
        }

The big addition is adding the <img> tag into the list item value, that’s it :-) Now for tweaking the jquery function from the orinigal post to call the new method:

function lookup(inputString) {
    $.post(“/LookupCode/GetWebsites”, { searchString: “” + inputString + “”},
    function(data) {
        var myObject = eval(‘(‘ + data + ‘)’);
        if (data.length > 0) {
        $(“#suggestions”).show();
        $( “#autoSuggestionsList”).html(‘<ul>’ + myObject + ‘</ul>’);
        }
    });
}

You can download the fully-function code project here:

Download Sample Application

Below is a video clip of the sample in action:

, , , ,

Import CSV or Tab Delimited Data with C#, ASP.NET MVC

Filed in ASP.NET MVC | C# 3 Comments

In this sample we are going to take a different approach to importing data from the traditional file upload method. This sample has a textarea and a button. Users will open their .csv or .txt file, copy the contents, paste them into the textarea, and submit.

Setting up the form

This part is pretty basic:

<textarea id="bulkcsvlist" name="bulkcsvlist" rows="20" cols="105"></textarea>
<input type="submit" value="Upload File" />

Create import method

This sample shows the basics of parsing and adding the records, which assumes is uploading into a Contact table, with the first two fields in the row being FirstName and LastName respectively. You probably want to bake in your security checks and data validation.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadAll(FormCollection f)
{
    string bulkcsvlist = f["bulkcsvlist"].ToString();

    //
    //    Split the rows into an array
    //
    string[] rows = bulkcsvlist.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

    for (int i = 0; i < rows.Length; i++)
    {
        //
        //    Split the tab separated fields (comma separated split commented)
        //
        //string[] dr = rows[i].Split(new  char[] {','});
        string[] dr = rows[i].Split(new char[] { '\t' });

        //
        //    Add Contact for current row
        //
        if (dr.Length > 0)
        {
                Contact c = new Contact();
                c.FirstName = dr[0].ToString();
                c.LastName = dr[1].ToString();
                c.CreateAndFlush();
                c = null;
        }
    }
}

Normally I’ll throw each successful add into a List<> so whoever is uploading can validate the records look right or do any post-upload polishing, and the errors into a ViewData to display so the user can fix whatever needs fixing.

If you want a working sample, let me know!

, ,

Dynamically populate dropdownlist in ASP.NET MVC

Filed in ASP.NET MVC | C# | jquery 5 Comments

There are a few different ways to dynamically populate a dropdownlist in MVC: you could use a classic ASP old school loop with a bunch of response.writes, you can store the list’s collection into ViewData and use an html helper, or you can use jquery. We’ll look at samples for each way.

Populate dropdownlist with response.writes

We will start out with the least elegant solution, but it does work nonetheless. So this is the code inside your view:

        <select id="ID" name="ID">
            <%
             Contact[] contacts = Contact.FindAll();
             for(int i=0; i < contacts.length;i++){ %>
             <option value="\&quot;&quot;">" + contacts[i].FullName + "</option>
             <% } %>
        </select>

Populate dropdownlist with ViewData

This method is better, and is baked right into MVC. The downside is you can only use it in MVC, and involves using ViewData (detailed ViewData definition), the View and the Controller. First we prepare the Controller:

public ActionResult Index()
{
    Contact[] contacts = Contact.FindAll();
    ViewData["Contacts"] = new SelectList(contacts,"ID","FullName", <span style="color:red;">[Selectedvalue]</span>);
    return View();
}

Selectedvalue – this optional parameter can be used to select a specific value, useful if you are displaying a form in edit mode.

The last part is binding the ViewData contents to a dropdownlist in the View:

    <%= Html.DropDownList("Contacts") %>

Populate dropdownlist with jQuery

This is the most flexible of the three, and can be used in web forms, php, MVC, etc. This method involves a jquery call in javascript:

    <script language="javascript" type="text/javascript">
        $(function() {
            $.getJSON("YOURPATH/Contact/ContactList", function(data) {
                var items = "<option selected></option>";
                $.each(data, function(i, item) {
                    items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
                });
                $("#ContactID").html(items);
        });
    </script>

The above function calls the ContactList method, which returns a ListItem collection. You then loop through the result, and add the options. Finally, the html contents of the dropdownlist are set. The MVC method that returns the contact list looks like this:

        public ActionResult OrganizationList()
        {
            Contact[] contacts = Contact.FindAll();
            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(contacts, "ID", "FullName"));
            }
            return View(contacts);
        }

, ,

TinyMCE samples with ASP.NET MVC

Filed in ASP.NET MVC | C# | Html | jquery 3 Comments

After using Telerik’s RadEditor control for years with all my asp.net web form applications, I found myself looking for a javascript alternative when I moved up to MVC. Having paid top dollar for RadEditor (which is a fine product!) and never used TinyMCE, I couldn’t imagine something free could be that good. Well it is! And really easy to use–whether in c#, vb, php, etc.–plus no nasty viewstate to bloat your page.

You can download code samples here.

Downloading files

The first step is visiting the TinyMCE website and downloading the files: http://tinymce.moxiecode.com/download.php. Make sure you select the “jQuery package” link.

Extract the zip file, and copy the actual script files (tinymce\jscripts directory) into a folder in your project. I typically have a scripts folder, and create a “tiny_mce” subdirectory to hold the files.

Setting references

If you have a master page, just add the following line into the top of the master page:

<script type="text/javascript" src="<%=Url.Content("~/scripts/tiny_mce/tiny_mce.js") %>"></script>

Otherwise add the same line to the top of each page that will use the TinyMCE editor. Next, you initialize the textareas to use TinyMCE. The following javascript snippet initializes every textarea on the page (or every single page if added in the master page) using the defaults:

<script type="text/javascript">

tinyMCE.init({
mode: "textareas",
theme: "advanced"
});

We will dive deeper into configuring the available buttons.

Samples

TinyMCE in a dialog

One common need is allowing users to edit text in a modal window. Combining jQuery’s dialog (http://www.billsternberger.net/asp-net-mvc/jquery-modal-dialog-without-the-x-button/) with TinyMCE is a simple and elegant solution.

First, initialize the dialog and add the click event to show the editor:

$(function() {
$("#texteditorform").dialog({
height: 300,
width: 520,
autoOpen: false
});
});

function ShowModalEditor() {
$("#texteditorform").dialog('open');
}

Next, add the button to show the editor:

<a onclick="ShowModalEditor()" href="#">Show modal text editor</a>

Next, create the dialog div with the textarea inside:

<div title="Text Editor" id="texteditorform">
Add something below:<br />
<textarea rows="5" cols="25" id="modalTextarea"&gt;&lt;/textarea><br /><br />
<input type="button" onclick="CloseModalEditor()" value="Save" /><br />
</div>

Toggle TinyMCE editor and textarea

Occasionally you may want to allow users to toggle between the advanced editor and the regular textarea. There is a simple function to pull this off. First, add the javascript function to handle the toggling:

function toggleEditor(id) {
if (!tinyMCE.get(id)) {
tinyMCE.execCommand('mceAddControl', false, id);
}
else {
tinyMCE.execCommand('mceRemoveControl', false, id);
}
}

Next, add a button that will allow the user to toggle:

<a href="#" onclick="javascript:toggleEditor('toggleTextarea');">Toggle</a>

Validate input value

To validate the user input of a TinyMCE-enabled editor, the standard jqeuery $(“#field”).val() method won’t work.  Instead, you need to use a TinyMCE method instead:

var theValue = tinyMCE.get('valueTextarea').getContent();

Make TinyMCE editor Read Only

Should you need to initialize a TinyMCE editor as readonly, all you have to do is add a line to the init:

$(function() {
$("#texteditorform").dialog({
<span style="color: #0000ff;">readonly: true</span>
});
});

Customize TinyMCE Editor buttons

Include underline, copy, paste, and other formatting options in toolbar

Customizing which buttons appear on the toolbar is really easy, below are some sample configurations. Setting and aligning the buttons are done in theme_advanced properties.

tinyMCE.init({
mode: "textareas",
theme: "advanced",
plugins: "style,iespell,searchreplace,contextmenu,paste,html",

//  Theme options #1
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
theme_advanced_buttons4: "",

//Theme options #2
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,|,fontselect,fontsizeselect",
theme_advanced_buttons2: "",

// Align and place toolbar
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The above are the two standard configurations I use. To view a full list of buttons, click here.

, , , ,

Export to Excel or CSV from ASP.NET MVC with C#

Filed in ASP.NET MVC | C# 3 Comments

Since programming way back in the Classic ASP days, at some point a client always wants to export an html grid into an Excel grid. In c#, that need didn’t disappear, but got a lot easier with GridView and the HtmlTextWriter. Finally reached that point in my ASP.NET MVC programming world, and quite frankly, am surprised it took this long, for this same need! But I digress. To pull this off, all we are really going to do is add an export method to a controller, most of which will look very familiar to asp.net web forms.

Add using statements

using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

We are going to use our dear old friend the GridView from web forms as a placeholder for our data, which is why we need the second using statement.

Create Controller Method

This one is pretty easy, consisting of three parts:

  • Creating the GridView placeholder
  • Binding the query results to the GridView placeholder
  • Dumping the results back to the browser

This example queries all contacts that have not unsubscribed, but you can imagine how easy it is to extend.
var contacts = Contact.FindAll();
var grid = new System.Web.UI.WebControls.GridView();

grid.DataSource = from contact in contacts
where contact.Unsubscribe == false
select new
{
ContactID = contact.ID,
FullName = contact.FullName,
Email = contact.Email
};
grid.DataBind();

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

That’s it!

, , , ,

ActiveRecord ICriterion Search Example (c#)

Filed in ActiveRecord | C# | NHibernate Leave a comment

In this post we are going to search using ICriterion to filter and sort the results. The only pre-requisite is that you properly configure your nHibernate environment, and like all my other code samples, know c#.

This one is pretty easy, first we are going to set the required references:

using NHibernate;
using NHibernate.Criterion;

Then we are going to define the ICriterion array. In this example, were are going to search for contacts that:

  • Belonging to the logged on owner (OwnerID variable).
  • LastName starts with some string entered by the user (LastNameValue variable)
  • Were added after a specific date chosen by the user (StartDate variable)

For the LastName like search, nHibernate gives us some options in the MatchMode enum: Anywhere, End, Exact, Start. In the snippet below, you will notice I went with Start.

Finally, we are going to sort the results by LastName, then FirstName.

ICriterion[] query = {
Expression.Eq("OwnerID", OwnerID),
Expression.Like("LastName",LastNameValue,MatchMode.Start),
Expression.Ge("CreationDate",StartDate) };

Order[] order = {
Order.Asc("LastName"),
Order.Asc("FirstName")};

Contact[] results = contact.FindAll(order, query);

That’s it!

Related articles:

,

Javascript, jQuery Rich text editor

Filed in C# | Html | jquery Leave a comment

I did a post earlier today (yes, I’m on a roll while jr. is sleeping!) on my Top 10 favorite jQuery functions and plugins. This post is dedicated to one of them: TinyMCE. In the past I’ve used editors like Telerik’s RAD Editor and obout’s Html Editor, both very powerful editors. I was turned on to TinyMCE not too long ago, and haven’t looked back since.

Integrating TinyMCE into any ASP.NET project (MVC included) is really easy, this post will cover the basics of setting up TinyMCE, and then some of the different variations available.

Setup TinyMCE

After you download TinyMCE, copy all the files into your project. Typically I’ll drop the TinyMCE folder into my “Scripts” directory. Once copied, you add a reference in either your page’s header:

<script type="text/javascript" src="<%=Url.Content("~/scripts/tiny_mce/tiny_mce.js") %>"></script>
1

<h2>Initialize TinyMCE</h2>
This is where the fun begins. You can show all the possible buttons, or just a subset of buttons if you need to keep it simple. Below is a "keep it simple" scenario, where only the most basic buttons are presented to the user:

1
tinyMCE.init({
mode: "textareas",
theme: "advanced",
plugins: "style,iespell,searchreplace,contextmenu,paste,html",

// Theme options
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The theme_advanced_buttons1 – 4 represent the rows where the buttons will appear. If you have a really wide textarea, you could theoretically show all the buttons on a single row. Consult the TinyMCE documentation for a detailed list of every single button.

Next is the generic “advanced” configuration I’ll use when I have a more savvy user. It gives users a html button so they can modify the markup:

tinyMCE.init({
mode : "textareas",
theme : "advanced",

theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

There are also times where I want to keep the custom toolbar, but also allow the user to show/hide the html. To accomplish that, you can add this hyperlink:

<a href="#" onclick="ToggleEditor('textareaID');">Show/Hide Html</a>

And this function:

function ToggleEditor(id)
{
if (!tinyMCE.get(id)) {
tinyMCE.execCommand('mceAddControl', false, id);
}
else {
tinyMCE.execCommand('mceRemoveControl', false, id);
}
}

, , ,

TOP