20 December, 2011

Localization in Chart (Microsoft Chart Control), Localizing DataPoint

I had a scenario where need to localize the data points that are displayed on the chart, that the decimal needs to be localized as comma (,) in Russian and Spanish., Thanks to my friend Gagan for this
E.g.:

We can assign an EventHandler to FormatNumber Property as Below

private MemoryStream RenderGraph()
{
Chart barchart = new Chart();
//many number codes are removed
//Removed other formatting lines
barchart.FormatNumber += new EventHandler<FormatNumberEventArgs>(ConvertChartDecimalFormat);
            barchart.DataSource = dt;   
barchart.Series[0].XValueMember = "XProp";
            barchart.Series[0].YValueMembers = "YProp";
            barchart.DataBind();

//return the memory stream image
}

Followed the event method will look as below. 
void ConvertChartDecimalFormat(object sender, FormatNumberEventArgs e)
{
if (sender.GetType() == typeof(DataPoint))
       {
                try
                {
                    e.LocalizedValue = Double.Parse(e.LocalizedValue).ToString(currentCulture);
                }
                catch (Exception)
                {
                    //do if anything required.
                }
        }

}




Enjoy.!!! :-)

17 December, 2011

knockoutjs with Umbraco and Umbraco base call

I was thinking how we could use knockoutjs with Umbraco, so just thought blog it.

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
  • Features
  • Elegant dependency tracking
  • Declarative bindings
  • Flexible and sophisticated templating
  • Trivially extensible

More information reference: http://knockoutjs.com.

Well, we start with Umbraco, To know more on umbraco, Please refer below links
http://our.umbraco.org/wiki/how-tos/a-complete-newbie's-guide-to-umbraco
http://umbraco.com/help-and-support/video-tutorials/getting-started?freeVideos=1
http://our.umbraco.org/wiki/how-tos/getting-started-with-umbraco-what-is-next-after-you-install
http://our.umbraco.org/wiki/install-and-setup

I have created a document with document type "Announcement" with below two properties
  • announcementTitle 
  • description
My Html block is as shown below
<p>
        <h1 data-bind="text: Title">
        </h1>
    </p>
    <p>
        <span data-bind="html: Description"></span>
    </p>
    <form id="frmAnnoumcent">
    <p>
        Title:
        <input data-bind="value: Title" name="Title" style="width: 400px" /></p>
    <p>
        Annoucement:
        <textarea data-bind="value: Description" name="Description" rows="5" cols="60"> </textarea></p>
    <button data-bind="click: save">
        Save Listings</button>
    </form>

Script Block

    <script type="text/javascript">

    var announcement = {
        "Title": ko.observable("") ,
        "Description": ko.observable(""),
    };
  
   var viewModel=ko.mapping.fromJS(announcement);
     $.ajax({
        url: '/base/baseCall/GetAnnouncement.aspx',
        type: "POST",
        data: $('#frmTest').serialize(),
        dataType: 'JSON',
        success: function(result)
        {
            ko.mapping.fromJS(result,{},viewModel);
          
        },
        error:
        function(result)
        {
        alert(result.message);
        }
       
    });
  
    viewModel.save = function() {
    $.ajax({
        url: '/base/baseCall/SaveAnnouncement.aspx',
        type: "POST",
        data: $('#frmTest').serialize(),
        dataType: 'JSON',
        success: function(result)
        {

            ko.mapping.fromJS(result,{},viewModel);
             ko.applyBindings(viewModel);
          
        },
        error:
        function(result)
        {
        alert(result.message);
        }
       
    });
},
$(function() {
    ko.applyBindings(viewModel);
});
     </script>

