Sep 21

It is not the way to fight spams on blogs, but for professional look for websites, duplicate comments should not be allowed. This feature is common among most popular blogs and forums, so i bring this simple extension to add this feature to BlogEngine.

To enable this extension just upload it to your extension directory under App_Code.

The extension is attches with this post.

ValidateComments.cs (1,014.00 bytes)

Sep 12

YUI 3.0.0 From Yahoo!

Posted By Ahmed El-Kilani On 12 Sep 2009 4 Comments »

The Yahoo! next-generation JavaScript and CSS library, is a big step forward.
YUI team has improved the library; syntax is enhanced, API is more flexible and easy to use.

Featured Components:

  1. DataSource: YUI’s data abstraction layer provides a standard interface into data sets, regardless of the data’s origin (local, XHR, XSS, etc.) and format (JSON, XML, CSV, etc.);
  2. ImageLoader: ImageLoader allows you to defer the loading of images that aren’t in the viewport when the page paints, throttling bandwidth usage and improving performance;
  3. History: The History component gives you control of the brower’s back button within the context of a single-page web application;
  4. StyleSheet: StyleSheet makes it easy to create and modify CSS rules on the fly, allowing you to dynamically style page elements with fewer repaints.

More:
http://developer.yahoo.com/yui/3/

Sep 04

BlogEngine.NET SendMailMessage issue

Posted By Ahmed El-Kilani On 04 Sep 2009 2 Comments »
BlogEngine.NET is one of the best .NET blogs over there. I have changed to blogengine for its simplicity and themes support and customizability.
Sending mail from BlogEngine sometimes does not work. Why?
BlogEngine uses different email addresses as "Sender email" i.e "From", for example: the email of the comment poster is used as the sender notification email.
Most of the SMTP severs like godaddy only replay emails sent from only addresses hosted at the same domain as the blog is hosted, for security and spam-fighting reasons.

To fix this issue add the following to BlogSettings class under BlogEngine.Core:
/// 
/// Gets or sets the e-mail address notifications are sent from.
/// 
public string SenderEmail { get; set; }
Then we need to add the following node to settings.xml under BlogEngine.Web/App_Data
sendername@example.com
And finally a little modification in SendMailMessage method in Util class under BlogEngine.Core
/// 
/// Sends a MailMessage object using the SMTP settings.
/// 
public static void SendMailMessage(MailMessage message)
{
	if (message == null)
		throw new ArgumentNullException("message");

	try
	{
        //Override sender email which was set from contact or comment forms:
        MailAddress senderEmail = new MailAddress(BlogSettings.Instance.SenderEmail, message.From.DisplayName);
        message.From = message.ReplyTo = message.Sender = senderEmail;
		message.IsBodyHtml = true;
		message.BodyEncoding = Encoding.UTF8;
		SmtpClient smtp = new SmtpClient(BlogSettings.Instance.SmtpServer);
        // don't send credentials if a server doesn't require it,
        // linux smtp servers don't like that 
        if (!string.IsNullOrEmpty(BlogSettings.Instance.SmtpUserName)) {
		    smtp.Credentials = new System.Net.NetworkCredential(BlogSettings.Instance.SmtpUserName, BlogSettings.Instance.SmtpPassword);
        }
		smtp.Port = BlogSettings.Instance.SmtpServerPort;
		smtp.EnableSsl = BlogSettings.Instance.EnableSsl;
		smtp.Send(message);
		OnEmailSent(message);
	}
	catch (SmtpException)
	{
		OnEmailFailed(message);
	}
	finally
	{
		// Remove the pointer to the message object so the GC can close the thread.
		message.Dispose();
		message = null;
	}
}
Aug 29
One of the ways to call synchronous method asynchronously is using delegate BeginInvoke method.
The Delegate BeginInvoke method makes a call to the target method on a different thread from the caller of the delegate.
Why to use this method?
1- Easy to use.
2- It is possible to have a callback after the target method has completed its execution.

The problem:
Not supported in the .Net compact framework.

The following code works on .Net Framework while throws a NotSupportedException in .Net CF
//Call AsyncCall asynchronously
new ThreadHelper(AsyncCall).BeginInvoke(new AsyncCallback(Result), null);
            
MessageBox.Show("Should be called first");
private void AsyncCall()
{
    //Wait for 2 seconds
    Thread.Sleep(2000);
}
private void Result(IAsyncResult result)
{
    MessageBox.Show("Should be called later");
}        
        
delegate void ThreadHelper();
Solution:
This simple method does what we needed on the .Net CF
private void ThreadInvoke(ThreadHelper target, ThreadHelper callback)
{
   ThreadStart threadStart = delegate
   {
      target();
      callback();
   };
   new Thread(threadStart).Start();
            
}
Now the code should go like this:
//Call AsyncCall asynchronously
ThreadInvoke(delegate { AsyncCall(); }, delegate { Result(null); });

