/// <summary>
        /// return the layers from a mapservice
        /// </summary>
        /// <param name="ms2">IMapServer2 object</param>
        /// <returns>a dictionary of service name and its corresponding id</returns>
        public Dictionary<string, int> getLayers(IMapServer2 ms2)
        {
            Dictionary<string, int> lyrDic = new Dictionary<string, int>();
            int maxR = getMaxRecords(ms2);
            if(maxR<1)
            {
                return lyrDic;
            }
            esriUtil.Forms.RunningProcess.frmRunningProcessDialog rp = new Forms.RunningProcess.frmRunningProcessDialog(false);
            try
            {
                rp.TopMost = true;
                rp.addMessage("Looking for eligible layers...");
                rp.addMessage("Please be patient...");
                rp.Show();
                rp.Refresh();
                for (int m = 0; m < ms2.MapCount; m++)
                {
                    rp.addMessage("Searching Map " + m.ToString());
                    rp.stepPGBar(5);
                    rp.Refresh();
                    string mName = ms2.get_MapName(m);
                    IMapServerInfo msInfo = ms2.GetServerInfo(mName);
                    IMapLayerInfos mLyrInfos = msInfo.MapLayerInfos;
                    for (int j = 0; j < mLyrInfos.Count; j++)
                    {
                        IMapLayerInfo mLyrInfo = mLyrInfos.get_Element(j);
                        bool ftrF = mLyrInfo.IsFeatureLayer;
                        bool ftrC = mLyrInfo.IsComposite;
                        bool ftrS = mLyrInfo.CanSelect;
                        bool geoField = false;
                        for (int i = 0; i < mLyrInfo.Fields.FieldCount; i++)
                        {
                            IField fld = mLyrInfo.Fields.get_Field(i);
                            if (fld.Type == esriFieldType.esriFieldTypeGeometry)
                            {
                                geoField = true;
                                break;
                            }
                        }
                        if (ftrF && ftrS && geoField && !ftrC)
                        {
                            rp.addMessage("\tFound layer" + mLyrInfo.Name);
                            rp.Refresh();
                            string lNm = mLyrInfo.Name;
                            int lyrId = mLyrInfo.ID;
                            if (!lyrDic.ContainsKey(lNm))
                            {
                                lyrDic.Add(lNm, lyrId);
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                rp.stepPGBar(100);
                rp.enableClose();
                rp.Close();
            }
            return lyrDic;
        }
        /// <summary>
        /// method used internally to update the default service table within the default geodatabase that stores all the server related server info
        /// </summary>
        /// <param name="lyrDic">the dictionary that has all related values</param>
        /// <param name="connection">url</param>
        public void updateServiceTable(string svConnection)
        {
            Dictionary<string, IAGSServerObjectName3> msSvrDic = getServices(svConnection);
            string conOidValue = getConnectionOID(svConnection);
            if (conOidValue == null)
            {
                return;
            }
            IQueryFilter qf = new QueryFilterClass();
            qf.WhereClause = "FKID = " + conOidValue;
            removeExistingRecords(tblSrv, qf);
            int srvIndex = tblSrv.FindField("SERVICE");
            int urlIndex = tblSrv.FindField("URL");
            int sfkIndex = tblSrv.FindField("FKID");
            int sTypeIndex = tblSrv.FindField("STYPE");
            Forms.RunningProcess.frmRunningProcessDialog rp = new Forms.RunningProcess.frmRunningProcessDialog(false);
            rp.TopMost = true;
            rp.Show();
            rp.Refresh();
            try
            {
                rp.addMessage("Getting all available services...");
                rp.addMessage("Please be patient...");
                rp.stepPGBar(10);
                rp.Refresh();

                foreach (KeyValuePair<string, IAGSServerObjectName3> kVp in msSvrDic)
                {
                    rp.addMessage("Looking at service " + kVp.Key);
                    rp.stepPGBar(5);
                    rp.Refresh();
                    IWorkspaceEdit wksE = (IWorkspaceEdit)servWks;
                    bool weStart = false;
                    if (!wksE.IsBeingEdited())
                    {
                        wksE.StartEditing(false);
                        weStart = true;
                    }
                    wksE.StartEditOperation();
                    try
                    {
                        IRow row2 = tblSrv.CreateRow();
                        int srvOidValue = row2.OID;
                        string ky = kVp.Key;
                        string kyl = ky.ToLower();
                        string vl = kVp.Value.URL;
                        string lTyp = kVp.Value.Type;
                        row2.set_Value(srvIndex, ky);
                        row2.set_Value(urlIndex, vl);
                        row2.set_Value(sTypeIndex, lTyp);
                        row2.set_Value(sfkIndex, System.Convert.ToInt32(conOidValue));
                        row2.Store();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    finally
                    {
                        wksE.StopEditOperation();
                        if (weStart)
                        {
                            wksE.StopEditing(true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                rp.stepPGBar(100);
                rp.enableClose();
                rp.Close();
            }
        }
        public string fillDbRaster(IImageServerLayer imSvLyr, IWorkspace wks,ESRI.ArcGIS.Geometry.IEnvelope ext,ISpatialReference sr, out IRaster outrs)
        {
            if (ext.SpatialReference.FactoryCode != sr.FactoryCode)
            {
                ext.Project(sr);
            }
            StringBuilder msg = new StringBuilder();
            if (wks == null)
            {
                wks = servWks;
            }
            outrs = null;
            Forms.RunningProcess.frmRunningProcessDialog rp = new Forms.RunningProcess.frmRunningProcessDialog(false);
            rp.addMessage("Downloading images please be patient...");
            rp.Show();
            //rp.showInSepperateProcess();
            rp.TopMost = true;
            rp.stepPGBar(10);
            rp.Refresh();
            DateTime dtS = DateTime.Now;
            try
            {
                rasterUtil rsUtil = new rasterUtil();
                int minX = System.Convert.ToInt32(ext.XMin);
                int maxX = System.Convert.ToInt32(ext.XMax);
                int minY = System.Convert.ToInt32(ext.YMin);
                int maxY = System.Convert.ToInt32(ext.YMax);
                int xDiff = System.Convert.ToInt32(ext.Width);
                int yDiff = System.Convert.ToInt32(ext.Height);
                int tile = 1;
                IRaster rast = rsUtil.createRaster(((IRaster2)imSvLyr.Raster).RasterDataset);
                ISaveAs saveas = (ISaveAs)rast;
                IRasterProps rasterProps = (IRasterProps)rast;
                imSvLyr.SpatialReference = sr;
                string nm = "T" + System.Guid.NewGuid().ToString().Substring(0, 3);
                string svImgNm = imSvLyr.ServiceInfo.Name;
                string rNm = nm;
                int mCols = System.Convert.ToInt32(imSvLyr.ServiceInfo.MaxNCols * .90);
                int mRows = System.Convert.ToInt32(imSvLyr.ServiceInfo.MaxNRows * .90);
                if (xDiff < mCols) mCols = xDiff;
                if (yDiff < mRows) mRows = yDiff;
                List<IRaster> tileLst = new List<IRaster>();
                for (int i = minX; i < maxX; i += mRows)
                {
                    for (int j = minY; j < maxY; j += mCols)
                    {

                        IEnvelope clipEnvelope = new EnvelopeClass();
                        clipEnvelope.PutCoords(i, j, i + mRows, j + mCols);
                        rasterProps.Extent = clipEnvelope;
                        rasterProps.Width = mRows;
                        rasterProps.Height = mCols;
                        rasterProps.SpatialReference = sr;
                        string r = rNm + tile.ToString();
                        if (r.Length > 12)
                        {
                            rp.addMessage("Too many tiles. Ending at Tile: " + tile);
                            msg.AppendLine("Too many tiles. Ending at Tile: " + tile);
                            //outrs = rsUtil.mosaicRastersFunction(wks, rNm, tileLst.ToArray(),esriMosaicMethod.esriMosaicNone,rstMosaicOperatorType.MT_FIRST,true,true,false,true);
                            return msg.ToString();
                        }
                        if (((IWorkspace2)wks).get_NameExists(esriDatasetType.esriDTRasterDataset, r))
                        {
                            r = rsUtil.getSafeOutputName(wks, r);
                            //Console.WriteLine("Deleting Raster " + r);
                            //((IRasterWorkspaceEx)wks).DeleteRasterDataset(r);
                        }
                        rp.addMessage("Creating tile " + r);
                        rp.stepPGBar(5);
                        rp.Refresh();
                        //Console.WriteLine("TestLength  = " + testLng.ToString());
                        tileLst.Add(rsUtil.returnRaster((IRasterDataset)saveas.SaveAs(r, wks, "GDB")));
                        msg.AppendLine("Added Tile " + r);
                        tile++;
                    }
                }
                rp.addMessage("Merging rasters...");
                rp.Refresh();
                //outrs = rsUtil.mosaicRastersFunction(wks, rNm, tileLst.ToArray(), esriMosaicMethod.esriMosaicNone, rstMosaicOperatorType.MT_FIRST, true, true, false, true);
            }
            catch (Exception e)
            {
                string x = e.ToString();
                msg.AppendLine(x);
                Console.WriteLine("Error: " + x);
            }
            finally
            {
                DateTime dtE = DateTime.Now;
                TimeSpan ts = dtE.Subtract(dtS);
                msg.AppendLine("Finished process in " + ts.TotalMinutes + " minutes.");
                rp.addMessage("Finished process in " + ts.TotalMinutes + " minutes.");
                rp.stepPGBar(100);
                rp.enableClose();
                rp.TopMost = false;
                rp.Close();
            }
            return msg.ToString();
        }
        /// <summary>
        /// Performs an unsupervised iso Clustering Maximum likelyhood classification
        /// </summary>
        /// <param name="inRasterDset"> input raster dataset (string, IRaster, IRasterDataset, IRasterDescription) used to perform the isoCluster</param>
        /// <param name="outWorkSpace">string identifing the output workspace</param>
        /// <param name="numClasses">int specifing the number of classes</param>
        /// <param name="outRstPath">the full path of the output Raster. If null will use outWorkSpace and name the raster iso</param>
        /// <param name="outSigPath">the full path fo the signature file. If null will use outWorkSpace and name signature file isoSig.gsg</param>
        /// <returns>geoprocessing messages</returns>
        public string isoClusterUnSupervised(object inRasterDset, IWorkspace outWorkSpace, int numClasses, string outRstPath, string outSigPath)
        {
            Forms.RunningProcess.frmRunningProcessDialog frmRd = new Forms.RunningProcess.frmRunningProcessDialog(false);
            frmRd.addMessage("Running Iso Cluster Unsupervised classification");
            frmRd.stepPGBar(10);
            frmRd.Show();
            string outRstStr = null;
            if (outRstPath == null)
            {
                outRstPath = outWorkSpace.PathName + "\\iso";
                outSigPath = System.IO.Path.GetDirectoryName(outWorkSpace.PathName) + "\\isoSig.gsg";
            }
            try
            {
                gp.OverwriteOutput = true;
                gp.SetEnvironmentValue("workspace", outWorkSpace.PathName);
                ESRI.ArcGIS.SpatialAnalystTools.IsoClusterUnsupervisedClassification isoCls = new IsoClusterUnsupervisedClassification();
                isoCls.Input_raster_bands = inRasterDset;
                isoCls.Minimum_class_size = numClasses * 10;
                isoCls.Number_of_classes = numClasses;
                isoCls.Output_classified_raster = outRstPath;
                isoCls.Output_signature_file = outSigPath;
                isoCls.Sample_interval = 10;
                IGeoProcessorResult gpRslt = (IGeoProcessorResult)gp.Execute(isoCls, null);
                frmRd.addMessage(getMessages(gpRslt));
                outRstStr = gpRslt.ReturnValue.ToString();
                frmRd.stepPGBar(60);
            }
            catch (Exception e)
            {
                string x = e.ToString();
                Console.WriteLine("New Error: " + x);
                frmRd.addMessage(x);
            }
            finally
            {
                frmRd.addMessage("Finished IsoCluster");
                frmRd.stepPGBar(100);
                frmRd.enableClose();
                frmRd.TopMost = false;
            }

            return outRstStr;
        }