Base Service Call

       [RestExtension("baseCall")]
    public class TestService
    {
        [RestExtensionMethod(returnXml = false)]
        public static string SaveAnnouncement()
        {
            DocumentType dt = DocumentType.GetByAlias("Announcement");
            User author = User.GetUser(0);

            string title = HttpContext.Current.Request["Title"];
            string Description = HttpContext.Current.Request["Description"];

            Document doc = Document.MakeNew(title, dt, author, 1048);
            doc.getProperty("announcementTitle").Value = title;
            doc.getProperty("description").Value = Description;
            //after creating the document, prepare it for publishing

            doc.Publish(author);

            //Tell umbraco to publish the document
            umbraco.library.UpdateDocumentCache(doc.Id);

            return GetAnnouncement();
        }
        [RestExtensionMethod(returnXml=false)]
        public static string GetAnnouncement()
        {

            List<Announcement> announcement = new List<Announcement>();
            Document root = new Document(1048);
            string sJSON="";
            if (root.HasChildren)
            {
                foreach (Document tempDocument in root.Children.OrderByDescending(res => res.CreateDateTime))
                {
                    Announcement a = new Announcement();
                    Property prop1 = tempDocument.getProperty("announcementTitle");

                    a.Title = (string)prop1.Value;
                    prop1 = tempDocument.getProperty("description");
                    a.Description = (string)prop1.Value;
                    announcement.Add(a);
                    System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
        new System.Web.Script.Serialization.JavaScriptSerializer();
                    sJSON = oSerializer.Serialize(a);

                    sJSON=sJSON.Insert(sJSON.Length - 2, ",");
                    break;
                }
            }
          
            return sJSON;
        }



    }
    public class Announcement
    {
        public string Title { get; set; }
        public string Description { get; set; }
    }

Of-course the knockoutjs can be used well, and it gives an live UI. We could create an amazing user experience with it.

Error: ko.mapping.updateFromJS, use ko.mapping.fromJS instead

I had the same issue, (Error: ko.mapping.updateFromJS, use ko.mapping.fromJS instead) I bugged for long time, then i tried the another alternative.fromJS

 the functionality is the same, but be aware that updateFromJS's parameter list is just the other away around, so instead of doing:
   ko.mapping.updateFromJS(viewModel, jsData);

You need to replace this with:
   ko.mapping.fromJS(jsData, {}, viewModel);

16 December, 2011

Localization in Umbraco, Item Page field localization




Umbraco is one of the most deployed Web Content Management Systems on the Microsoft stack. It's in the top five most popular server applications and among the ten most popular open source tools in general.

You can directly download and start using it from http://www.umbraco.com

If you have not used the application yet, its always worth trying it once. I am sure you will love it.

Well, for the first time users, Umbraco provide step by step instruction for initial set up, once you are done you can use some sample template or create a blank website.


To know more on umbraco, Please refer below links
http://our.umbraco.org/wiki/how-tos/a-complete-newbie's-guide-to-umbraco
http://umbraco.com/help-and-support/video-tutorials/getting-started?freeVideos=1
http://our.umbraco.org/wiki/how-tos/getting-started-with-umbraco-what-is-next-after-you-install
http://our.umbraco.org/wiki/install-and-setup


I have created a blank website, Now we will go step by step.

  • First create the home page template.

  • I created the document type with same name, and some properties, like, Page title, and page content, with two tabs, one for English and one for Malayalam
  • Now you are Good to go for localization, but with few changes in your properties, You can insert the page field of your property using umbraco page field utility.
                      <umbraco:Item field="pageTitle" runat="server" />

  • To apply the localization on fields, we have to customize our on item field as below, 
    • Write a class Item by implementing umbraco.presentation.templateControls.Item
  public class Item : umbraco.presentation.templateControls.Item
    {
        [Bindable(true)]
        [Category("Umbraco")]
        [DefaultValue("")]
        [Localizable(true)]
        public new string Field
        {
            get
            {
                return base.Field;
            }
            set
            {
                umbraco.cms.businesslogic.web.Document objCurrentDocument = new umbraco.cms.businesslogic.web.Document(umbraco.NodeFactory.Node.GetCurrent().Id);
                string locale = Utils.GetLanguageCode(HttpContext.Current.Request["locale"]);
                if (locale == "ENG")
                {
                    locale = "";
                }
                else
                {
                    locale = "_" + locale;
                }
                string sNewField = string.Format("{0}{1}", value, locale);
                if (objCurrentDocument.getProperty(sNewField) != null && objCurrentDocument.getProperty(sNewField).Value != null && !string.IsNullOrEmpty(objCurrentDocument.getProperty(sNewField).Value.ToString()))
                {
                    value = sNewField;
                }
                base.Field = value;
            }
        }
    }
  • Register this class on the template as below 
    <%@ Register Assembly="site" Namespace="site.UmbracoUsercontrols"
    TagPrefix="Cumbraco" %>
  •  Well, Now you can directly use the utility  as below.