MessageBox.Show("Should be called first");
And you're done!
Aug 26
An interesting way to declare a variable in the same name as a reserved keyword in C# by prefixing @ before the variable name: Example:
int @int = 0;
This creates a variable name int holding the value 0.
May 20

Modal Ajax UpdateProgress Control

Posted By Ahmed El-Kilani On 20 May 2008 No Comments »

UpdateProgress control which is included with AjaxExtentions works with UpdatePanel control to keep users informed about the progress of the partial postback.
UpdateProgress is important for users to know the current process which is processed by UpdatePanel , so that users is going to wait until the process has completed, clicking a button more than one time or refreshing the page is a bad action usually taken by users in the same situations.

So, I have developed this UpdateProgress to prevent users from preforming any action until UpdatePanel progress is complete. This class is a web control that overrides the UpdateProgress template and inject a modal template which is like AjaxModalPopupExtender, disables page controls until the process is complete.

namespace AjaxedControls
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.ComponentModel;

    /// 
    /// Summary description for AjaxUpdateProgress
    ///    
    public class AjaxUpdateProgress : Control
    {
        UpdateProgress ajaxUpdateProgress;
        
        protected override void  OnLoad(EventArgs e)
        {
            ajaxUpdateProgress = new UpdateProgress();
            ajaxUpdateProgress.ID = "ajaxUpdateProgress";
            ajaxUpdateProgress.DisplayAfter = 0;
            ajaxUpdateProgress.ProgressTemplate = new CustomProgressTemplate(_loadingHTMLText);
            this.Controls.Add(ajaxUpdateProgress);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //For flexible use (only one .cs file) i added the css style script here.
            //If you are to compile this control into a separate assembly, it is better to move this script to an external .css file.
            writer.Write(@"
                ");

            base.Render(writer);
        }

        #region Properties

        string _loadingHTMLText = "Loading...";

        [Description("HTML text displayed in the loading area.")]
        [DefaultValue("Loading...")]
        public string LoadingHTMLText
        {
            set
            {
                _loadingHTMLText = value;
            }
            get
            {
                return _loadingHTMLText;
            }
        }

        Boolean _renderCss = true;

        [Description("Gets or sets whether to render css styles for the loading text, else you can add your custom styles to the page.")]
        [DefaultValue(true)]
        public Boolean RenderCss
        {
            get { return _renderCss; }
            set { _renderCss = value; }
        }

        #endregion
    }



    /// 
    /// Progress template for AjaxUpdateProgress control.
    /// 
    internal class CustomProgressTemplate : ITemplate
    {

        internal CustomProgressTemplate() { }

        internal CustomProgressTemplate(string loadingHTMLText)
        {
            _loadingHTMLText = loadingHTMLText;
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            //Override UpdateProgress progress template.
            container.Controls.Add(new LiteralControl(@"
            
            
            
{0}
".Replace("{0}", _loadingHTMLText) )); } string _loadingHTMLText; public string LoadingHTMLText { set { _loadingHTMLText = value; } } #endregion } }
Apr 29

Powerful Codesmith data layers templates

Posted By Ahmed El-Kilani On 29 Apr 2008 No Comments »

Codesmith tools is one of the powerful template-based code generation tool. For more info go to www.codesmithtools.com

Codesmith has various predefined templates for genrating domain model, N-tires, CSLA and NHibernate classes or mapping files.
In fact none of predefined templates are suitable for easy and quick use. NetTiers is the best but it needs a lot of customization and also generates a lot of code which is not necessary in most cases.
Today I come with a Generator template to generate domain model classes and data access layer and also CRUD stored procedures.

The final output of the template (generated for Northwind Category table) is figured below:

SqlDB class is the class containing Execute, ExecuteScalar, ExecuteReader, FillTable methods, which are responsible for creating database connection and execute queries and stored procedure on the database.

AbstractDataProvider is the base class for each Entity DataProvider class, it abstracts the definitions for the common base methods such as select, insert, update and delete.

AbstractEntity Class is the base class for each Entity class. IComparable interface is implemented to allow dynamic sorting for domain objects into lists; for more info about default comparer see :
http://blogs.a-h-m-e-d.com/Blogs/post/Another-dynamic-comparer-for-sorting-lists-(-very-simple-).aspx

Features:
- DeleteByFlag:

This feature allows you to specify a boolean column in a given table to be a flag for deleted rows instead of deleting them permenantly from database.
Select stored procedures select only rows of a table which has the DeleteFlagColumn set to 0 (False). Delete stored procedure just updates the colum to 1 (True) instead of the delete action.

-UseCollection:
Returned rows can be returned as generic lists if UseCollections option is set to True else a DataTable is returned.

-Generator template:
This template will generate all classes and stored procedures needed for interaction with database for given table(s).

Generator.rar (13.38 KB)

Apr 10

Drag and drop over images (Javascript)

Posted By Ahmed El-Kilani On 10 Apr 2008 No Comments »

To drag an image or drag and drop over images you need to handle the mousedown, mousemove and mouseup events, But you cannot drag an image in an html document directly, this means you cannot handle those events for the img element itself. You cannot say:


    

All we have to do is to handle those events for the document element and detect what we are draging over.
The source/target element which is sent to the handler is the element we are draging over:
//Called when the mouse moves over the document.
function documentDragOver()
{
    var el = e ? e.target : event.srcElement;
}
Here is the complete code in order to drag an image:
var ie = document.getElementById;
var dragStarted = false;
var objToDrag;

function mouseMove()
{
  if (objToDrag && dragStarted)
  {    
    objToDrag.style.left = (ie ? event.clientX : e.clientX) - diffX;
    objToDrag.style.top  = (ie ? event.clientY : e.clientY) - diffY;
    return false;
  }
}

document.onmousedown = function() 
{  
  objToDrag = ie ? event.srcElement : e.target;
  
  if (objToDrag && objToDrag.className == "ddImg")
  {
    dragStarted = true;
    diffX = (ie ?  event.clientX : e.clientX) - parseInt(objToDrag.offsetLeft);
    diffY = (ie ?  event.clientY : e.clientY) - parseInt(objToDrag.offsetTop);
    document.onmousemove = mouseMove;
    return false;
  }
}

document.onmouseup = function(){
	dragStarted = false;
}

Mar 22

Textbox label inside

Posted By Ahmed El-Kilani On 22 Mar 2008 No Comments »
Sometimes labels beside textboxes require much space and bad design, so the best solution is to type the label text inside the textbox, it is pretty easy but we need some retouch, like coloring the label text with a different color and handle onfocus and onblur events.
Here is a javascript function that does this for you:
    function labelText(id , text)
    {    
        var element = document.getElementById(id);
        var labelColor = 'gray';
        var originalColor = 'black';
        if(element.style.color)
            originalColor = element.style.color;
        
        element.style.color = labelColor;
        element.value = text;
        element.isNull = true;
               
        element.onblur = function(){
            if(this.value.replace(' ','') == '')
            {
                this.value = text;
                this.isNull = true;
                this.style.color = labelColor;
            }
        }
        element.onfocus = function(){
            if(this.isNull)
            {
                this.value = '';
                this.isNull = false;
                this.style.color = originalColor;
            }
        }
        
    }
    
And easily you can label any input field like:
    
    
    labelText('myText' , 'Search...');
    
Feb 29

Most 5 features jquery newbies should learn

Posted By Ahmed El-Kilani On 29 Feb 2008 No Comments »
Here are the most top 5 brillant features of jquery, that a jquery-newbie should know:

1- Switching between DOM elements and jQuery:
To convert your jquery object to DOM element just use the indexer like the following since jquery object contains an array of matched elements:
    $('#elementid')[0].innerHTML = "New data";
    
On the contrary you can convert the DOM element to jquery using $() function:
    $(document.getElementById('elementid')).html("New data");
    
2- Filters:
    $(':hidden').show(); // Show all hidden elements
    if($('#elementid').is(':visible'))$('#elementid').hide(); // Hides an element if it is visible
    $(':empty').remove(); // Remove all emty elements
    $("table1 tr:first").css("font-style", "italic"); //Find the first row of table1
    $("table1 tr:last").css("font-style", "italic"); //Find the last row of table1
    
3- each method:
Loops DOM elements inside a jquery object since jquery object contains an array of DOM elements:
    //Display a warning if any input field is empty
    $('input[type=text]').each(function(){
    if($(this).val() == '')alert(this.id + " is empty!");
    });
    
4- trim whitespace:
var trimmed = $.trim(" Text to be trimmed ");

5- Inserting elements inside/outside other elements:
With jquery creating elements on the fly, inserting, removing or replacing them are much easier:
append() : append an element right after the last element inside the given element:
$('#container').append("<div>A new child</div>");
prepend() : append an element right before the first element inside the given element:
$('#container').prepend("<div>A child at the first order</div>");
after() : append an element right after the given element:
$('#elementid').after("<div>A new nextsibling element</div>");
before() : append an element right before the given element:
$('#elementid').before("<div>A new previoussibling element</div>");
replaceWith() : replaces and element with another:
$('#elementid').replaceWith("<div>Element to replace</div>");