-----------------------------------

Acquista i software ArcGIS tramite Studio A&T srl, rivenditore autorizzato dei prodotti Esri.

I migliori software GIS, il miglior supporto tecnico!

I migliori software GIS, il miglior supporto tecnico!
Azienda operante nel settore GIS dal 2001, specializzata nell’utilizzo della tecnologia ArcGIS e aderente ai programmi Esri Italia Business Network ed Esri Partner Network

-----------------------------------



Visualizzazione post con etichetta mapviewer. Mostra tutti i post
Visualizzazione post con etichetta mapviewer. Mostra tutti i post

venerdì 24 aprile 2009

Query Builder & Print SOE x MapViewer

Nel result task del Map Viewer se vuoi visualizzare le descrizioni del dominio aggiungi questa funzione in ESRI.ArcGIS.NITK -> Framework -> Results -> ResultProductiongTask.cs


/// <summary>
        /// Set the Results after applying renderers and IS_SELECTED column of the graphics layer to true.
        /// </summary>
        /// <param name="dtResults">Contains the data of the graphics layer.</param>
        /// <param name="sResourceName">Name of the resource to apply renderers.</param>
        /// <param name="sLayerId">Name of the layer Id to apply renderers.</param>        
        /// <param name="bSetAsSelected">Whether to set IsSelected column of graphics layer to true.</param>
        public void SetResults(ref DataTable dtResults, string sResourceName, string sLayerId, bool bSetAsSelected)
        {
            try
            {
                if (dtResults == null  dtResults.Rows.Count == 0)
                {
                    NoSelectionsTaskResult taskResult = new NoSelectionsTaskResult(this.Title);
                    Results = taskResult;
                }
                else
                {
 
                    dtResults = LoadDomainValues(dtResults); //<- add this function 
 
                ......


public DataTable LoadDomainValues(DataTable dt)
        {
            try
            {
                IDictionary<String, IDictionary<Int32, String>> dc = null;
                MapResourceLocal mr = (MapResourceLocal)Map.PrimaryMapResourceInstance;
                ESRI.ArcGIS.Carto.IMapServerObjects mso = (ESRI.ArcGIS.Carto.IMapServerObjects)mr.MapServer;
 
                ESRI.ArcGIS.Carto.ILayer layer = null;
 
 
                ESRI.ArcGIS.Carto.IMap map = mso.get_Map(mr.MapServer.DefaultMapName);
 
 
                ESRI.ArcGIS.Carto.IEnumLayer enumLayer = map.get_Layers(null, true);
                ESRI.ArcGIS.Carto.ILayer loopLayer = null;
                while ((loopLayer = enumLayer.Next()) != null)
                {
                    if (loopLayer.Name == dt.TableName)
                    {
                        layer = loopLayer;
                        break;
                    }
                }
 
                ESRI.ArcGIS.Carto.IFeatureLayer fl = (ESRI.ArcGIS.Carto.IFeatureLayer)layer;
                ESRI.ArcGIS.Geodatabase.IFeatureClass fclass = fl.FeatureClass;
                ESRI.ArcGIS.Geodatabase.IFields flds = fclass.Fields;
                ESRI.ArcGIS.Geodatabase.IDomain d = null;
                ESRI.ArcGIS.Geodatabase.ICodedValueDomain cvd = null;
 
                dc = new Dictionary<String, IDictionary<Int32, String>>();
 
 
                IDictionary<Int32, String> dm = null;
                ESRI.ArcGIS.Geodatabase.IField f = null;
                for (Int32 fi = 0; fi < flds.FieldCount; fi++)
                {
                    f = flds.get_Field(fi);
                    d = f.Domain;
                    if (d == null)
                        dm = null;
                    else
                    {
                        cvd = (ESRI.ArcGIS.Geodatabase.ICodedValueDomain)d;
                        dm = new Dictionary<Int32, String>();
                        for (Int32 i = 0; i < cvd.CodeCount; i++)
                            dm.Add(Convert.ToInt32(cvd.get_Value(i)), cvd.get_Name(i));
                    }
                    dc.Add(f.Name, dm);
                }
 
                IDictionary<Int32, String> listDomain = null;
                DataTable dtnew = dt.Clone();
                foreach (DataColumn c in dtnew.Columns)
                {
                    if (dc.ContainsKey(c.ColumnName))
                    {
                        listDomain = dc[c.ColumnName];
                        if (listDomain != null)
                            c.DataType = System.Type.GetType("System.String");
                    }
                }
 
 
                DataRow newRow;
                foreach (DataRow r in dt.Rows)
                {
 
                    newRow = dtnew.NewRow();
                    foreach (DataColumn c in dt.Columns)
                    {
                        if (dc.ContainsKey(c.ColumnName))
                        {
                            listDomain = dc[c.ColumnName];
                            if (listDomain == null)
                                newRow[c.ColumnName] = r[c.ColumnName];
                            else
                            {
                                if (!(r[c.ColumnName] is DBNull))
                                    newRow[c.ColumnName] = listDomain[Convert.ToInt32(r[c.ColumnName])];
                            }
                        }
                        else
                            newRow[c.ColumnName] = r[c.ColumnName];
                    }
                    dtnew.Rows.Add(newRow);
                }
                return dtnew;
            }
            catch (Exception ex)
            {
                _log.Error("Error in LoadDomainValues", ex);
                return dt;
 
            }
 
        }





Scarica qui il task Query Builder x MapViewer

Scarica qui il task Layout SOE x MapViewer (versione semplificata: solo PDF)

domenica 5 aprile 2009

Simple Photo gallery per MapViewer

This is a simple task to visualize a photo list associated to a feature: the task was developed integrating it in the map viewer ( http://resources.esri.com/arcgisserver/adf/dotnet/index.cfm?fa=codeGalleryDetails&scriptID=15963 ) framework. In the code, you will have to point out the id layer and the field name on which the feature must be searched (variable LayerId and fieldName). Besides, in the static function LoadImages you will have to write your business logic in order to get back the photo list.
For instance, in this function I get back the photo list from a table (many) joined with the feature class passing to the function the value in fieldName in feature class (one). In this particular case the join is between ObjectId in feature class and the relevant value in a many table field, while the value searched in input in the user's floating panel is another one, in this case the fieldName string type field parameter key passed to the function. The last sentence highlights that, if the field is of numeric type, the apostrophes in the query must be removed.
The function returning the photo list could become more than one because it can be modified in runtime (through the property methodImages) as it is called via reflection.




 
 
namespace Studioat.ARCGIS.ADF.Tasks
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data.OleDb;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ESRI.ArcGIS.ADF.Web;
using ESRI.ArcGIS.ADF.Web.DataSources;
using ESRI.ArcGIS.ADF.Web.UI.WebControls;
using ESRI.Solutions.NITK.Framework.Results;
using ESRI.Solutions.NITK.Framework.TaskResults;
//Author: Domenico Ciavarella
//www.studioat.it
[AjaxControlToolkit.ClientScriptResource("Studioat.ARCGIS.ADF.Tasks.PhotoGalleryTask", "Studioat.ARCGIS.ADF.Tasks.javascript.PhotoGalleryTask.js")]
[System.Web.UI.ToolboxData(@"<{0}:PhotoGalleryTask runat=""server"" BackColor=""White""
        BorderColor=""LightSteelBlue"" BorderStyle=""Outset"" BorderWidth=""1px"" Font-Names=""Verdana""
        Font-Size=""8pt"" ForeColor=""Black"" TitleBarColor=""WhiteSmoke"" TitleBarHeight=""20px""
        TitleBarSeparatorLine=""True"" Transparency=""35"" Width=""130px"">
        </{0}:PhotoGalleryTask>")]
public class PhotoGalleryTask : ResultProducingTask
{
static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static readonly string taskFullName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;
static readonly string taskNamespace = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
ITaskResultsContainer m_TaskResults;
//Change here your data
//*********************************************************
string LayerId = "1";
string fieldName = "YourNameFieldSearchUserFeature";
//*********************************************************
[Browsable(true)]
[Category("PhotoGalleryTask")]
[DefaultValue("LoadImages")]
[PersistenceMode(PersistenceMode.Attribute)]
[DisplayName("Method for list images")]
public string MethodImages
{
get
{
object o = StateManager.GetProperty("methodImages");
return (o == null) ? "LoadImages" : o as string;
}
set
{
StateManager.SetProperty("methodImages", value);
}
}
        #region CreateChildControls, Render
HtmlGenericControl container = null;
HtmlGenericControl containerDivPG = null;
Image progressImage = null;
Image htmlPrevButton = null;
Image htmlNextButton = null;
HtmlGenericControl containerDiv = null;
Image photoImage = null;
public HtmlInputText txtValue = null;
public HtmlInputButton btnFind = null;
protected override void CreateChildControls()
{
Controls.Clear();
base.CreateChildControls();
container = new HtmlGenericControl("div");
container.ID = "photoGallery";
Controls.Add(container);
containerDivPG = new HtmlGenericControl("div");
container.Controls.Add(containerDivPG);
htmlPrevButton = new Image();
htmlPrevButton.ID = "prevButton";
htmlPrevButton.ImageUrl = GetSource("backDisabled.png");
containerDivPG.Controls.Add(htmlPrevButton);
htmlNextButton = new Image();
htmlNextButton.ID = "nextButton";
htmlNextButton.ImageUrl = GetSource("forwardDisabled.png");
containerDivPG.Controls.Add(htmlNextButton);
progressImage = new Image();
progressImage.ID = "progress";
progressImage.ImageUrl = GetSource("activity_indicator.gif");
containerDivPG.Controls.Add(progressImage);
containerDiv = new HtmlGenericControl("div");
container.Controls.Add(containerDiv);
photoImage = new Image();
photoImage.ID = "image";
photoImage.ImageUrl = GetSource("gray_x_button.gif");
containerDiv.Controls.Add(photoImage);
txtValue = new HtmlInputText();
txtValue.ID = "txtValue";
Controls.Add(txtValue);
btnFind = new HtmlInputButton();
btnFind.ID = "btnFind";
btnFind.Value = "Find";
Controls.Add(btnFind);
StringBuilder KeyValues = new StringBuilder();
KeyValues.Append(string.Format("'{0}=' + $get('{1}').value", "txtFindValue", txtValue.ClientID));
string onClick = string.Format("executeTask({0},\"{1}\");", KeyValues.ToString(), CallbackFunctionString);
btnFind.Attributes.Add("onclick", onClick);
}
        #endregion
private string GetSource(string image)
{
return Page.ClientScript.GetWebResourceUrl(typeof(PhotoGalleryTask), string.Format("{0}.images.{1}", taskNamespace, image));
}
protected override void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
if (!base.IsAsync)
{
RegisterScriptControl();
}
}
protected string ControlClientID
{
get
{
EnsureChildControls();
return container.ClientID;
}
}
void RegisterScriptControl()
{
StringBuilder script = new StringBuilder();
script.Append("Sys.Application.add_init(function() {");
script.AppendFormat("$create({0},",taskFullName);
script.Append("{");
script.AppendFormat("'imageElement': $get('{0}'),", photoImage.ClientID);
script.AppendFormat("'prevElement': $get('{0}'),", htmlPrevButton.ClientID);
script.AppendFormat("'nextElement': $get('{0}'),", htmlNextButton.ClientID);
script.AppendFormat("'progressElement': $get('{0}'),", progressImage.ClientID);
script.AppendFormat("'forwardDisabledUrl': '{0}',", GetSource("forwardDisabled.png"));
script.AppendFormat("'backwardDisabledUrl': '{0}',", GetSource("backDisabled.png"));
script.AppendFormat("'forwardUrl': '{0}',", GetSource("forward.png"));
script.AppendFormat("'backwardUrl': '{0}',", GetSource("back.png"));
script.AppendFormat("'noPhotoUrl': '{0}',", GetSource("gray_x_button.gif"));
script.Append("'images': []");
script.AppendFormat("}}, {{}}, {{}}, $get('{0}'));", ControlClientID);
script.AppendLine("});");
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID + "_startup", script.ToString(), true);
}
/// <summary>
/// sample method used for list of images
/// </summary>
/// <param name="key">your key</param>
/// <returns>string: 'http://www.myphoto.com/01.jpg','http://www.myphoto.com/02.jpg' or string.Empty</returns>
static string LoadImages(string key)
{
//********************************************************************************
//change with your code. This is an example.
//********************************************************************************
string connectionString = ConfigurationManager.AppSettings["ConnectionDB"];
string pathFoto = ConfigurationManager.AppSettings["PhysicalPathFoto"];
string queryString = "SELECT Photo from featureclassOne,tableMany "
+ "WHERE (featureclassOne.objectid = tableMany.foreignKey) and (YourFieldName = ?)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.AddWithValue("@key", key);
try
{
string result=null;
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
result += string.Format("'{0}{1}{2}",pathFoto, reader[0].ToString().Replace("\\","/"),"',");
}
}
result = result.Substring(0, result.Length - 1);
return result;
}
catch
{
return string.Empty;
}
}  
}
public override void ExecuteTask()
{
Results = null;
if (Input == null) return;
NameValueCollection keyValColl = Input as NameValueCollection;
string stxtFindValue = keyValColl["txtFindValue"] as string;
string sWhere = string.Format("{0} = {2}{1}{2}", fieldName, stxtFindValue,"'");
ESRI.ArcGIS.ADF.Web.DataSources.IGISResource gisresource = Map.PrimaryMapResourceInstance;
IQueryFunctionality queryFunctionality = (IQueryFunctionality)gisresource.CreateFunctionality(typeof(IQueryFunctionality), null);
SpatialFilter spatialfilter = new SpatialFilter();
spatialfilter.ReturnADFGeometries = true;
spatialfilter.MaxRecords = 1;
spatialfilter.WhereClause = sWhere;
System.Data.DataTable datatable = queryFunctionality.Query(null, LayerId, spatialfilter);
if ((datatable == null)  (datatable.Rows.Count == 0))
{
NoSelectionsTaskResult setResultsTaskResult = new NoSelectionsTaskResult((datatable == null) ? "Error!" : "No found value!");
Results = setResultsTaskResult;
return;
}
try
{
SetResults(ref datatable, null, LayerId, true);
TaskResults.DisplayResults(null, null, null, this.Results);
TaskResults.Show();
MethodInfo dynMethod = GetType().GetMethod(MethodImages, BindingFlags.NonPublic  BindingFlags.Static);
object o = dynMethod.Invoke(this, new object[] { stxtFindValue });
CallbackResults.Add(CallbackResult.CreateJavaScript(string.Format("$find('{0}').set_images([{1}]);", ControlClientID, o)));
}
catch (Exception ex)
{
UnableToSetResultsTaskResult setResultsTaskResult = new UnableToSetResultsTaskResult(this.Title, ex.Message);
Results = setResultsTaskResult;
}
}
private ITaskResultsContainer TaskResults
{
get
{
if ((m_TaskResults == null) && (TaskResultsContainers[0] != null))
m_TaskResults = ESRI.ArcGIS.ADF.Web.UI.WebControls.Utility.FindControl(TaskResultsContainers[0].Name, Page) as ITaskResultsContainer;
return m_TaskResults;
}
}
public override string GetCallbackResult()
{
NameValueCollection keyValColl = CallbackUtility.ParseStringIntoNameValueCollection(CallbackEventArgument);
Input = keyValColl;
return base.GetCallbackResult();
}
public override List<GISResourceItemDependency> GetGISResourceItemDependencies()
{
throw new System.NotImplementedException();
}
}
}

Here you can download the source code http://resources.esri.com/arcgisserver/adf/dotnet/index.cfm?fa=codeGalleryDetails&scriptID=16219

Preview:








For Adalmj:
I used the same logic as this sample
and from the task I pass information to maptips

"if (result.StreetView != '')" +
                       "      {{" +
                              "mapTips.add_expanded(ExpandMapTips);" +
                              "mapTips.set_width(405);" +
                              "mapTips.set_maxheight(350);" +
                              "mapTips.set_contentTemplate('<span><b><a href=\'{{@StreetView}}\' target=\'_blank\'>Street View</a><br><br><a href=\'{{@GoogleMaps}}\' target=\'_blank\'>Google Maps</a></b></span><div onclick=\'var coords = new GLatLng({{@Lat}},{{@Lon}});panoramaOptions = {{ latlng:coords }};var myPano = new GStreetviewPanorama($get(""{{@Id}}""), panoramaOptions);\' name=\'{{@Id}}\' id=\'{{@Id}}\' style=\'width: 400px; height: 300px\'></div>');" +
                              "}}";