<title><Cumbraco:Item field="pageTitle" runat="server" /></title>
  •  Now we can create  home page as below content 
 
The localized page can be seen as below
Umbraco one of the fastest growing platforms for building websites. I suggest to just use it, I am sure you will love it.

30 November, 2011

Observer Pattern With C# 4.0

Observer Pattern
"The Observer Pattern Defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically."
Publishers + Subscribers = Observer Pattern

C# Introduced , IObserver<T> and IObservable<T> which will help push-based notification,also known as the observer design pattern. The IObservable<T> interface represents the class that sends notifications (the provider); the IObserver<T> interface represents the class that receives them (the observer). T represents the class that provides the notification information.

An IObserver<T> implementation arranges to receive notifications from a provider (an IObservable<T> implementation) by passing an instance of itself to the provider's IObservable<T>.Subscribe method. This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

The IObserver<T> interface defines the following three methods that the observer must implement:
The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

The OnError method, which is typically called by the provider to indicate that data is unavailable, inaccessible, or corrupted, or that the provider has experienced some other error condition.
The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.




WeatherData.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherData  
   {  
     private float temperature;  
     private float humidity;  
     private float presssure;  
     public WeatherData(float temp,float hum, float press)  
     {  
       temperature = temp;  
       humidity = hum;  
       presssure = press;  
     }  
     public float Temperature  
     {  
       get { return this.temperature; }  
     }  
     public float Humidity  
     {  
       get { return this.humidity; }  
     }  
     public float Presssure  
     {  
       get { return this.presssure; }  
     }  
   }  
 }  
WeatherProvider.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherProvider: IObserver<WeatherData>  
   {  
     private IDisposable unsubscriber;  
     private string instName;  
     public WeatherProvider(string name)  
     {  
       this.instName = name;  
     }  
     public string Name  
     {  
       get { return this.instName; }  
     }  
     public virtual void Subscribe(IObservable<WeatherData> provider)  
     {  
       if (provider != null)  
         unsubscriber = provider.Subscribe(this);  
     }  
     void IObserver<WeatherData>.OnCompleted()  
     {  
       Console.WriteLine("The Provider has completed transmitting data to {0}.", this.Name);  
       this.Unsubscribe();  
     }  
     public virtual void Unsubscribe()  
     {  
       unsubscriber.Dispose();  
     }  
     void IObserver<WeatherData>.OnError(Exception error)  
     {  
       Console.WriteLine("{0}: The provider cannot be read data.", this.Name);  
     }  
     void IObserver<WeatherData>.OnNext(WeatherData value)  
     {  
       Console.WriteLine("{3}: The current Weather is Temperature: {0}, Pressure {1}, Humidty {2}", value.Temperature, value.Presssure, value.Humidity,this.Name);  
     }  
   }  
 }  
WeatherSubscriber.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherSubscriber : IObservable<WeatherData>  
   {  
     private List<IObserver<WeatherData>> observers;  
     public WeatherSubscriber()  
     {  
       observers = new List<IObserver<WeatherData>>();  
     }  
     public IDisposable Subscribe(IObserver<WeatherData> observer)  
     {  
       if (!observers.Contains(observer))  
         observers.Add(observer);  
       return new Unsubscriber(observers, observer);  
     }  
     private class Unsubscriber : IDisposable  
     {  
       private List<IObserver<WeatherData>> _observers;  
       private IObserver<WeatherData> _observer;  
       public Unsubscriber(List<IObserver<WeatherData>> observers, IObserver<WeatherData> observer)  
       {  
         this._observers = observers;  
         this._observer = observer;  
       }  
       public void Dispose()  
       {  
         if (_observer != null && _observers.Contains(_observer))  
           _observers.Remove(_observer);  
       }  
     }  
     public void SetMeasurements(WeatherData weather)  
     {  
       foreach (var observer in observers)  
       {  
         if (weather == null)  
           observer.OnError(new WeatherUnKnnowException());  
         else  
           observer.OnNext(weather);  
       }  
     }  
   }  
 }  
