Common Add dynamic data
Common_AddDynamicData_CSharp\PartialPostback_RegisterDataItem.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 PartialPostback_RegisterDataItem : System.Web.UI.Page
{
    #region Instance Variable Declarations

    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_PreRender(object sender, System.EventArgs e)
    {
        string scriptKeyCustom = "customDataItemScript";
        // Check whether a script block with the name stored in scriptKeyCustom has already
        // been registered on the client, and whether the page is in an asynchronous postback.
        // If neither of these is true, create and register the script block.  Note that replacing
        // ScriptManager1.IsInAsyncPostBack with Page.IsPostback will work initially, but if a
        // full page postback occurs, the script may be lost.
        if (!this.Page.ClientScript.IsClientScriptBlockRegistered(GetType(), scriptKeyCustom) && 
        !ScriptManager1.IsInAsyncPostBack)
        {
            // Construct the JavaScript block that will be responsible for processing data items.
            // 
            // onLoadFunction specifies AsyncResponseHandler as a handler for the pageLoading AJAX
            // client-side event.  This event fires during asynchronous postbacks after the response 
            // has been received from the server, but before any content on the page is updated.  
            // 
            // AsyncResponseHandler retrieves the data items registered server-side during the 
            // asynchronous postback by accessing the dataItems property on the second argument 
            // passed to the handler.  It then gets the particular data item corresponding to the 
            // page by passing the page's client ID to the dataItems array as an array index.  This 
            // data item, assumed to be formatted as a Web ADF callback result, is then passed to 
            // ESRI.ADF.System.processCallbackResult - the client-side Web ADF function responsible 
            // for parsing callback results and updating Web ADF controls accordingly.
            //
            // Below the function declarations, onLoadFunction is added as a handler for the AJAX 
            // client-side event init, which is raised once when the page is first rendered. This 
            // is therefore the appropriate place for onLoadFunction to be called, since the 
            // asynchronous pageLoading handler in this case can remain unchanged for the life
            // of the application.
            //
            // The functions are enclosed in an extra pair of curly braces to allow the subsequent
            // call to String.Format.  String.Format is designed to replace the contents of curly
            // braces with the parameters passed to the function call.  These extra braces "escape" 
            // the braces that must enclose a JavaScript function's logic, essentially telling 
            // String.Format to not replace the contents of these particular braces.
            string scriptBlock = @"
                
                function onLoadFunction(){{
                  Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(AsyncResponseHandler);
                }}

                function AsyncResponseHandler(sender, args) {{
                  var dataItems = args.get_dataItems();
                  if (dataItems['{0}'] != null)
                    ESRI.ADF.System.processCallbackResult(dataItems['{0}']);
                }}

                Sys.Application.add_init(onLoadFunction);";

            // Insert the client ID of the page into the script block.  
            scriptBlock = string.Format(scriptBlock, Page.ClientID);

            // Register the script on the client.  This will make the script block available client-side
            // and execute statements that are not function or object declarations, in this case adding
            // onLoadFunction as a handler for the init event.
            this.Page.ClientScript.RegisterStartupScript(GetType(), scriptKeyCustom, scriptBlock, true); 
        }
    }

    #endregion

    #region ASP.NET Web Control Event Handlers

    public void CheckBoxList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        // Declare the variable to store the callback response
        string callbackResult = string.Empty;

        try
        {
            // Get a reference to CheckBoxList1 by casting the sender parameter to CheckBoxList
            System.Web.UI.WebControls.CheckBoxList checkBoxList = (System.Web.UI.WebControls.CheckBoxList)sender;

            // Declare a list object to hold the list of visible map resources
            System.Collections.Generic.List<string> visibleResourceList;
            // Check whether the visible resource list exists in the session variables
            if (Session["visibleResources"] == null)
                // The visible resource list isn't among the session variables, so instantiate a
                // new list object and assign it to visibleResourceList.
                visibleResourceList = new System.Collections.Generic.List<string>();
            else
                // Assign the visible resource list session variable to visibleResourceList
                visibleResourceList = (System.Collections.Generic.List<string>)Session["visibleResources"];

            // Iterate through the checkbox list items and add/remove a map resource based
            // on which item's selected state disagrees with the visibleResourceList
            for (int i = 0; i < checkBoxList.Items.Count; i++)
            {
                // Get a reference to the current list item
                System.Web.UI.WebControls.ListItem listItem = checkBoxList.Items[i];
                // Check whether the item's selected property matches whether it is 
                // contained in the list of visible resources.  If the item is selected
                // but not in the visible resource list, then the corresponding resource
                // needs to be added to the map.  If the item is in the visible resource
                // list but not selected, then the corresponding resource needs to be
                // removed from the map.
                if (listItem.Selected != visibleResourceList.Contains(listItem.Text))
                {
                    string resourceName = string.Empty;
                    // Assign the resource name variable based on the text of the current list item
                    switch (listItem.Text)
                    {
                        case "ArcGIS Server Local":
                            resourceName = AGSLocalName;
                            break;
                        case "ArcGIS Server Internet":
                            resourceName = AGSInternetName;
                            break;
                        case "ArcIMS":
                            resourceName = IMSName;
                            break;
                    }
                    // Call the AddOrRemoveMapResource method, which adds/removes
                    // resources to/from the map
                    callbackResult = AddOrRemoveMapResource(resourceName, listItem.Selected);

                    // Modify the list of visible resources so that it is in sync
                    // with which resources are visible on the map
                    if (visibleResourceList.Contains(listItem.Text))
                        visibleResourceList.Remove(listItem.Text);
                    else
                        visibleResourceList.Add(listItem.Text);

                    // The checked item has been found and action taken accordingly,
                    // so we can exit the loop iterating through the CheckBoxList items
                    break;
                }
            }

            // Update the visible resource list session variable
            Session["visibleResources"] = visibleResourceList;

        }
        catch (System.Exception exception)
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult =
                ErrorHandling.GetErrorCallback(exception);
            Map1.CallbackResults.Add(errorCallbackResult);
            callbackResult = Map1.CallbackResults.ToString();
        }

        // Register the callback response as a data item.  This sends the response back
        // to the client, where it can be accessed by handlers of the pageLoading, pageLoaded, or
        // endRequest events on the PageRequestManager object.  More specifically, the callback
        // response will be inserted into the dataItems array, which is passed to the client as a 
        // property of the second argument passed to any of the three aforementioned event 
        // handlers.  The response can be retrieved from the array by specifying the client ID of 
        // the control passed into the RegisterDataItem call (in this case Page) as the array
        // index.  In this case, a pageLoading handler was declared in the script block 
        // registered in the Page's PreRender event, and this handler retrieves the dataItem and 
        // passes it to ESRI.ADF.System.processCallbackResult.
        ScriptManager1.RegisterDataItem(Page, callbackResult, false);
    }

    #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.Visible = true;
                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
}