Friday, August 31, 2012

Adding Facebook like button as Custom toolbar button in TinyMCE editor

To add a Facebook Like button to the TinyMCE editor, we need to use the setup callback function that enables us to add events to the editor instances before they get rendered.

Set 1: Add a Callback function in your TinyMCE init function

Add a callback function to your TinyMCE init function as follows. Make sure that all of your other configurations are taken care by separating each attribute values with comma (,)

tinyMCE.init({
   ...
   setup : function(ed) {
        ed.addButton('facebook', {
            title : 'Facebook Like',
            image : '[Your path for image]/facebook.png',
            onclick : function() {
                ed.focus();
                ed.selection.setContent('<fb:like send="false" width="450"  show_faces="true"></fb:like>');
            }
        });
    }
});

And add this new button to tool bar as follows:

theme_advanced_buttons4: “facebook"

By Default TinyMCE will strip all invalid tags from editor, to add the Facebook tags as valid tags in TinyMCE add the following line..

valid_elements: "fb:like[send|width|show_faces]"

The valid_elements option defines which elements will remain in the edited text when the editor saves
So, finally your TinyMCE init function looks like as follows

tinyMCE.init({
   ...
    valid_elements: "fb:like[send|width|show_faces]",
   setup : function(ed) {
        ed.addButton('facebook', {
            title : 'Facebook Like',
            image : '[Your path for image]/facebook.png',
            onclick : function() {
                ed.focus();
                ed.selection.setContent('<fb:like send="false" width="450"  show_faces="true"></fb:like>');
            }
        });
    },
     theme_advanced_buttons4: “facebook"
});

Step 2: Include the following JavaScript SDK of Facebook on your default Layout / Master page
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>


That’s it; you’ll get a custom toolbar button in your TinyMCE editor!

Friday, August 24, 2012

CSS: Importance of Optimization


A coherent way to make your website faster is to make the client code you send to the browser smaller. When looking to optimize your CSS files, one of the most influential measures you can employ is to use each declaration just one time.

Using every declaration just once means making strict use of selector grouping.
For example, you can combine these rules:

h3 {color: #cdcdef ;}
p {color: #cdcdef ;}
into a single rule:
h3, p {color: #cdcdef;}

While this simple example appears obvious, things are getting more interesting and harder to compute when talking about complex style sheets. In our experience, using each declaration just one time can reduce the CSS file size by 20-40% on average.

Let's have a look at another example:

h1, h2, h3 { font-weight: normal; }
a strong { font-weight: normal !important; }
strong { font-style: italic; font-weight: normal; }
#nav { font-style: italic; }
.note { font-style: italic; }
 
Applying the "any declaration just once" rule here results in:

h1, h2, h3, strong { font-weight: normal; }
a strong { font-weight: normal !important; }
strong, #nav, .note { font-style: italic; }
 
Note that the !important declaration makes a difference.
There are some things to keep in mind when applying this method:
  • First, very long selectors can render this method useless. Repeating selectors like html body table tbody tr td p span.example in order to have unique declarations doesn't save much file size. In fact, since "using each declaration just one time" might mean a higher number of selectors, this could even result in a bigger style sheet. Using more compact selectors would help, and would enhance the readability of your stylesheet.
  • Second, be aware of CSS regulations. When a user agent can't parse the selector, it must ignore the declaration block as well. If you run into trouble with this, just bend the " each declaration just one time " rule – and use it more than once.
Third and most importantly, keep the cascade in mind. No matter if you're sorting your style sheets in a convinced way or are very tranquil about the order in which rules appear in your style sheets, using each declaration just one time will make you change the order of the rules in one way or another. This order, however, can be decisive for a browser to decide which rule to apply. The easiest solution if you're running into any issues with this is to make an exception as well and use the declaration in question more than once

Monday, March 26, 2012

Placing and Debugging of Script with Older version of IE

Placing the JavaScript Block

This is not really an advanced topic, but it helps the guys who recently jumped in Web development Bus!
Usually the content in HTML document is processed in linear approach in the order in which it appears, from top to bottom. If you have any script block that uses immediate JavaScript code [the raw script statements which are not wrapped in a function) is executes as soon as it is processed. So, to avoid such problems you must place script blocks after any elements that it manipulates.

However if your script blocks wrapped inside function/uses functions that are called later in the page life cycle (e.g. event handling functions that are triggered in response to a client-side event) cool guys! You don’t need to worry. In this situation, the browser will process the entire page before your functions are triggered. As a result, you can place your script block anywhere in the HTML document! It’s your area, your rule! But, according to me <head > section is the popular choice.

I know developers are like Heroes, But please stop behaving like James Bond!!

Placing JavaScript in a separate file or even embedding it in an assembly doesn’t prevent users retrieving it and examining it (my Friend Sowmya always do it, whenever she found an interesting JavaScript, she’ll save it directly and starts modifying it. Just kidding! But it’s a fact) and even modifying their local copy of the webpage to use a tampered version of the script file. Therefore, you should never include any secrete algorithms or sensitive information in your JavaScript code. You should also make sure you repeat any JavaScript validation steps on the server because the user can circumvent client-side code

Debugging JavaScript

Visual Studio has an integrated JavaScript debugging. If you are using IE 8, you don’t need to take any steps to switch on client-side debugging. Visual studio sets it up automatically, regardless of your Internet Explorer settings

Oops! What about older version of IE?

With versions of IE 8, you need to explicitly enable script debugging. To do so follow these steps
  1. Choose Tools > Internet Options from the menu in IE
  2. In the Internet Options dialog box, choose the advanced tab
  3. In the list of settings, under the Browsing group, remove the check mark next to Disable Script Debugging (IE). You can also remove the check mark next to Disable Script Debugging (Other) to allow debugging for IE windows hosted in other applications
  4. Click Ok to apply your changes
When script debugging is switched on, you’ll be prompted to debug web pages with script errors, even on websites that you don’t control, even on Google too! (But I’m dam sure; they don’t have any script errors)

Friday, March 23, 2012

Dynamic member lookup in C# 4.0

A new pseudo-type dynamic is presented into the C# type system. It is considered as System.Object, but in addition, any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an operator on a value of such type is allowed without any type checking, and its tenacity is postponed until run-time. This is known as Duck typing

// Returns the value of Length property or field of any object which supports the length
int GetLengthOf(dynamic obj)
{
return obj.Length;
}

Now, consider followings

// a string has a Length property, So, It’s a valid
// returns 34 including white spaces
GetLengthOf("This time my Return is Huge! - DON");

// an array has a Length property, So, It’s a valid
// returns 3, holding 3 items in an array
GetLengthOf(new int[] { 1, 2, 3 });

// but not an integer - an exception will be thrown here at run-time
// returns exception as 'int' does not contain a definition for 'Length'
GetLengthOf(42); 

Dynamic method calls are triggered by a value of type "dynamic" as any implicit or explicit parameter (and not just a receiver). For example:

void PrintThis(dynamic obj)
{
// which overload of Write() to call is decided at run-time
Response.Write(obj);
}
 
PrintThis(3*6);   // ends up calling Write(int)
PrintThis("Don retruns"); // ends up calling Write(string)

Dynamic lookup is achieved using three distinct mechanisms: COM IDispatch for COM objects, IDynamicMetaObjectProvider DLR interface for objects implementing that interface, and reflection for all other objects. Any C# class can therefore intercept dynamic calls on its instances by implementing IDynamicMetaObjectProvider.

In case of dynamic method and indexer calls, overload resolution happens at run-time according to the actual types of the values passed as arguments, but otherwise according to the usual C# overloading resolution rules. Furthermore, in cases where the receiver in a dynamic call is not itself dynamic, run-time overload resolution will only reflect the methods that are exposed on the declared compile-time type of the receiver. . For example:

class BaseClass
{
  void Don(double me);
}

class DerivedClass : BaseClass
{
  void Don(int me);
}

dynamic me = 55;
BaseClass b = new DerivedClass();
// picks BaseClass.Don(double) because b is of type Base, and DerivedClass.Don(int) is not exposed
b.Don(me);
  
dynamic myself = b;
// picks DerivedClass.Don(int)
myself.Don(me); 

Any value returned from a dynamic member access is itself of type dynamic. Values of type dynamic are implicitly convertible both from and to any other type. In the code sample above, this permits GetLengthOf function to treat the value returned by a call to Length as an integer without any explicit cast. At run-time, the actual value will be converted to the requested type.

Thursday, March 22, 2012

Optional Parameters in C# 4.0

One of the amazing features from C# 4.0 is “Optional Parameters”. It was a feature of VB.Net but it’s now available in C# too. 

I’m not so much involved in this, but I do think there will be some situations where this will be useful to make code more concise.

Consider a standard situation with method overloading or constructor chaining.  In C# we’d have several methods with different signatures where, in effect, we’re indeed just after default values. 
Let’s take the consequence where we’ve got a little helper class to send emails in our application. In some cases we want to CC the administrator to troubleshoot issues; in some cases we want rich HTML emails rather than plain text. We might set up our methods like this:

public void SendMail(string ToAddress, string Body)
{
        this.SendMail(ToAddress, Body, true);
}

public void SendMail(string ToAddress, string Body, bool CcAdministrator)
{
        this.SendMail(ToAddress, Body, CcAdministrator, false);
}

public void SendMail(string ToAddress, string Body, bool CcAdministrator, bool IsBodyHtml)
{
        // the whole Implementation goes here
}

This is a typical method overloading concept and basically we will set default values (true for CC the Admin, and false for HTML emails). 

With new C# 4.0 we can now make the code more short by only having to implement 1 method:

public void SendMail(string ToAddress, string Body, bool CcAdministrator = true, bool IsBodyHtml = false)
{
        // the whole Implementation goes here
}

Now the Magic Begins!

If I call the method by passing a least parameters like this

SendMail("shreekumar@donreturns.com", "This time my return is huge!");

The IL (Intermediate Language) that the C# compiler will generate will actually be the equivalent of this: [See the default values for CcAdministrator and IsBodyHtml]

SendMail("shreekumar@donreturns.com", "This time my return is huge!", true, false);

Another good thing is, here we’ve the ability to skip any parameter (say by skipping a 3rd parameter CcAdministrator and pass 4th parameter IsBodyHtml in a function call) like this

SendMail("shreekumar@donreturns.com", "This time my return is huge!", IsBodyHtml:true);

This will allow the code to only pass 3 arguments for conciseness but still invoke the appropriate overload since the IL generated in that instance will be equivalent to this:

SendMail("shreekumar@donreturns.com", "This time my return is huge!", true, true);

Finally, I can say that “Overall It’s a great feature in C# library if used in the correct situations, it can improve our code efficiency greatly”