Category Archive: C#

Subcategories: No categories

How To: Communication between UserControls

Problem : Allow one UserControl(DepartmentSelectorControl) to communicate /pass a value to another UserControl which will in turn

 


using System;
using System.Linq;
using System.Web.UI.WebControls;

public partial class Controls_DepartmentSelectorControl : System.Web.UI.UserControl
{

	private string selecteddepartment = string.Empty;
	public string SelectedDepartment
	{
		get { return selecteddepartment; }
		set
		{
			selecteddepartment = value;
			selecteddepartment = uxDepartments.SelectedItem.Text;
		}
	}

	//Create eventhandler to be consumed by the host page
	public event EventHandler SelectDepartment;

	protected void Page_Load(object sender, EventArgs e)
	{
		using (var context = new AdventureWorksEntities())
		{

			var departments = context.Departments.Select(p => new Department
			{
				DepartmentID = p.DepartmentID,
				GroupName = p.GroupName,
				Name = p.Name,
				ModifiedDate = p.ModifiedDate
			});
			foreach (var department in departments)
			{
				var dItem = new ListItem { Text = department.Name, Value = department.DepartmentID.ToString() };
				uxDepartments.Items.Add(dItem);
			}

		}

	}

	protected void uxDepartments_SelectedIndexChanged(object sender, EventArgs e)
	{
		//Set the member variable to what the user has selected
		selecteddepartment = uxDepartments.SelectedItem.Text;
		if(SelectDepartment != null)
		{
			//Event is raised and corresponding eventhandler is called to respond to the event
			SelectDepartment(this, new EventArgs());
		}

	}
}

Retrieving Editable Regions in Kentico

Problem : Retrieve contents of editable regions in Kentico

Kentico CMS allows you to use a custom control called CMSEditableRegion. There are times when you might need to check the contents of this region and perform some checks to implement business rules.

Solution : Check for the EditableRegion property on the Current document

Each document has a property called EditableRegions which is basically a key value pair. If an editable region is on the page then the name (in lower case) is stored as a key in Editable Regions.

if (CMSContext.CurrentDocument.DocumentContent.EditableRegions.ContainsKey("uxpagetitle"))
{
         content = CMSContext.CurrentDocument.DocumentContent.EditableRegions["uxpagetitle"].ToString();
}

How to generate an iCalendar file

Problem : Generate a iCalendar file which will trigger a calendar application (eg. outlook) to open with an updated event.

The iCalendar file is a fairly common feature which most developers add to enable  users to add events to their personalized calendars via a custom calendar application

save image

Solution : Create a web handler which will create a plain text file with the ‘ics’ extension.

using System;
using System.Web;
namespace MyNamespace
{
 public class iCalendar: IHttpHandler
 {

  public bool IsReusable
  {
   get
   {
    return true;
   }
  }

  string DateFormat
  {
    get
    {
      return "yyyyMMddTHHmmssZ"; // 20060215T092000Z
    }
  }

  public void ProcessRequest(HttpContext context)
  {
   DateTime startDate = DateTime.Now.AddDays(5);
   DateTime endDate = startDate.AddMinutes(35);
   string organizer = "foo@bar.com";
   string location = "My House";
   string summary = "My Event";
   string description = "Please come to\\nMy House";

   context.Response.ContentType="text/calendar";
   context.Response.AddHeader("Content-disposition", "attachment; filename=appointment.ics");

   context.Response.Write("BEGIN:VCALENDAR");
   context.Response.Write("\nVERSION:2.0");
   context.Response.Write("\nMETHOD:PUBLISH");
   context.Response.Write("\nBEGIN:VEVENT");
   context.Response.Write("\nORGANIZER:MAILTO:" + organizer);
   context.Response.Write("\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("\nLOCATION:" + location);
   context.Response.Write("\nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com");
   context.Response.Write("\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat));
   context.Response.Write("\nSUMMARY:" + summary);
   context.Response.Write("\nDESCRIPTION:" + description);
   context.Response.Write("\nPRIORITY:5");
   context.Response.Write("\nCLASS:PUBLIC");
   context.Response.Write("\nEND:VEVENT");
   context.Response.Write("\nEND:VCALENDAR");
   context.Response.End();
  }
 }
}

Eliminating if-else statements using a rule engine

Most of you, like me have run into the dreaded long chain of if-else statements while developing. These chain of conditional statements often make code very difficult to read and debug. While working on a recent project I discovered a new way to clean things up. I’ll first take you through the old approach

private static void Getgrade()
        {
            //Classic grade program

            double finalGrade = 86.4;

            if (finalGrade >= 95)
            {
                Console.WriteLine("Dan has obtained an A+, which is Outstanding");
            }
            else if (finalGrade >= 90 && finalGrade < 95)
            {
                Console.WriteLine("Dan has obtained an A-, which is Excellent");
            }
            else if (finalGrade >= 85 && finalGrade < 90)
            {
                Console.WriteLine("Dan has obtained a A, which is very good");
            }
            else if (finalGrade >= 70 && finalGrade < 85)
            {
                Console.WriteLine("Dan has obtained a B+, which is good");
            }
            else if (finalGrade >= 60 && finalGrade < 70)
            {
                Console.WriteLine("Dan has obtained a B, which is a pass");
            }
            else
            {
                Console.WriteLine("Dan has obtained an F, which is poor");
            }
        }

Now lets take a look at how we can improve this with our rule engine. I’ll define two classes to begin with.

public class Rule<T>
    {
        public Func<T, bool> Test { get; set; }
        public string DisplayMessage { get; set; }
    }

public class Student
    {
        public string Name { get; set; }
        public double Grade { get; set; }
    }

The first class provides us with our template to  generate rules for our engine. It comprises of two properties which make use of the Func delegate.

private static void GetGradeFromRuleEngine(Student freshman)
        {

            var rules = new List<Rule<Student>>
                            {
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 95,
                                    DisplayMessage =string.Format("{0} has obtained an A+, Which is Outstanding", freshman.Name)
                                },
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 90 && e.Grade < 95,
                                    DisplayMessage =
                                        string.Format("{0} has obtained an A-, which is Excellent", freshman.Name)
                                },
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 85 && e.Grade < 90,
                                    DisplayMessage =
                                        string.Format("{0} has obtained a A, which is very good", freshman.Name)
                                },
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 70 && e.Grade < 85,
                                    DisplayMessage =
                                        string.Format("{0} has obtained a B+, which is good", freshman.Name)
                                },
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 60 && e.Grade < 70,
                                    DisplayMessage =
                                        string.Format("{0} has obtained a B, which is a pass", freshman.Name)
                                },
                                new Rule<Student>
                                {
                                    Test = e => e.Grade >= 60 && e.Grade < 70,
                                    DisplayMessage =
                                        string.Format("{0} has obtained an F, which is poor", freshman.Name)
                                },

                            };

            bool isValid = rules.Any(r => r.Test(freshman));
            if (isValid)
            {
                var validRules = rules.Where(r => r.Test(freshman));

                string message = validRules.SingleOrDefault().DisplayMessage;

                Console.WriteLine(message);
            }

        }

We then create a method which accepts a student object called GetGradeFromRuleEngine. The next thing we do is to then build our rule engine. This structure makes it very easy to modify and even add new rules to our engine. Below is how you will run this and voila.

class Program
    {
        static void Main(string[] args)
        {
            var dan = new Student()
            {
                Name = "Dan",
                Grade = 86.4
            };

            GetGradeFromRuleEngine(dan);
        }

}