WeatherUnKnnowException.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class WeatherUnKnnowException: Exception  
   {  
     internal WeatherUnKnnowException()  
     { }  
   }  
 }  
Program.cs
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ObserverPatternInCsharp  
 {  
   public class Program  
   {  
     public static void Main()  
     {  
       WeatherSubscriber subscriber = new WeatherSubscriber();  
       WeatherProvider NDTVProvider = new WeatherProvider("NDTV");  
       NDTVProvider.Subscribe(subscriber);  
       WeatherProvider TimesProvider = new WeatherProvider("Times");  
       TimesProvider.Subscribe(subscriber);  
       WeatherProvider HeadLineProvider = new WeatherProvider("HeadLine");  
       HeadLineProvider.Subscribe(subscriber);  
       subscriber.SetMeasurements(new WeatherData(10, 7, 14));  
       HeadLineProvider.Unsubscribe();  
       subscriber.SetMeasurements(new WeatherData(28,26, 14));  
       subscriber.SetMeasurements(null);  
       Console.Read();  
     }  
   }  
 }  

27 November, 2011

CRM to SendEmail

Send email functionality with CRM
     internal static Boolean SendEmail(string toAddress, Guid? fromPartyGuid, string subjectLine, string body, Guid? contactId,string templateName)  
     {  
       CrmService crmService = GetCrmService();  
       //[[FROM activity party for the email.  
       activityparty fromParty = new activityparty();  
       fromParty.partyid = new Lookup();  
       fromParty.partyid.type = EntityName.queue.ToString();  
       fromParty.partyid.Value = fromPartyGuid;   
       //]]       
       //[[TO activity party for email  
       activityparty toParty = new activityparty();  
       toParty.partyid = new Lookup();  
       toParty.partyid.type = EntityName.contact.ToString();  
       toParty.partyid.Value = (contactId.HasValue) ? contactId.Value : new Guid("");  
       //]]  
       //[[Create a new email and set its properties  
       email emailInstance = new email();  
       //set email parameters  
       emailInstance.from = new activityparty[] { fromParty };  
       emailInstance.to = new activityparty[] { toParty };  
       emailInstance.subject = subjectLine;  
       emailInstance.description = body;  
       emailInstance.regardingobjectid = CreateLookup(contactId.ToString(), EntityName.contact);  
       emailInstance.trackingtoken = templateName;  
       //]]  
       //Create a GUID for the email  
       Guid emailId = crmService.Create(emailInstance);  
       //Create a SendEmailRequest  
       SendEmailRequest request = new SendEmailRequest();  
       request.EmailId = emailId;  
       request.IssueSend = true;  
       request.TrackingToken = "";  
       //Execute request  
       SendEmailResponse sendEmailresp = (SendEmailResponse)crmService.Execute(request);  
       return true;  
     }  
           public static Lookup CreateLookup(string guid, EntityName lookupType)  
     {  
       if (string.IsNullOrEmpty(guid)) return null;  
       Lookup lkup = new Lookup();  
       lkup.Value = new Guid(guid);  
       lkup.type = lookupType.ToString();  
       return lkup;  
     }  

Create Document Dynamically (Umbraco)

