ArcGIS Add Dynamic Data
ArcGIS_AddDynamicData_CSharp\CustomMapHandler_ADF.aspx.cs
// Copyright 2009 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.
// 

// Illustrates how to add a new layer dynamically to a pooled ArcGIS Server map service using Web ADF 
// controls and ArcObjects.  The layer is added in a shallowly stateful way, meaning that it persists
// in the users browser, but does not affect the map service when used by other clients.
public partial class CustomMapHandler_ADF : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    #region Instance Variable Declarations

    private string m_adfCallbackFunctionString;
    private ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResultCollection m_callbackResultCollection =
        new ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResultCollection();
    ServerObjectStateModifier m_serverObjectStateModifier = null;

    // Specify the name of the resource to target when adding/removing the dynamic layer
    private string m_targetResourceName = "MapResourceItem0";
    // Specify the name of the layer to be added/removed
    private string m_dynamicLayerName = "Canada";

    #endregion

    #region ASP.NET Page Life Cycle Event Handlers

    public void Page_PreInit(object sender, System.EventArgs eventArgs)
    {
        // Instantiate a ServerObjectStateModifier object to use for adding and removing the dynamic layer
        m_serverObjectStateModifier = new ServerObjectStateModifier();
    }

    protected void Page_Load(object sender, System.EventArgs eventArgs)
    {
        try
        {
            // 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);

            // Store the name of the resource to target for dynamic layer addition/removal in session.  We do this to share
            // this information with the custom map handler
            Session["targetResourceName"] = m_targetResourceName;

            // If the dynamic layer is currently present (indicated by the session variable), then we need to re-add it so that
            // the Web ADF components accessing the map resource containing that layer are aware of its presence.  
            if ((Session["dynamicLayerAdded"] != null) && ((bool)Session["dynamicLayerAdded"]))
            {
                // Get the dynamic layer's target resource and call the method to add the dynamic layer to it
                ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality agsMapFunctionality =
                    (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality)Map1.GetFunctionality(m_targetResourceName);
                ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal mapResourceLocal =
                    (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal)agsMapFunctionality.Resource;
                m_serverObjectStateModifier.AddLayer(mapResourceLocal, m_dynamicLayerName);
            }

            MapResourceManager1.ResourcesDispose += new System.EventHandler(MapResourceManager1_ResourcesDispose);
        }
        catch (System.Exception exception)
        {
            // Check whether the page is loading as a result of a callback.  If not, assume that a full page postback
            // is occuring, since this page implements the callback framework (and not partial postback).
            if (Page.IsCallback)
            {
                // Get a callback result that will show an alert with information pertaining to the exception
                ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult =
                    Utility.GetErrorCallback(exception);
                // Get the control that initiated the postback
                System.Web.UI.Control control = Utility.GetPostBackControl(Page);

                // If the control is a Web ADF Control (i.e. WebCotnrol or CompositeControl), add the error 
                // callback to that control's callback results.  Otherwise, add the error callback to the 
                // callback results collection member variable, which will be passed to the client in 
                // GetCallbackResult.
                if (control is ESRI.ArcGIS.ADF.Web.UI.WebControls.WebControl)
                {
                    ESRI.ArcGIS.ADF.Web.UI.WebControls.WebControl adfWebControl = control as
                        ESRI.ArcGIS.ADF.Web.UI.WebControls.WebControl;
                    adfWebControl.CallbackResults.Add(errorCallbackResult);
                }
                else if (control is ESRI.ArcGIS.ADF.Web.UI.WebControls.CompositeControl)
                {
                    ESRI.ArcGIS.ADF.Web.UI.WebControls.CompositeControl adfCompositeControl = control as
                        ESRI.ArcGIS.ADF.Web.UI.WebControls.CompositeControl;
                    adfCompositeControl.CallbackResults.Add(errorCallbackResult);
                }
                else
                {
                    m_callbackResultCollection.Add(errorCallbackResult);
                }
            }
            else
            {
                // Since the page is in full postback, write the javascript alert code directly to the response
                string jsErrorAlert = string.Format("<script>{0}</script>",
                    Utility.GetJavaScriptErrorString(exception));
                Response.Write(jsErrorAlert);
            }
        }
    }

    #endregion

    #region Web ADF Control Event Handlers

    void MapResourceManager1_ResourcesDispose(object sender, System.EventArgs e)
    {
        // If the dynamic layer is currently present (indicated by the session variable), then we need to remove it from the
        // map service before the server context created as a result of the current page request is released.  Otherwise, 
        // the layer will remain in the map service outside the scope of this request, making it possible for this layer to 
        // be seen by other clients.
        if ((Session["dynamicLayerAdded"] != null) && ((bool)Session["dynamicLayerAdded"]))
        {
            // Get the dynamic layer's target resource and call the method to remove the dynamic layer from it
            ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality agsMapFunctionality =
                (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality)Map1.GetFunctionality(m_targetResourceName);
            ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal mapResourceLocal =
                (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal)agsMapFunctionality.Resource;
            m_serverObjectStateModifier.RemoveLayer(mapResourceLocal, m_dynamicLayerName);
        }
    }

    protected void Toc1_NodeChecked(object sender, ESRI.ArcGIS.ADF.Web.UI.WebControls.TreeViewPlusNodeEventArgs treeViewPlusNodeArgs)
    {
        try
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.TreeViewPlusNode treeViewPlusNode = treeViewPlusNodeArgs.Node;
            ESRI.ArcGIS.ADF.Web.TocLayer tocLayer = treeViewPlusNode.Data as ESRI.ArcGIS.ADF.Web.TocLayer;

            if (tocLayer == null) return;

            // If the dynamic layer was clicked, change it's visibility in the Toc and store its new visibility in session.  
            // We do this so that the proper visibility can be applied if the layer is removed and re-added.
            if (tocLayer.Name == m_dynamicLayerName)
            {
                tocLayer.Visible = !tocLayer.Visible;
                Session["dynamicLayerVisible"] = tocLayer.Visible;
            }
        }
        catch (System.Exception exception)
        {
            // Get a callback that will show an alert containing information about the error and add it to the Toc's
            // callback results
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult = Utility.GetErrorCallback(exception);
            Toc1.CallbackResults.Add(errorCallbackResult);
        }
    }

    #endregion

    #region ICallbackEventHandler Members

    // Receives the arguments packaged in the callback on the client.  We parse those arguments here and 
    // initiate server-side logic accordingly.
    public void RaiseCallbackEvent(string eventArgs)
    {
        try
        {
            ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality agsMapFunctionality =
                    (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality)Map1.GetFunctionality(m_targetResourceName);
            ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal mapResourceLocal =
                (ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal)agsMapFunctionality.Resource;

            // 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 callbackArgsCollection =
                ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackUtility.ParseStringIntoNameValueCollection(eventArgs);

            // Check whether the callback event argument specifies adding or removing layers
            switch (callbackArgsCollection["EventArg"])
            {
                case "addLayer":
                    // Call the method to add the dynamic layer, which will add the layer to the map service.
                    m_serverObjectStateModifier.AddLayer(mapResourceLocal, m_dynamicLayerName);

                    // Refresh the Map and Toc controls so they show the layer.
                    RefreshMapAndToc();

                    // Set session variables indicating the presence and name of the dynamic layer.  We do this to share
                    // this information with the custom map handler.
                    Session["dynamicLayerAdded"] = true;
                    Session["dynamicLayerName"] = m_dynamicLayerName;
                    break;
                case "removeLayer":
                    // Call the method to remove the dynamic layer, which will remove the layer from the map service.
                    m_serverObjectStateModifier.RemoveLayer(mapResourceLocal, m_dynamicLayerName);

                    // Refresh the Map and Toc controls so they do not show the layer.
                    RefreshMapAndToc();

                    // Set the session variable indicating the absence of the dynamic layer
                    Session["dynamicLayerAdded"] = false;
                    break;
            }
        }
        catch (System.Exception exception)
        {
            // Get a callback result that will alert the user of the error and add it to the callback results collection
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorCallbackResult =
                Utility.GetErrorCallback(exception);
            m_callbackResultCollection.Add(errorCallbackResult);
        }
    }

    // Last server-side method called before the callback returns to the browser.  Here we specify the 
    // the server-side result of the callback (as a string) to be passed back to the browser.
    public string GetCallbackResult()
    {
        return m_callbackResultCollection.ToString();
    }

    #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

    // Refreshes the Map and Toc controls and populates the callback results member variable with the
    // resulting callback results 
    public void RefreshMapAndToc()
    {
        Toc1.Refresh();
        Map1.CallbackResults.CopyFrom(Toc1.CallbackResults);

        Map1.RefreshResource(m_targetResourceName);
        m_callbackResultCollection.CopyFrom(Map1.CallbackResults);
    }

    #endregion

}