Common Add dynamic data
Common_AddDynamicData_CSharp\Callback.aspx.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.
// 


public partial class Callback : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    #region Instance Variable Declarations

    private string m_ADFCallbackFunctionString;
    private string m_CallbackResults = string.Empty;
    private string m_CheckBoxId = string.Empty;
    const string AGSLocalName = "AGSLocalMapResource";
    const string AGSInternetName = "AGSInternetMapResource";
    const string IMSName = "IMSMapResource";

    #endregion

    #region ASP.NET Page Event Handlers

    protected void Page_Load(object sender, System.EventArgs e)
    {
        // Add an onclick event for each checkbox
        foreach (System.Web.UI.WebControls.ListItem checkBox in CheckBoxList1.Items)
        {
            checkBox.Attributes.Add("onclick", "AddOrRemoveMapResource(this)");
        }

        // Define the parameters for a browser call to the WebForm_DoCallback JavaScript function
        // via the GetCallbackEventReference function.  The GetCallbackEventReference function returns 
        // the syntax for initiating a callback (i.e a call to WebForm_DoCallback) with the passed-in 
        // parameters.  Here the parameters are defined as follows:
        // this - the Page will handle the callback request
        // "message" - a JavaScript variable named "message" will contain argument-value pairs passed 
        //      to the callback server-side
        // "processCallbackResult" - name of the JavaScript function to process the callback 
        //      results from the server.  This function is the callback results handler included with 
        //      the Web ADF JavaScript Library.
        // "context" - a JavaScript variable named "context" which can be used by the client to
        //      indicate the origin of the callback
        // "postBackError" - name of the JavaScript function that will process errors returned during 
        //      callback processing.  This is the callback error handler included with the Web ADF 
        //      JavaScript Library
        // true - define whether the callback is synchronous or asynchronous.  True is asynchronous.        
        m_ADFCallbackFunctionString = Page.ClientScript.GetCallbackEventReference
            (this, "message", "processCallbackResult", "context", "postBackError", true);
    }

    #endregion

    #region ICallbackEventHandler Members

    // Parse callback request to determine which checkbox was checked\unchecked and thus which
    // resource will be added or removed.
    public void RaiseCallbackEvent(string eventArgs)
    {
        try
        {
            // Parse the callback string passed from the client to the server into separate
            // arguments using the Web ADF's callback parsing utility.
            System.Collections.Specialized.NameValueCollection nameValueCollection = null;
            nameValueCollection =
                ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackUtility.ParseStringIntoNameValueCollection(eventArgs);
            // Check whether the EventArg matches that created by the custom callback
            // and, if so, add the resource corresponding to the checkbox clicked
            if (nameValueCollection["EventArg"] == "ChangeResource")
            {
                // Get the type of datasource, whether the checkbox was checked or unchecked,
                // and the control id of the checkbox clicked from the collection of arguments
                string dataSourceType = nameValueCollection["DataSource"];
                bool isChecked = bool.Parse(nameValueCollection["IsChecked"]);
                m_CheckBoxId = nameValueCollection["CheckboxID"];
                string resourceName = string.Empty;
                switch (dataSourceType)
                {
                    // Set the resource name class variable based on the data source type
                    case "ArcGIS Server Local":
                        resourceName = AGSLocalName;
                        break;
                    case "ArcGIS Server Internet":
                        resourceName = AGSInternetName;
                        break;
                    case "ArcIMS":
                        resourceName = IMSName;
                        break;
                    default:
                        break;
                }

                // Call the method to add/remove the resource corresponding to the checkbox clicked
                m_CallbackResults = AddOrRemoveMapResource(resourceName, isChecked);
            }
        }
        catch (System.Exception exception)
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult =
                ErrorHandling.GetErrorCallback(exception);
            Map1.CallbackResults.Add(errorCallbackResult);
            m_CallbackResults = Map1.CallbackResults.ToString();
        }
    }

    // Return callback result to the browser.  
    public string GetCallbackResult()
    {
        return m_CallbackResults;
    }

    #endregion

    #region Instance Properties

    // Store the callback function string used by the browser to initiate a callback request.
    // Added to the aspx page as a server variable - populated at runtime.
    public string ADFCallbackFunctionString
    {
        get
        {
            return m_ADFCallbackFunctionString;
        }
        set
        {
            m_ADFCallbackFunctionString = value;
        }
    }

    #endregion

    #region Instance Methods

    string AddOrRemoveMapResource(string resourceName, bool isChecked)
    {
        try
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemCollection<ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem> mapResourceItemCollection =
                MapResourceManager1.ResourceItems;
            ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem mapResourceItem = null;

            // Get current resource item count to determine if the primary map resource needs to be set.
            int mapResourceCount = mapResourceItemCollection.Count;

            // If checked, add the resource.  If unchecked, remove the resource.
            if (!isChecked)
            {
                mapResourceItem = mapResourceItemCollection.Find(resourceName);
                mapResourceItemCollection.Remove(mapResourceItem);
                Map1.Refresh();
            }
            else
            {
                mapResourceItem = new ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem();

                // Map resource items consist of a definition and display settings.  The definition 
                // will define the data source and resource parameters.  Display settings will define
                // map image properties and retrieval types. 
                ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemDefinition gisResourceItemDefinition =
                    new ESRI.ArcGIS.ADF.Web.UI.WebControls.GISResourceItemDefinition();

                // Check the name of the resource corresponding to the checkbox checked and initialize
                // the resource definition accordingly
                switch (resourceName)
                {
                    case (AGSLocalName):
                        gisResourceItemDefinition.DataSourceDefinition = "localhost";
                        gisResourceItemDefinition.DataSourceType = "ArcGIS Server Local";
                        gisResourceItemDefinition.ResourceDefinition = "Layers@USA";
                        break;
                    case (AGSInternetName):
                        gisResourceItemDefinition.DataSourceDefinition = "http://serverapps.esri.com/arcgis/services/";
                        gisResourceItemDefinition.DataSourceType = "ArcGIS Server Internet";
                        gisResourceItemDefinition.ResourceDefinition = "Layers@SamplesNet/NorthAmerica";
                        break;
                    case (IMSName):
                        gisResourceItemDefinition.ResourceDefinition = "states";
                        gisResourceItemDefinition.DataSourceDefinition = "localhost@5300";
                        gisResourceItemDefinition.DataSourceType = "ArcIMS";
                        break;
                }
                               
                
                // Associate the resource item definition with a map resource item
                mapResourceItem.Definition = gisResourceItemDefinition;
                // Set the resource item's name to the passed-in resource name
                mapResourceItem.Name = resourceName;

                // Initialize display settings
                ESRI.ArcGIS.ADF.Web.DisplaySettings displaySettings = new ESRI.ArcGIS.ADF.Web.DisplaySettings();
                displaySettings.Transparency = 50.0F;
                displaySettings.ImageDescriptor.ImageFormat = ESRI.ArcGIS.ADF.Web.ImageFormat.PNG8;
                displaySettings.ImageDescriptor.TransparentBackground = true;
                displaySettings.ImageDescriptor.TransparentColor = System.Drawing.Color.White;
                displaySettings.ImageDescriptor.ReturnMimeData = false;


                // Associate the map resource with the display settings
                mapResourceItem.DisplaySettings = displaySettings;

                // Insert the new resource item at the beginning (top).
                MapResourceManager1.ResourceItems.Insert(0, mapResourceItem);
                mapResourceItem.InitializeResource();
                
                // Make sure that the resource item initialized properly.  Call the 
                // GetResourceInitFailureCallback error handling method if the resource item
                // did not initialize.
                if (mapResourceItem.FailedToInitialize)
                {
                    string exceptionMessage = mapResourceItem.InitializationFailure.Message;
                    return ErrorHandling.GetResourceInitFailureCallback(exceptionMessage, m_CheckBoxId);
                }
            }

            // Refresh the Toc and add to Map's callback result collection.
            Toc1.Refresh();
            Map1.CallbackResults.CopyFrom(Toc1.CallbackResults);
        }
        catch (System.Exception exception)
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult =
                ErrorHandling.GetErrorCallback(exception);
            Map1.CallbackResults.Add(errorCallbackResult);
        }

        // return the Map's collection of callback results as a string
        return Map1.CallbackResults.ToString();
    }


    #endregion
}