public override TestResult Execute(int paramSetId) { try { var param = new NameValueCollection(); _unitTestVm.ReadParameterValue(paramSetId, "USER", param); _unitTestVm.ReadParameterValue(paramSetId, "LOGIN", param); _unitTestVm.ReadParameterValue(paramSetId, "PASSWORD", param); var userInfo = new MgUserInformation(); userInfo.SetMgUsernamePassword(param["LOGIN"], param["PASSWORD"]); userInfo.SetLocale("en"); var site = new MgSite(); site.Open(userInfo); MgStringCollection roles = site.EnumerateRoles(param["USER"]); site.Close(); return(new TestResult(CommonUtility.MgStringCollectionToString(roles), "text/plain")); } catch (MgException ex) { return(TestResult.FromMgException(ex)); } }
// GET: Home public ActionResult Index() { MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSiteConnection conn = new MgSiteConnection(); conn.Open(user); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); var vm = new HomeViewModel() { HasSampleResources = true, AjaxLayout = AJAX_LAYOUT, FlexLayout = FLEX_LAYOUT }; MgResourceIdentifier mdfId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"); MgResourceIdentifier sample1 = new MgResourceIdentifier(vm.AjaxLayout); MgResourceIdentifier sample2 = new MgResourceIdentifier(vm.FlexLayout); vm.HasSampleResources = resSvc.ResourceExists(mdfId) && resSvc.ResourceExists(sample1) && resSvc.ResourceExists(sample2); return(View(vm)); }
public override TestResult Execute(int paramSetId) { try { var param = new NameValueCollection(); _unitTestVm.ReadParameterValue(paramSetId, "USER", param); _unitTestVm.ReadParameterValue(paramSetId, "LOGIN", param); _unitTestVm.ReadParameterValue(paramSetId, "PASSWORD", param); var userInfo = new MgUserInformation(); userInfo.SetMgUsernamePassword(param["LOGIN"], param["PASSWORD"]); userInfo.SetLocale("en"); var site = new MgSite(); site.Open(userInfo); MgByteReader reader = site.EnumerateGroups(param["USER"]); site.Close(); return(TestResult.FromByteReader(reader)); } catch (MgException ex) { return(TestResult.FromMgException(ex)); } }
protected void Page_Load(object sender, EventArgs e) { try { // Initialize a session and register a variable to hold the // session id, then initialize the Web Extensions, connect // to the site, and create a session. //InitializeWebTier(); MapGuideApi.MgInitializeWebTier(@"C:\Program Files\Autodesk\Autodesk Infrastructure Web Server Extension 2012\www\webconfig.ini"); // MgUserInformation userInfo = new MgUserInformation("Anonymous", ""); // MgSite site = new MgSite(); //site.Open(userInfo); // String sessionId = site.CreateSession(); //String webLayout = "Library://rany1/Layout/gis.WebLayout"; /* public String defaultUser = ConfigurationManager.AppSettings["defaultUser"]; public String defaultPassword = ConfigurationManager.AppSettings["defaultPassword"];*/ MgUserInformation userInfo = new MgUserInformation(defaultUser, defaultPassword); MgSite site = new MgSite(); site.Open(userInfo); sessionId = site.CreateSession(); } catch (Exception ex) { Response.Write(ex.Message); } }
protected MgSiteConnection CreateConnection(MapGuideViewerInputModel input) { MgSiteConnection conn = new MgSiteConnection(); MgUserInformation user = new MgUserInformation(input.Session); conn.Open(user); return conn; }
// GET: Home public ActionResult Index() { MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSiteConnection conn = new MgSiteConnection(); conn.Open(user); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); var vm = new HomeViewModel() { HasSampleResources = true, AjaxLayout = AJAX_LAYOUT, FlexLayout = FLEX_LAYOUT }; MgResourceIdentifier mdfId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"); MgResourceIdentifier sample1 = new MgResourceIdentifier(vm.AjaxLayout); MgResourceIdentifier sample2 = new MgResourceIdentifier(vm.FlexLayout); vm.HasSampleResources = resSvc.ResourceExists(mdfId) && resSvc.ResourceExists(sample1) && resSvc.ResourceExists(sample2); return View(vm); }
public bool ClearSpatialFilter() { bool result = true; MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource"); MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgMap map = new MgMap(); map.Open(resourceService, Request["MAPNAME"]); MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection(); MgLayer layer = null; MgLayerCollection layers = map.GetLayers(); if (layers.Contains("_QuerySpatialFilter")) { layer = (MgLayer)layers.GetItem("_QuerySpatialFilter"); updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0")); featureService.UpdateFeatures(sdfResId, updateCommands, false); layers.Remove(layer); map.Save(resourceService); } return result; }
protected MgSiteConnection CreateConnection(MapGuideViewerInputModel input) { MgSiteConnection conn = new MgSiteConnection(); MgUserInformation user = new MgUserInformation(input.Session); conn.Open(user); return(conn); }
protected void Page_Load(object sender, EventArgs e) { MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSite site = new MgSite(); site.Open(user); string sessionId = site.CreateSession(); string wl = "Library://Samples/Sheboygan/Layouts/SheboyganAsp.WebLayout"; Response.Redirect("http://localhost/mapguide/mapviewerajax/?WEBLAYOUT=" + wl + "&SESSION=" + sessionId); }
public MgOperationPacket(MgPacketHeader header, UInt32 packetVersion, UInt32 serviceID, UInt32 operationID, UInt32 operationVersion, UInt32 numArguments, MgUserInformation userInfo) : base(header) { PacketVersion = packetVersion; ServiceID = serviceID; OperationID = operationID; OperationVersion = operationVersion; NumArguments = numArguments; UserInfo = userInfo; }
private MgFeatureService GetMgFeatureService(string sessionId) { MapGuideApi.MgInitializeWebTier(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "../webconfig.ini"); MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection site = new MgSiteConnection(); site.Open(userInfo); MgFeatureService resourceService = (MgFeatureService)site.CreateService(MgServiceType.FeatureService); return(resourceService); }
String GetLegendIcons() { // Initialize the web-tier. String realPath = Request.ServerVariables["APPL_PHYSICAL_PATH"]; String configPath = realPath + "..\\webconfig.ini"; MapGuideApi.MgInitializeWebTier(configPath); // Connect to the site. MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); // Get an instance of the required service(s). MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; // Get the current map. MgMap map = new MgMap(); map.Open(resourceService, mapName); // Get map layers. MgLayerCollection mgLayers = map.GetLayers(); // Define table-body rows, one per layer. int mgLayerCount = mgLayers.Count; // Get the current-visiable layer list String jsonlist = ""; for (int i = 0; i < mgLayerCount; i++) { MgLayer mgLayer = mgLayers.GetItem(i) as MgLayer; Boolean inLegend = false; String mgLayerName = mgLayer.LegendLabel; String mgLegendImage = mgLayer.GetLayerDefinition().Path + "/" + mgLayer.GetName(); String mgLayerIsVisible = mgLayer.IsVisible() ? "on" : "off"; String[] mgLayerData = new String[] { mgLegendImage, mgLayerName, mgLayerIsVisible }; for (int j = 0; j < mgLayerData.Length - 1; j++) { if (mgLayerData[mgLayerData.Length - 1] == "on" && mgLayerData[mgLayerData.Length - 2].Trim() != "") { jsonlist += mgLayerData[j] + "$"; inLegend = true; } } if (inLegend) jsonlist = jsonlist.Substring(0, (jsonlist.Length - 1)) + "@"; } return jsonlist.Substring(0, (jsonlist.Length - 1)); }
//Usage: MgTestRunner.exe <webconfig.ini path> <MENTOR_DICTIONARY_PATH> [test log path] static void Main(string[] args) { if (args.Length >= 2 && args.Length <= 3) { string webconfig = args[0]; string logFile = "UnitTests.log"; if (args.Length == 3) { logFile = args[2]; } int failures = 0; using (var logger = new TestLoggerFile(logFile, false)) { logger.Write("Run started: {0}\n\n", DateTime.Now.ToString()); Environment.SetEnvironmentVariable("MENTOR_DICTIONARY_PATH", args[1], EnvironmentVariableTarget.Process); MapGuideApi.MgInitializeWebTier(args[0]); userInfo = new MgUserInformation("Administrator", "admin"); siteConn = new MgSiteConnection(); siteConn.Open(userInfo); var factory = new PlatformFactory(siteConn); int testsRun = 0; bool isEnterprise = false; failures += ExecuteTest(ApiTypes.Platform, "../../TestData/ResourceService/ResourceServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/DrawingService/DrawingServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/FeatureService/FeatureServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/SiteService/SiteServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/MappingService/MappingServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/ServerAdmin/ServerAdminTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/MapLayer/MapLayerTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/WebLayout/WebLayoutTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/Unicode/UnicodeTest.dump", ref testsRun, logger, isEnterprise); //Run auxillary tests not part of the SQLite-defined suite failures += CommonTests.Execute(factory, logger, ref testsRun); failures += MapGuideTests.Execute(factory, logger, ref testsRun); logger.Write("\n\nTests failed/run: {0}/{1}\n", failures, testsRun); Console.Write("\n\nTests failed/run: {0}/{1}\n", failures, testsRun); logger.Write("Run ended: {0}\n\n", DateTime.Now.ToString()); } Environment.ExitCode = failures; } else { Console.WriteLine("Usage: MgTestRunner.exe <webconfig.ini path> <MENTOR_DICTIONARY_PATH> [test log path]"); Environment.ExitCode = 1; } }
public ActionResult LoadSampleData(SetupInputModel input) { MgUserInformation user = new MgUserInformation(input.Username, input.Password); MgSiteConnection conn = new MgSiteConnection(); conn.Open(user); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); //Load the package file if specified if (input.Package != null && input.Package.ContentLength > 0) { var path = Path.GetTempFileName(); try { input.Package.SaveAs(path); MgByteSource bs = new MgByteSource(path); MgByteReader br = bs.GetReader(); resSvc.ApplyResourcePackage(br); } finally { try { if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } catch { } } } //Load in our sample-specific resources MgResourceIdentifier sample1 = new MgResourceIdentifier(AJAX_LAYOUT); MgResourceIdentifier sample2 = new MgResourceIdentifier(FLEX_LAYOUT); MgByteSource bs1 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.WebLayout.xml")); MgByteReader br1 = bs1.GetReader(); resSvc.SetResource(sample1, br1, null); MgByteSource bs2 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.ApplicationDefinition.xml")); MgByteReader br2 = bs2.GetReader(); resSvc.SetResource(sample2, br2, null); return(RedirectToAction("Index")); }
private static MgResourceService GetMgResurceService(string sessionId) { // Initialize web tier with the site configuration file. The config // file should be in the same directory as this script. // MapGuideApi.MgInitializeWebTier(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "../webconfig.ini"); MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection site = new MgSiteConnection(); site.Open(userInfo); MgResourceService resourceService = (MgResourceService)site.CreateService(MgServiceType.ResourceService); return(resourceService); }
public ActionResult LoadSampleData(SetupInputModel input) { MgUserInformation user = new MgUserInformation(input.Username, input.Password); MgSiteConnection conn = new MgSiteConnection(); conn.Open(user); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); //Load the package file if specified if (input.Package != null && input.Package.ContentLength > 0) { var path = Path.GetTempFileName(); try { input.Package.SaveAs(path); MgByteSource bs = new MgByteSource(path); MgByteReader br = bs.GetReader(); resSvc.ApplyResourcePackage(br); } finally { try { if (System.IO.File.Exists(path)) System.IO.File.Delete(path); } catch { } } } //Load in our sample-specific resources MgResourceIdentifier sample1 = new MgResourceIdentifier(AJAX_LAYOUT); MgResourceIdentifier sample2 = new MgResourceIdentifier(FLEX_LAYOUT); MgByteSource bs1 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.WebLayout.xml")); MgByteReader br1 = bs1.GetReader(); resSvc.SetResource(sample1, br1, null); MgByteSource bs2 = new MgByteSource(Server.MapPath("~/App_Data/SheboyganAspMvc.ApplicationDefinition.xml")); MgByteReader br2 = bs2.GetReader(); resSvc.SetResource(sample2, br2, null); return RedirectToAction("Index"); }
public override TestResult Execute(int paramSetId) { try { var site = new MgSite(); var user = new MgUserInformation(); user.SetMgSessionId(_session.SessionID ?? ""); site.Open(user); var userId = site.GetUserForSession(); site.Close(); return(new TestResult(userId, "text/plain")); } catch (MgException ex) { return(TestResult.FromMgException(ex)); } }
//Usage: MgTestRunner.exe <webconfig.ini path> <MENTOR_DICTIONARY_PATH> [test log path] static void Main(string[] args) { if (args.Length >= 2 && args.Length <= 3) { string webconfig = args[0]; string logFile = "UnitTests.log"; if (args.Length == 3) logFile = args[2]; int failures = 0; using (var logger = new TestLoggerFile(logFile, false)) { logger.Write("Run started: {0}\n\n", DateTime.Now.ToString()); Environment.SetEnvironmentVariable("MENTOR_DICTIONARY_PATH", args[1], EnvironmentVariableTarget.Process); MapGuideApi.MgInitializeWebTier(args[0]); userInfo = new MgUserInformation("Administrator", "admin"); siteConn = new MgSiteConnection(); siteConn.Open(userInfo); int testsRun = 0; bool isEnterprise = false; failures += ExecuteTest(ApiTypes.Platform, "../../TestData/ResourceService/ResourceServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/DrawingService/DrawingServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/FeatureService/FeatureServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/SiteService/SiteServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/MappingService/MappingServiceTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/ServerAdmin/ServerAdminTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/MapLayer/MapLayerTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/WebLayout/WebLayoutTest.dump", ref testsRun, logger, isEnterprise); failures += ExecuteTest(ApiTypes.Platform, "../../TestData/Unicode/UnicodeTest.dump", ref testsRun, logger, isEnterprise); logger.Write("\n\nTests failed/run: {0}/{1}\n", failures, testsRun); Console.Write("\n\nTests failed/run: {0}/{1}\n", failures, testsRun); logger.Write("Run ended: {0}\n\n", DateTime.Now.ToString()); } Environment.ExitCode = failures; } else { Console.WriteLine("Usage: MgTestRunner.exe <webconfig.ini path> <MENTOR_DICTIONARY_PATH> [test log path]"); Environment.ExitCode = 1; } }
public override TestResult Execute(int paramSetId) { try { var user = new MgUserInformation(); user.SetMgUsernamePassword("Administrator", "admin"); user.SetLocale("en"); var site = new MgSite(); site.Open(user); string session = site.CreateSession(); _session.SessionID = session; site.Close(); return(new TestResult(session, "text/plain")); } catch (MgException ex) { return(TestResult.FromMgException(ex)); } }
static void Main(string[] args) { var webConfigPath = @"C:\Program Files\OSGeo\MapGuide\Web\www\webconfig.ini"; MapGuideApi.MgInitializeWebTier(webConfigPath); MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSiteConnection conn = new MgSiteConnection(); conn.Open(user); MgSite site = conn.GetSite(); string sessionId = site.CreateSession(); Console.WriteLine("Session ID: " + sessionId); MgResourceIdentifier wlId = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganAsp.WebLayout"); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); MgWebLayout layout = new MgWebLayout(resSvc, wlId); Console.WriteLine("Web Layout Title: " + layout.GetTitle()); Console.WriteLine("Looks good! Press any key to continue"); Console.Read(); }
protected void Page_Load(object sender, EventArgs e) { MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSite site = new MgSite(); site.Open(user); string sessionId = site.CreateSession(); user.SetMgSessionId(sessionId); MgSiteConnection siteConn = new MgSiteConnection(); siteConn.Open(user); MgResourceIdentifier mdfId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); MgMap map1 = new MgMap(siteConn); map1.Create(mdfId, "ColdStart"); sw.Stop(); Trace.Write("ColdStart - " + sw.ElapsedMilliseconds + "ms"); sw.Reset(); sw.Start(); MgMap map2 = new MgMap(siteConn); map2.Create(mdfId, "WarmStart"); sw.Stop(); Trace.Write("WarmStart - " + sw.ElapsedMilliseconds + "ms"); sw.Start(); MgMap map3 = new MgMap(siteConn); map3.Create(mdfId, "WarmStart2"); sw.Stop(); Trace.Write("WarmStart2 - " + sw.ElapsedMilliseconds + "ms"); }
private void ClearSessions() { try { InitializeWebTier(); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); MgLayerCollection layerCol = map.GetLayers(); string layerName = "LocationMarker"; MgLayer layerToRemove = null; foreach(MgLayer layer in layerCol) { if(layer.Name == layerName) { layerToRemove = layer; break; } } if(layerToRemove != null) { layerCol.Remove(layerToRemove); } map.Save(resourceService); Xcoord.Value = ""; Ycoord.Value = ""; kanam.Value = "10000"; targetsnewTitle.InnerHtml = ""; targetsnew.InnerHtml = ""; targetsold.InnerHtml=""; targetsoldTitle.InnerHtml = ""; Response.Write("<script>try{ parent.parent.mapFrame.Refresh(); parent.parent.mapFrame.ZoomToSelection();}catch(e){}</script>"); /* success = true;*/ } catch (Exception exx) { } }
private void InitConnection(string sessionid) { MgUserInformation mgui = new MgUserInformation(sessionid); m_con = new MgSiteConnection(); m_con.Open(mgui); m_sessionId = sessionid; DisableAutoSessionRecovery(); }
/// <summary> /// Restarts the server session, and creates a new session ID /// </summary> /// <param name="throwException">If set to true, the call throws an exception if the call failed</param> /// <returns>True if the creation succeed, false otherwise</returns> protected override bool RestartSessionInternal(bool throwException) { if (m_username == null || m_password == null) if (throwException) throw new Exception("Cannot recreate session, because connection was not opened with username and password"); else return false; try { MgUserInformation mgui = new MgUserInformation(m_username, m_password); if (m_locale != null) mgui.SetLocale(m_locale); else mgui.SetLocale("en"); MgSiteConnection con = new MgSiteConnection(); con.Open(mgui); string s = con.GetSite().CreateSession(); if (s == null || s.Trim().Length == 0) throw new Exception("Failed to retrieve new session identifier"); m_sessionId = s; m_con = con; return true; } catch { if (throwException) throw; else return false; } }
public void ConnectToServer() { MgUserInformation userInfo = new MgUserInformation("Anonymous", ""); siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); }
public bool ShowSpatialFilter() { bool result = true; MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource"); MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection(); MgMap map = new MgMap(); map.Open(resourceService, Request["MAPNAME"]); MgLayer layer = null; MgLayerCollection layers = map.GetLayers(); if (layers.Contains("_QuerySpatialFilter")) { layer = (MgLayer)layers.GetItem("_QuerySpatialFilter"); //updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0")); } else { // Create the Feature Source (SDF) MgFeatureSchema sdfSchema = this.CreateFilterSchema(); MgCreateSdfParams sdfParams = new MgCreateSdfParams("MAPCS", map.GetMapSRS(), sdfSchema); featureService.CreateFeatureSource(sdfResId, sdfParams); // Create the Layer MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.LayerDefinition"); String layerDefinition = File.ReadAllText(GetQueryXmlTemplatePath()); layerDefinition = layerDefinition.Replace("%s", sdfResId.ToString()); MgByteReader reader = new MgByteReader(layerDefinition, "text/xml"); resourceService.SetResource(layerResId, reader, null); layer = new MgLayer(layerResId, resourceService); layer.SetName("_QuerySpatialFilter"); layer.SetLegendLabel("תחום זמני"); layer.SetDisplayInLegend(true); layer.SetSelectable(true); layer.ForceRefresh(); layer.NeedsRefresh(); layers.Insert(0, layer); } // Make the layer visible layer.SetVisible(true); map.Save(resourceService); // Add the geometry to the filter feature source MgPolygon polygon = this.CreatePolygonFromGeomText(Request["GEOMTEXT"].ToString()); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); MgByteReader byteReader = agfWriter.Write(polygon); MgPropertyCollection propertyValues = new MgPropertyCollection(); propertyValues.Add(new MgGeometryProperty("Geometry", byteReader)); try { updateCommands.Add(new MgInsertFeatures("Filter", propertyValues)); featureService.UpdateFeatures(sdfResId, updateCommands, false); } catch { } return result; }
private string createMapSiteSession() { // Initierar kartsite och kartsession string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString(); string mapUserName = ConfigurationManager.AppSettings["MGUserName"].ToString(); string mapUserPass = ConfigurationManager.AppSettings["MGUserPass"].ToString(); MapGuideApi.MgInitializeWebTier(mapWebTierInit); MgUserInformation userInfo = new MgUserInformation(mapUserName, mapUserPass); MgSite mapSite = new MgSite(); mapSite.Open(userInfo); string mapSiteSessionID = mapSite.CreateSession(); //mapSite.Close(); return mapSiteSessionID; }
public MgApplySession(MgUserInformation userInfo) { _userInfo = userInfo; }
public string getPlanMapImageAsBase64String(string planID, string imageWidth, string imageHeight) { try { MgUserInformation userInfo = null; string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString(); MapGuideApi.MgInitializeWebTier(mapWebTierInit); // Om kartsession finns för applikationssession använd den annars skapa ny kartssitesession string mapSiteSessionID = null; if (Session["MapSiteSessionID"] != null) { mapSiteSessionID = Session["MapSiteSessionID"].ToString(); userInfo = new MgUserInformation(mapSiteSessionID); } else { // Initierar kartsite och kartsession string mapUserName = ConfigurationManager.AppSettings["MGUserName"].ToString(); string mapUserPass = ConfigurationManager.AppSettings["MGUserPass"].ToString(); userInfo = new MgUserInformation(mapUserName, mapUserPass); MgSite mapSite = new MgSite(); mapSite.Open(userInfo); userInfo.Dispose(); mapSiteSessionID = mapSite.CreateSession(); //mapSite.Close(); Session["MapSiteSessionID"] = mapSiteSessionID; userInfo = new MgUserInformation(mapSiteSessionID); } //bool test = resSvc.ResourceExists(mapResId); string mapSurfaceFactor = ConfigurationManager.AppSettings["MGMapSurfaceFactor"].ToString(); string mapRes = ConfigurationManager.AppSettings["MGMapResource"].ToString(); string planRes = ConfigurationManager.AppSettings["MGPlanytorResource"].ToString(); string planClassName = ConfigurationManager.AppSettings["MGPlanytorClassName"].ToString(); string planFilterColumn = ConfigurationManager.AppSettings["MGPlanytorFilterColumn"].ToString(); string planGeometryColumn = ConfigurationManager.AppSettings["MGPlanytorGeometryColumn"].ToString(); string planytorStrokeRgbaColor = ConfigurationManager.AppSettings["MGPlanytorStrokeRgbaColor"].ToString(); string planytorForegroundRgbaColor = ConfigurationManager.AppSettings["MGPlanytorForegroundRgbaColor"].ToString(); string mapImageSizeFromServer = ConfigurationManager.AppSettings["MGMapImageSizeFromServer"].ToString(); // Standardvärde för storlek på kartbild, används om värde ej finns i Settings.config eller skickas in som parametrar i webbmetod string mapImageWidthPixel = "400"; string mapImageHeightPixel = "300"; // Väljer bredd och höjd på kartbild om värde ska finnas i Settings.config samt indikeras att de ska användas // annars förväntas värde skickas med i webbmetod if (mapImageSizeFromServer.ToLower() == "true") { mapImageWidthPixel = ConfigurationManager.AppSettings["MGMapImageWidth"].ToString(); mapImageHeightPixel = ConfigurationManager.AppSettings["MGMapImageHeight"].ToString(); } else { if (!string.IsNullOrWhiteSpace(imageWidth) && !string.IsNullOrWhiteSpace(imageHeight)) { mapImageWidthPixel = imageWidth; mapImageHeightPixel = imageHeight; } } MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceService resSvc = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgResourceIdentifier mapResId = new MgResourceIdentifier(mapRes); MgFeatureService featSvc = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgResourceIdentifier planResId = new MgResourceIdentifier(planRes); // Filter för planDoc efter planDoc-ID MgFeatureQueryOptions featureQuery = new MgFeatureQueryOptions(); featureQuery.SetFilter(planFilterColumn + " = " + planID); MgFeatureReader featureReader = featSvc.SelectFeatures(planResId, planClassName, featureQuery); MgByteReader byteReaderGeometry = null; MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryCollection geometryCollection = new MgGeometryCollection(); int featureCount = 0; try { while (featureReader.ReadNext()) { byteReaderGeometry = featureReader.GetGeometry(planGeometryColumn); MgGeometry districtGeometry = agfReaderWriter.Read(byteReaderGeometry); geometryCollection.Add(districtGeometry); featureCount++; } } finally { featureReader.Close(); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgMultiGeometry multiGeometry = geometryFactory.CreateMultiGeometry(geometryCollection); MgMap map = new MgMap(siteConnection); MgEnvelope envelope = multiGeometry.Envelope(); // Anpassar ev. punkt till komma i tal som hanteras som textsträng för kommande konvertering if (mapImageHeightPixel.IndexOf(".") != -1) { mapImageHeightPixel = mapImageHeightPixel.Replace(".", ","); } if (mapImageWidthPixel.IndexOf(".") != -1) { mapImageWidthPixel = mapImageWidthPixel.Replace(".", ","); } // Önskad bilds höjd och bredd i punkter double imageHeightPixel = Convert.ToDouble(mapImageHeightPixel); double imageWidthPixel = Convert.ToDouble(mapImageWidthPixel); map.DisplayDpi = 120; double heightEnvelopeN = envelope.Height; double widthEnvelopeE = envelope.Width; // Anpassar utbredningen på sökta planer (envelope) till bildens format för att bevara skalriktighet string mapFarthest = string.Empty; if (heightEnvelopeN > widthEnvelopeE) mapFarthest = "height"; else mapFarthest = "width"; string imageFarthest = string.Empty; if (imageHeightPixel > imageWidthPixel) imageFarthest = "height"; else imageFarthest = "width"; double scale = 1.0; const double inch = 2.54; // Ändring av kartans utbredning och addering av utrymme i kartans bild runt planavgränsningen // Map = avgränsning enligt planytan (utbredning i kartan), Image = önskad bild att skapa med kartan // Om: kartans höjd är längst & bildens bredd är längst if (mapFarthest == "height" && imageFarthest == "width") { scale = imageWidthPixel / imageHeightPixel * inch; widthEnvelopeE = imageWidthPixel / imageHeightPixel * heightEnvelopeN * scale; } // Om: kartans bredd är längst & bildens höjd är längst else if (mapFarthest == "width" && imageFarthest == "height") { scale = imageHeightPixel / imageWidthPixel * inch; heightEnvelopeN = imageHeightPixel / imageWidthPixel * widthEnvelopeE * scale; } // Om: kartans höjd är längst & bildens höjd är längst else if (mapFarthest == "height" && imageFarthest == "height") { double compareSide = (heightEnvelopeN / (imageHeightPixel / imageWidthPixel)); bool isCompareSideFarthest = false; if (compareSide > widthEnvelopeE) { isCompareSideFarthest = true; } else { isCompareSideFarthest = false; } scale = imageHeightPixel / imageWidthPixel * inch; if (isCompareSideFarthest) { widthEnvelopeE = heightEnvelopeN / (imageHeightPixel / imageWidthPixel) * scale; } else { heightEnvelopeN = (imageHeightPixel / imageWidthPixel) * widthEnvelopeE * scale; } } // Om(annars): kartans bredd är längst & bildens bredd är längst else { double compareSide = (widthEnvelopeE / (imageWidthPixel / imageHeightPixel)); bool isCompareSideFarthest = false; if (compareSide > heightEnvelopeN) { isCompareSideFarthest = true; } else { isCompareSideFarthest = false; } scale = imageWidthPixel / imageHeightPixel * inch; if (isCompareSideFarthest) { heightEnvelopeN = widthEnvelopeE / (imageWidthPixel / imageHeightPixel) * scale; } else { widthEnvelopeE = heightEnvelopeN * (imageWidthPixel / imageHeightPixel) * scale; } } double mapSurfaceFactorDbl = Convert.ToDouble(mapSurfaceFactor.Replace('.', ',')); double newHeightN = heightEnvelopeN * mapSurfaceFactorDbl; double newWidthE = widthEnvelopeE * mapSurfaceFactorDbl; MgCoordinate lowerLeft = envelope.LowerLeftCoordinate; MgCoordinate upperRight = envelope.UpperRightCoordinate; envelope = new MgEnvelope(lowerLeft.X - (newWidthE - widthEnvelopeE) / 2, lowerLeft.Y - (newHeightN - heightEnvelopeN) / 2, upperRight.X + (newWidthE - widthEnvelopeE) / 2, upperRight.Y + (newHeightN - heightEnvelopeN) / 2); map.Create(resSvc, mapResId, mapResId.Name); // Skapa lagerdefinition i XML DefineAreaLayer areaLayer = new DefineAreaLayer(); areaLayer.FeatureName = planClassName; areaLayer.FeatureSourceName = planRes; areaLayer.GeometryColumnName = planGeometryColumn; areaLayer.Filter = planFilterColumn + " = " + planID; LayerScaleRangeCollection lsrCollection = new LayerScaleRangeCollection(); LayerScaleRange lsr = new LayerScaleRange(); // MinScale applikations-default till 0 (inklusive) om utelämnat, MaxScale applikations-default till kartans maxskala (exklusive) om utelämnat //lsr.MinScale = "0"; //lsr.MaxScale = "100000000"; AreaTypeStyle ats = new AreaTypeStyle(); AreaRuleCollection arCollection = new AreaRuleCollection(); AreaRule ar = new AreaRule(); //ar.Filter = planFilterColumn + " = " + planID; ar.LegendLabel = "Plan" + planID; AreaSymbolization2D symb2D = new AreaSymbolization2D(); Fill fill = new Fill(); fill.BackgroundColor = "FFFF0000"; fill.FillPattern = "Solid"; fill.ForegroundColor = convertRgbsToHexColor(planytorForegroundRgbaColor); Stroke stroke = new Stroke(); stroke.Color = convertRgbsToHexColor(planytorStrokeRgbaColor); stroke.LineStyle = "Solid"; stroke.Thickness = "1"; stroke.Unit = "Points"; symb2D.Fill = fill; symb2D.Stroke = stroke; ar.Symbolization2D = symb2D; arCollection.Add(ar); ats.AreaRules = arCollection; lsr.AreaTypeStyle = ats; lsrCollection.Add(lsr); areaLayer.LayerScaleRanges = lsrCollection; XmlDocument xmlFile = new XmlDocument(); //XDocument xmlFile = new XDocument(); // om returnerande av xml-dokument //xmlFile = areaLayer.CreateLayerDefinitionAsXmlDocument(); // om returnerande av xml-sträng xmlFile.LoadXml(areaLayer.CreateLayerDefinitionAsXmlString()); //xmlFile = areaLayer.CreateLayerDefinitionAsXDocument(); //xmlFile.Save(Server.MapPath(this.Context.Request.ApplicationPath) + "XmlTestLayerDefinition.xml"); using (MemoryStream msNewPlanLayer = new MemoryStream()) { xmlFile.Save(msNewPlanLayer); msNewPlanLayer.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] layerDefinition = msNewPlanLayer.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(layerDefinition)); layerDefinition = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(layerDefinition, layerDefinition.Length); MgResourceIdentifier layerResourceID = new MgResourceIdentifier("Session:" + mapSiteSessionID + "//" + "planytor" + ".LayerDefinition"); //"SearchedPlan" + planID + ".LayerDefinition"); resSvc.SetResource(layerResourceID, byteSource.GetReader(), null); MgLayer newPlanLayer = new MgLayer(layerResourceID, resSvc); newPlanLayer.SetName("Sökta planer"); newPlanLayer.SetVisible(true); newPlanLayer.SetLegendLabel("Sökta planer"); newPlanLayer.SetDisplayInLegend(true); MgLayerCollection layerCollection = map.GetLayers(); if (!layerCollection.Contains(newPlanLayer)) { // Insert the new layer at position 0 so it is at the top // of the drawing order layerCollection.Insert(0, newPlanLayer); } else { layerCollection.Remove(newPlanLayer); layerCollection.Insert(0, newPlanLayer); } map.Save(); } double mapScale = map.ViewScale; // XML-dokument till ren text //StringWriter stringWriter = new StringWriter(); //XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter); //xmlFile.WriteTo(xmlTextWriter); //xmlTextWriter.Flush(); string xmlSelection = string.Empty; //string xmlSelection = stringWriter.GetStringBuilder().ToString(); MgSelection selection = null; if (!string.IsNullOrEmpty(xmlSelection)) { selection = new MgSelection(map, xmlSelection); } else { selection = new MgSelection(map); } MgColor color = new MgColor("255,255,255"); // Skapar bild av kartan MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService); //MgByteReader byteReader = renderingService.RenderMap(map, selection, "PNG"); MgByteReader byteReader = renderingService.RenderMap(map, selection, envelope, Convert.ToInt32(imageWidthPixel), Convert.ToInt32(imageHeightPixel), color, "PNG"); MemoryStream ms = new MemoryStream(); byte[] byteBuffer = new byte[1024]; int numBytes = byteReader.Read(byteBuffer, 1024); while (numBytes > 0) { ms.Write(byteBuffer, 0, numBytes); numBytes = byteReader.Read(byteBuffer, 1024); } byte[] mapImageByte = ms.ToArray(); string imageBase64String = Convert.ToBase64String(mapImageByte); map.Dispose(); siteConnection.Dispose(); DataTable dtResult = new DataTable(); DataColumn dc = new DataColumn("MAPIMAGEBASE64"); dtResult.Columns.Add(dc); dc = new DataColumn("WIDTH"); dtResult.Columns.Add(dc); dc = new DataColumn("HEIGHT"); dtResult.Columns.Add(dc); DataRow dr = dtResult.NewRow(); dr["MAPIMAGEBASE64"] = imageBase64String; dr["WIDTH"] = imageWidthPixel; dr["HEIGHT"] = imageHeightPixel; dtResult.Rows.Add(dr); //TODO: MAP: Vad kan returneras, base64 eller länk där bild temporärt genereras på server //JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //return jsonSerializer.Serialize(imageBase64String); return getDatatableAsJson(dtResult); } catch (System.Exception ex) { UtilityException.LogException(ex, "Webbmetod : getPlanMapImageAsBase64String", true); return null; } }
public void CreateMarkup(string mgSessionId,string mgMap) { //Response.Write("CreateMarkup" ); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); // map.Open(resourceService, GetParameter(args, "MAPNAME")); // Create the Markup Feature Source (SDF) MgResourceIdentifier markupSdfResId = new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".FeatureSource"); MgFeatureSchema markupSchema = MarkupSchemaFactory.CreateMarkupSchema(); MgCreateSdfParams sdfParams = new MgCreateSdfParams("XY-M", map.MapSRS, markupSchema); featureService.CreateFeatureSource(markupSdfResId, sdfParams); String url = "concat('" + GetParameter(this.args, "MARKUPURL") + "', concat('?key=', "ID"))"; //Link to ProjectManager /* if (GetParameter(this.args, "LINKTOPROJECTMANAGER").ToLower() == "on" && !String.IsNullOrEmpty(GetParameter(this.args, "ProjectCollectionName")) && GetParameter(this.args, "ProjectCollectionName") != "áçø îøùéîä") { string projectCollectionName = GetParameter(this.args, "ProjectCollectionName"); if (projectCollectionName == "àçø...") { projectCollectionName = GetParameter(this.args, "ProjectCollectionOtherName"); } int projectId = 0; using (var conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ProjectManagerConnectionString"].ConnectionString)) { var cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO ProjectCollections(LayoutId, FeatureId, ProjectCollectionName) VALUES(@LayoutId, @FeatureId, @ProjectCollectionName); SELECT @@IDENTITY AS [NEWID]"; cmd.CommandType = System.Data.CommandType.Text; var layoutIdParam = new System.Data.SqlClient.SqlParameter("@LayoutId", System.Data.SqlDbType.NVarChar, 255); layoutIdParam.Value = GetParameter(args, "LAYOUT"); cmd.Parameters.Add(layoutIdParam); var featureIdParam = new System.Data.SqlClient.SqlParameter("@FeatureId", System.Data.SqlDbType.NVarChar, 255); featureIdParam.Value = markupSdfResId.ToString(); cmd.Parameters.Add(featureIdParam); var pcNameParam = new System.Data.SqlClient.SqlParameter("@ProjectCollectionName", System.Data.SqlDbType.NVarChar, 50); pcNameParam.Value = projectCollectionName; cmd.Parameters.Add(pcNameParam); conn.Open(); //projectId = (int)cmd.ExecuteScalar(); using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { projectId = Convert.ToInt32(reader[0]); } } } string host = HttpContext.Current.Request.Url.Host; url = String.Format("concat('http://{0}/MgExtensions/ProjectManager/default.aspx?ProjectId={1}&UID=', \"UID\")", host, projectId); } */ // Create the Markup Layer Definition String hexFgTransparency = String.Format("{0:X2}", 255 * (100 - Int32.Parse(GetParameter(this.args, "FILLTRANSPARENCY"))) / 100); // Convert % to an alpha value String hexBgTransparency = GetParameter(this.args, "FILLBACKTRANS").Length > 0 ? "FF" : "00"; // All or nothing String bold = GetParameter(this.args, "LABELBOLD").Length > 0 ? "true" : "false"; String italic = GetParameter(this.args, "LABELITALIC").Length > 0 ? "true" : "false"; String underline = GetParameter(this.args, "LABELUNDERLINE").Length > 0 ? "true" : "false"; String markupLayerDefinition = File.ReadAllText(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Extensions\\markup\\templates\\markuplayerdefinition.xml"); markupLayerDefinition = String.Format(markupLayerDefinition, markupSdfResId.ToString(), //<ResourceId> - Feature Source GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Mark Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Mark Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Mark Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Mark Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Mark Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Mark Label bold, //<Bold> - Mark Label italic, //<Bold> - Mark Label underline, //<Underlined> - Mark Label GetParameter(this.args, "MARKERSIZEUNITS"), //<Unit> - Mark GetParameter(this.args, "MARKERSIZE"), //<SizeX> - Mark GetParameter(this.args, "MARKERSIZE"), //<SizeY> - Mark GetParameter(this.args, "MARKERTYPE"), //<Shape> - Mark "FF" + GetParameter(this.args, "MARKERCOLOR"), //<ForegroundColor> - Mark "FF" + GetParameter(this.args, "MARKERCOLOR"), //<Color> - Mark GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Line Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Line Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Line Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Line Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Line Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Line Label bold, //<Bold> - Line Label italic, //<Bold> - Line Label underline, //<Underlined> - Line Label GetParameter(this.args, "LINEPATTERN"), //<LineStyle> - Line GetParameter(this.args, "LINETHICKNESS"), //<Thickness> - Line "FF" + GetParameter(this.args, "LINECOLOR"), //<Color> - Line GetParameter(this.args, "LINESIZEUNITS"), //<Unit> - Line GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Polygon Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Polygon Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Polygon Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Polygon Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Polygon Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Polygon Label bold, //<Bold> - Polygon Label italic, //<Bold> - Polygon Label underline, //<Underlined> - Polygon Label GetParameter(this.args, "FILLPATTERN"), //<FillPattern> - Fill hexFgTransparency + GetParameter(this.args, "FILLFORECOLOR"), //<ForegroundColor> - Fill hexBgTransparency + GetParameter(this.args, "FILLBACKCOLOR"), //<BackgroundColor> - Fill GetParameter(this.args, "BORDERPATTERN"), //<LineStyle> - Fill GetParameter(this.args, "BORDERTHICKNESS"), //<Thickness> - Fill "FF" + GetParameter(this.args, "BORDERCOLOR"), //<Color> - Fill GetParameter(this.args, "BORDERSIZEUNITS"), //<Unit> - Fill HttpContext.Current.Server.HtmlEncode(url)); //<Url> - url link MgByteReader byteReader = new MgByteReader(markupLayerDefinition, "text/xml"); resourceService.SetResource(new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".LayerDefinition"), byteReader, null); }
private static MgResourceService GetMgResurceService(string sessionId) { // Initialize web tier with the site configuration file. The config // file should be in the same directory as this script. // MapGuideApi.MgInitializeWebTier(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "../webconfig.ini"); MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection site = new MgSiteConnection(); site.Open(userInfo); MgResourceService resourceService = (MgResourceService)site.CreateService(MgServiceType.ResourceService); return resourceService; }
protected void Button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(Xcoord.Value) || string.IsNullOrEmpty(Ycoord.Value) || string.IsNullOrEmpty(kanam.Value)) { // Response.Write("<script type='text/javascript'>try{ zoom();}catch(e){}</script>"); ClientScript.RegisterStartupScript(GetType(), "zoomme", "<script>try{ zoomzfd();}catch(e){}</script>"); return; } /* String mgSessionId = GetRequestParameters()["SESSION"]; String mgMap = GetRequestParameters()["map"]; //GeocodeAddress addr = null; bool success = false; decimal LatInput=0; decimal LonInput=0;*/ // Initialize the web-extensions and connect to the Site using // the session identifier passed in the query string. try { InitializeWebTier(); //MgUserInformation userInfo = new MgUserInformation(mgSessionId); // mgSessionId = site.CreateSession(); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); decimal LatInput = System.Convert.ToDecimal(Xcoord.Value); decimal LonInput = System.Convert.ToDecimal(Ycoord.Value); /* LatInput = System.Convert.ToDecimal(GetRequestParameters()["LatInput"]); LonInput = System.Convert.ToDecimal(GetRequestParameters()["LonInput"]);*/ // Make the request to geocoder.us passing the address. //addr = requestGeocodeAddress(address); if (LatInput != 0 && LonInput != 0) { //Request the specified address to the geocode service using REST, the // GET interface // if (targetsnew.InnerHtml == "") { targetsnewTitle.InnerHtml = "מיקום נוכחי :"; targetsoldTitle.InnerHtml = ""; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } else { targetsoldTitle.InnerHtml = "מיקום קודם :"; targetsold.InnerHtml += targetsnew.InnerHtml; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } // The geocode successfully returned a location. //if (IsDebugAssembly(this.GetType().Assembly)) // System.Diagnostics.Debugger.Launch(); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); // map.Open(mgMap); // Check the map for the AddressMarker layer. If it does not // exist then create a feature source to store address results // and a layer to display them. MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Session:" + mgSessionId + "//LocationMarker.FeatureSource"); // Session:7f4231a2-0d7e-11e2-8000-000c294ca3a6_en_7F0000010AFC0AFB0AFA//a2f5e4fb-0c3c-4ee7-bb5d-c8f4a226a68b.FeatureSource // MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Library://rany1/Data/findLocation/temp/LocationMarker.FeatureSource"); // string layerDef = "Session:" + mgSessionId + "//LocationMarker.FeatureSource"; //string dataSource = "Library://rany1/Data/LocationMarker.FeatureSource"; /*string layerDef = "Library://rany1/Layers/LocationMarker.LayerDefinition"; MgLayerCollection colLays = map.GetLayers(); MgLayer layer = FindLayer(colLays, layerDef);*/ //// MgLayer locationLayer = FindLayerByName(,"LocationMarker") ;//GetLayerByName(map, "LocationMarker"); //MgLayerCollection colLays = map.GetLayers(); MgLayerCollection colLays = map.GetLayers(); MgLayer locationLayer = FindLayerByName(colLays, "LocationMarker"); if (locationLayer == null) { // diverr.InnerHtml += " לא נמצאו שכבות LocationMarker "; lf.CreateLocationMarkerFeatureSource(featureService, locationMarkerDataResId, map); locationLayer = lf.CreateLocationMarkerLayer(resourceService, locationMarkerDataResId, mgSessionId); map.GetLayers().Insert(0, locationLayer); } else if (locationLayer.GetVisible()) { // If the layer exists and is visible, then display the // previous results. //EmitAddressResults(featureService, locationMarkerDataResId, mgSessionId, Response); EmitLocationResults(featureService, locationMarkerDataResId, mgSessionId, HttpContext.Current.Response); } // Insert the results of the Geo-Code into the temporary // feature source and ensure the address marker layer // is visible. MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgPoint locationPoint = geometryFactory.CreatePoint(geometryFactory.CreateCoordinateXY(Convert.ToDouble(LonInput), Convert.ToDouble(LatInput))); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgStringProperty("Address", "")); properties.Add(new MgGeometryProperty("Location", geometryReaderWriter.Write(locationPoint))); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); commands.Add(new MgInsertFeatures("LocationMarker", properties)); featureService.UpdateFeatures(locationMarkerDataResId, commands, false); locationLayer.SetVisible(true); locationLayer.ForceRefresh(); map.Save(resourceService); Response.Write("<script type='text/javascript'>try{ parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); /* success = true;*/ } else { // Response.Write("<tr><td>נקודת הציון לא נמצאה: <hr></td></tr>"); } } catch (MgException eee) { // Response.Write("<script type='text/javascript'>try{alert('rany'); parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); // Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); // Response.Write("<tr><td>" + eee.InnerException.Message + "</td></tr>"); Response.Write("<tr><td>" + eee.ToString() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetBaseException() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetStackTrace()+ "</td></tr>"); Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); Response.Write("<tr><td class=\"Spacer\"></td></tr>"); // Response.Write("<tr><td>" + eee.GetDetails() + "</td></tr>"); } }
protected void Session_End(object sender, EventArgs e) { // Om kartsessions finns lagrad i applikationens session string sessionVariableName = "MapSiteSessionID"; if (Session[sessionVariableName] != null) { // Rensar bort kartsession, både kartsessions-ID från sessionsvariabeln och från kartserver string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString(); string mapSessionID = Session[sessionVariableName].ToString(); Session.Remove(sessionVariableName); MapGuideApi.MgInitializeWebTier(mapWebTierInit); MgUserInformation userInfo = new MgUserInformation(mapSessionID); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgSite mapSite = siteConnection.GetSite(); mapSite.DestroySession(mapSite.GetCurrentSession()); } }
//---------------------------------------------------------------------------------------- // �� �ܣ� ����վ������� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public void ConnectToServer(String userName, String password) { MgUserInformation userInfo = new MgUserInformation(userName, password); siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); }
public MapGuideTestExecutorCollection(MgUserInformation userInfo, MgSiteConnection conn) { _userInfo = userInfo; _conn = conn; }
public string AddNaaz(double X, double Y, string MapSession, string mapName) { try { string dataSource = "Session:" + MapSession + "//RedlineSymbol.FeatureSource"; string layerDef = "Session:" + MapSession + "//RedlineSymbol.LayerDefinition"; // MgSiteConnection site = MGMapObject.GetMgSite(MapSession); MgUserInformation userInfo = new MgUserInformation(MapSession); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); // Create a ReserviceService object and use it to open the Map // object from the sessions repository. Use the Map object to // determine if the "AddressMarker" layer is visible. MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); map.Open(resourceService, mapName); // MgLayer locationLayer = GetLayerByName(map, "LocationMarker"); if (siteConnection == null) { return "יש לרענן את האתר , לחיצה על כפתור הבית בפינה השמאלית עליונה"; } MgFeatureService featureSrvc = siteConnection.CreateService(2) as MgFeatureService; MgResourceService resourceSrvc = siteConnection.CreateService(0) as MgResourceService; MgResourceIdentifier dataSourceId = new MgResourceIdentifier(dataSource); MgResourceIdentifier layerDefId = new MgResourceIdentifier(layerDef); //MgMap map = MGMapObject.GetMgMap(resourceSrvc, mapName); MgGeometryFactory geomFactory = new MgGeometryFactory(); MgPoint geom = geomFactory.CreatePoint(geomFactory.CreateCoordinateXY(X, Y)); if (DataSourceExists(resourceSrvc, dataSourceId)) { resourceSrvc.DeleteResource(dataSourceId); } MgClassDefinition classDef = CreateFeatureClass("RedlineSymbol", "RedlineSymbol"); AddFeatureClassProperty(classDef, "KEY", 7, true); SetGeometryProp(classDef); MgFeatureSchema schema = CreateSchema(classDef, "RedlineSymbolShema", "RedlineSymbolShema"); MgCreateSdfParams parameters = new MgCreateSdfParams("ArbitraryXY", GetMapSrs(map), schema); featureSrvc.CreateFeatureSource(dataSourceId, parameters); MgLayerCollection layers = map.GetLayers(); MgLayer layer = FindLayer(layers, layerDef); LayerDefinitionFactory LayerDeffactory = new LayerDefinitionFactory(); if ((layer == null) && LayerDeffactory.CreateLayerDef("SymbolLayerDef_Cell", dataSource, "RedlineSymbol", "")) { resourceSrvc.SetResource(layerDefId, LayerDeffactory.layerDefContent, null); layer = new MgLayer(layerDefId, resourceSrvc); layer.SetDisplayInLegend(false); layer.SetSelectable(false); layer.SetVisible(true); layer.SetLegendLabel("ZoomSymbol"); layers.Insert(0, layer); } MgPropertyCollection featureProps = new MgPropertyCollection(); AddPointFeature("RedlineSymbol", featureProps, geom, featureSrvc, dataSourceId); if (layer != null) { layer.ForceRefresh(); } map.Save(resourceSrvc); siteConnection = null; map = null; dataSourceId = null; layerDefId = null; featureSrvc = null; resourceSrvc = null; geomFactory = null; geom = null; classDef = null; schema = null; featureProps = null; parameters = null; layers = null; layer = null; LayerDeffactory = null; GC.Collect(); GC.WaitForPendingFinalizers(); return "Ok"; } catch (Exception ex) { return ex.Message; } }
private MgResourceService GetMgResurceService(string sessionId) { MapGuideApi.MgInitializeWebTier(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "../webconfig.ini"); MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection site = new MgSiteConnection(); site.Open(userInfo); MgResourceService resourceService = (MgResourceService)site.CreateService(MgServiceType.ResourceService); return resourceService; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ����վ������� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public void ConnectToServer(String sessionID) { MgUserInformation userInfo = new MgUserInformation(sessionID); siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); }