Common Simple UserControlTask
Common_SimpleUserControlTask_CSharp\UserControlConfigurators\SimpleTaskWebConfig\SimpleTaskWebConfigurator.ascx.cs
// Copyright 2010 ESRI
// 
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
// 
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
// 
// See the use restrictions.
// 

using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
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 ESRI.ArcGIS.ADF.Web.UI.WebControls;
using ESRI.ArcGIS.ADF.Web;
using System.Drawing;

public partial class SimpleTaskWebConfigurator : System.Web.UI.UserControl, IWebConfigurator, IWebConfiguratorValidation, IDefaultWebConfiguration
{
    private string defaultText = string.Empty;
    private Color backColor;

    public void Page_Load(object sender, EventArgs args)
    {
        #region Populate UI from task's configuration settings
        if (ScriptManager.GetCurrent(Page) != null && !ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
        {
            if (ControlToConfigure != null && !string.IsNullOrEmpty((ControlToConfigure as UserControlTask).Configuration))
                FromJsonstring((ControlToConfigure as UserControlTask).Configuration);

            txtLabelText.Text = defaultText;
            colorPicker.ChosenColor = backColor;
        }
        #endregion
    }

    #region Design Tag Creation
    private string getMarkup(ControlCollection additionalControls)//, string defaultConfigurationValue, Color backColor)
    {
        #region Find task result control to buddy with
        ArrayList taskResultControls = new ArrayList();
        if (additionalControls != null && additionalControls.Count > 0)
            FindControls(typeof(TaskResults), additionalControls, ref taskResultControls);
        else
            FindControls(typeof(TaskResults), Page.Controls, ref taskResultControls);

        string taskResultsID = string.Empty;
        if (taskResultControls != null && taskResultControls.Count > 0)
        {
            taskResultsID = (taskResultControls[0] as TaskResults).ID;
        }
        #endregion

        #region Create tag for task results property
        StringBuilder taskResultsTag = new StringBuilder();
        if (!string.IsNullOrEmpty(taskResultsID))
        {
            taskResultsTag.Append("<TaskResultsContainers>");
            taskResultsTag.AppendFormat("<esri:BuddyControl Name=\"{0}\" />", taskResultsID);
            taskResultsTag.Append("</TaskResultsContainers>");
        }
        #endregion

        #region Create markup for the user control task

        string color = (backColor == null || backColor == Color.Transparent || backColor == Color.Empty) ? "White" : ColorTranslator.ToHtml(backColor);
        string str = string.Format("<esriTasks:UserControlTask runat=\"server\" Width=\"200px\" Transparency=\"35\" BackColor=\"{0}\" " +
            "TitleBarColor=\"WhiteSmoke\" TitleBarSeparatorLine=\"False\" TitleBarHeight=\"20px\" Visible=\"False\" " +
            "BorderColor=\"LightSteelBlue\" BorderStyle=\"Outset\" BorderWidth=\"1px\" Font-Names=\"Verdana\" " +
            "Font-Size=\"8pt\" ForeColor=\"Black\" TaskControl=\"~/App_Data/UserControlTasks/SimpleTask/SimpleTask.ascx\" Configuration=\"{1}\">",
            color, _controlToConfigure.Configuration) + taskResultsTag.ToString() + "</esriTasks:UserControlTask>";
        return str;
        #endregion
    }
    #endregion

    #region Event Handlers - On OK and Cancel
    protected void ok_Clicked(object sender, EventArgs args)
    {
        //Fire WebConfigurationCompleted event
        if (WebConfigurationCompleted != null)
        {
            // parse the json string and set the default values
            _controlToConfigure.Configuration = ToJsonString();
            FromJsonstring(_controlToConfigure.Configuration);
            WebConfigurationCompleted(sender, new WebConfigurationCompleteEventArgs(_controlToConfigure, getMarkup(AdditionalControls)));
        }
    }

    protected void cancel_Clicked(object sender, EventArgs args)
    {
        //Fire WebConfigurationCanceled event
        if (WebConfigurationCanceled != null)
            WebConfigurationCanceled(sender, EventArgs.Empty);
    }

    public string ToJsonString()
    {
        ESRI.ArcGIS.ADF.Web.Display.JsonSerializer json = new ESRI.ArcGIS.ADF.Web.Display.JsonSerializer(true);
        json.StartObject();
        json.WriteProperty("textboxvalue", txtLabelText.Text);
        json.AddSeparator();
        json.WriteProperty("color", colorPicker.ChosenColor);
        json.EndObject();
        ESRI.ArcGIS.ADF.XmlHelper xmlhelper = new ESRI.ArcGIS.ADF.XmlHelper();
        return xmlhelper.Encode(json.ToString());
    }

    //Read of the configuration by parsing JSON string
    public void FromJsonstring(string json)
    {
        if (string.IsNullOrEmpty(json))
            return;

        ESRI.ArcGIS.ADF.XmlHelper xmlhelper = new ESRI.ArcGIS.ADF.XmlHelper();
        string decoded = xmlhelper.Decode(json);

        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        System.Collections.Generic.IDictionary<string, object> deserilizedjson = jss.DeserializeObject(decoded) as System.Collections.Generic.IDictionary<string, object>;
        //set the textbox value by reading the json string from configuration
        if (deserilizedjson.ContainsKey("textboxvalue"))
            defaultText = deserilizedjson["textboxvalue"] as string;
        if (deserilizedjson.ContainsKey("color"))
            backColor = System.Drawing.ColorTranslator.FromHtml(deserilizedjson["color"] as string);
        return;
    }
    #endregion

    #region IWebConfigurator - Properties
    ControlCollection _additionalControls;
    public ControlCollection AdditionalControls
    {
        get
        {
            return _additionalControls;
        }
        set
        {
            _additionalControls = value;
        }
    }

    UserControlTask _controlToConfigure;
    public Control ControlToConfigure
    {
        get
        {
            return _controlToConfigure;
        }
        set
        {
            if (!(value is UserControlTask))
            {
                throw new ArgumentException();
            }
            _controlToConfigure = value as UserControlTask;
        }
    }
    #endregion

    #region IWebConfigurator Methods/Events

    public bool ValidateResources(out string message)
    {
        // This task is not dependent on any resources
        message = null;
        return true;
    }

    public event WebConfigurationCanceledEventHandler WebConfigurationCanceled;

    public event WebConfigurationCompleteEventHandler WebConfigurationCompleted;

    #endregion

    #region IConfiguratorValidation Members - an opportunity to validate configuration

    public bool IsConfigurationValid(out string message)
    {
        message = string.Empty;
        return true;
    }

    #endregion

    #region IDefaultWebConfiguration Members - to allow users to add task without configuring it

    public string GetDefaultTag(ControlCollection AdditionalControls)
    {
        return getMarkup(AdditionalControls);//, string.Empty, Color.White);
    }
    #endregion

    #region Helper functions
    private static void FindControls(Type type, ControlCollection controls, ref ArrayList foundControls)
    {
        if (controls == null) return;
        Control control;
        if (foundControls == null) foundControls = new ArrayList();
        for (int i = 0; i < controls.Count; ++i)
        {
            control = controls[i];
            if (type.IsInstanceOfType(control))
            {
                foundControls.Add(control);
            }
            if (control.Controls.Count > 0) FindControls(type, control.Controls, ref foundControls);
        }
    }
    #endregion
}