You can create document and publish the content during run time, Below code snippets helps you to do it.
   public class UmbracoUtils  
   {  
  /// <summary>  
     /// Create and publish the document programatically  
     /// </summary>  
     /// <param name="nodeName"></param>  
     /// <param name="properties"></param>  
     /// <param name="documentType"></param>  
     /// <param name="parentId"></param>  
     /// <returns>node id</returns>  
     public static int CreateDocument(string nodeName, Dictionary<string, string> properties, int documentType, int parentId, List<string> roles = null)  
     {  
       DocumentType dt = new DocumentType(documentType);  
       umbraco.BusinessLogic.User u = new umbraco.BusinessLogic.User(0);  
       // Create the document  
       Document d = Document.MakeNew(nodeName, dt, u, parentId);  
       // Add values to the generic properties of the document   
       if (properties != null)  
       {  
         foreach (string property in properties.Keys)  
         {  
           d.getProperty(properties[property]).Value = properties[property];  
         }  
       }  
       // Set the publish status of the document and there by create a new version   
       if (roles != null)  
       {  
         int loginDocId = Constants.NODE_ID_HOME;  
         int errorDocId = Constants.NODE_ID_HOME;  
         umbraco.cms.businesslogic.web.Access.ProtectPage(false, d.Id, loginDocId, errorDocId);  
         foreach (string role in roles)  
         {  
           umbraco.cms.businesslogic.web.Access.AddMembershipRoleToDocument(d.Id, role);  
         }  
       }  
       d.Publish(u);  
       // Tell the runtime environment to publish this document   
       umbraco.library.UpdateDocumentCache(d.Id);  
       return d.Id;  
     }  
     }  
You could achieve this by calling directly as below,
  List<string> roles = new List<string>();  
       roles.Add(Constants.ROLE_COLLEGE);  
       roles.Add(Constants.ROLE_STUDENT);  
       UmbracoUtils.CreateDocument("MBA College", null, Constants.TEMPLATE_ID_CONTENTPAGE, Constants.NODE_ID_HOME, roles);  

Logger with UmbracoLog

Umbraco logger is powerful tool and It can be extended to use in your Umbraco application to log anything that you want to do, instead of using another logger to do the task.
     /// <summary>  
     /// Logger to log Error/Debug/Warning to Umbraco log table  
     /// </summary>  
     public class Logger  
     {  
       public enum LogLevels  
       {  
         DEBUG = 1,  
         WARNING = 2,  
         ERROR = 3,  
         NONE = 100  
       }  
       public static LogLevels CurrentLevel  
       {  
         get;  
         set;  
       }  
       private static string StrLoggedInUserId;  
       public static void SetStrLoggedInUserId()  
       {  
         if (StrLoggedInUserId == null || StrLoggedInUserId == "NA")  
         {  
           if (HttpContext.Current != null)  
           {  
             HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];  
             if (cookie != null)  
             {  
               FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);  
               StrLoggedInUserId = ticket.Name;  
               return;  
             }  
           }  
           if (string.IsNullOrEmpty(StrLoggedInUserId))  
           {  
             StrLoggedInUserId = "NA";  
           }  
         }  
       }  
       private static string StrSessionId  
       {  
         get  
         {  
           return HttpContext.Current.Session != null ? HttpContext.Current.Session.SessionID : "NA";  
         }  
       }   
       public static void Debug(string message)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.DEBUG)  
         {  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, -1, StrLoggedInUserId + " : " + StrSessionId + " : " + message);  
         }  
       }  
       public static void Error(string message)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.ERROR)  
         {  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, -1, StrLoggedInUserId + " : " + StrSessionId + " : " + message);  
         }  
       }  
       public static void Exception(Exception e)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.ERROR)  
         {  
           string logstring = e.Message;  
           logstring += Environment.NewLine;  
           logstring += e.StackTrace != null ? e.StackTrace : "";  
           logstring += Environment.NewLine;  
           logstring += e.InnerException != null ? e.InnerException.Message : "";  
           logstring += Environment.NewLine;  
           logstring += e.InnerException != null && e.InnerException.StackTrace != null ? e.InnerException.StackTrace : "";  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Custom, -1, StrLoggedInUserId + " : " + StrSessionId + " : " + logstring);  
         }  
       }  
       public static void Login(string message)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.DEBUG)  
         {  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Login, -1, StrLoggedInUserId + "~" + StrSessionId + "~" + message);  
         }  
       }  
       public static void ErrorLogin(string message)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.ERROR)  
         {  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.LoginFailure, -1, StrLoggedInUserId + "~" + StrSessionId + "~" + message);  
         }  
       }  
       public static void Logout(string message)  
       {  
         SetStrLoggedInUserId();  
         if ((int)CurrentLevel <= (int)LogLevels.DEBUG)  
         {  
           umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Logout, -1, StrLoggedInUserId + "~" + StrSessionId + "~" + message);  
         }  
       }  
     }