public IWorkspace OpenSDEWorkspace() { m_workspaceFactory = new FileGDBWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspace = null; try { featureWorkspace = m_workspaceFactory.OpenFromFile(m_fgdbPath, 0) as IFeatureWorkspace; } catch { MessageBox.Show("请检查连接SDE服务器的连接字符串"); return null; } IWorkspace workspace = featureWorkspace as IWorkspace; this.m_workSpace = workspace; return workspace; }
private void openFile_Click(object sender, EventArgs e) { DialogResult res = openFileDlg.ShowDialog(this); if (res == DialogResult.OK) { try { zigFile.Text = openFileDlg.FileName; // Open workspace wksf = new PostGisWorkspaceFactory(); fwks = (IFeatureWorkspace)wksf.OpenFromFile(zigFile.Text, 0); // Open workspace IWorkspace ws = fwks as IWorkspace; // Show workspace PostGIS layer IEnumDatasetName edsn = ws.get_DatasetNames(esriDatasetType.esriDTFeatureClass); IDatasetName dsn; // Load PostGIS layer names clbLayers.Items.Clear(); while ((dsn = edsn.Next()) != null) { clbLayers.Items.Add(dsn.Name); } } catch (COMException COMex) { MessageBox.Show("Error " + COMex.ErrorCode.ToString() + ": " + COMex.Message); } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.Message); } } }
public static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); // To make changes to a Mosaic Dataset, a Standard or Advanced license is required. esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Flags to specify the operation to perform bool addToRD = true; // Create Watermark Function Raster Dataset bool addToMD = false; // Add Watermark Function to MD bool writeTemplateToXml = false; // Serialize a template form of the NDVI Custom Funtion to Xml. bool getfromXml = false; // Get a template object back from its serialized xml. #region Specify inputs. // Raster Dataset parameters string workspaceFolder = @"f:\data\RasterDataset\LACounty\"; string rasterDatasetName = "6466_1741c.tif"; // Output parameters for Function Raster Dataset string outputFolder = @"c:\temp\CustomFunction"; string outputName = "WatermarkSample.afr"; // Mosaic Dataset parameters // GDB containing the Mosaic Dataset string mdWorkspaceFolder = @"c:\temp\CustomFunction\SampleGdb.gdb"; // Name of the Mosaic Dataset string mdName = "SampleMD"; // Watermark Parameters string watermarkImagePath = @"e:\Dev\SDK\Raster\NET\Samples\CustomRasterFunction\CSharp\TestWatermarkFunction\Sample.png"; double blendPercentage = 80.00; esriWatermarkLocation wmLocation = esriWatermarkLocation.esriWatermarkCenter; // Xml file path to save to or read from xml. string xmlFilePath = @"c:\temp\CustomFunction\Xml\Watermark.RFT.xml"; #endregion if (addToRD) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(workspaceFolder, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(rasterDatasetName); AddWatermarkToRD(rasterDataset, outputFolder, outputName, watermarkImagePath, blendPercentage, wmLocation); // Cleanup workspaceFactory = null; rasterWorkspace = null; rasterDataset = null; } if (addToMD) { AddWatermarkDataToMD(mdWorkspaceFolder, mdName, watermarkImagePath, blendPercentage, wmLocation, true); } if (writeTemplateToXml && xmlFilePath != "") { // Create a template with the Watermark Function. IRasterFunctionTemplate watermarkFunctionTemplate = CreateWatermarkTemplate(watermarkImagePath, blendPercentage, wmLocation); // Serialize the template to an xml file. bool status = WriteToXml(watermarkFunctionTemplate, xmlFilePath); } if (getfromXml && xmlFilePath != "") { // Create a RasterFunctionTemplate object from the serialized xml. object serializedObj = ReadFromXml(xmlFilePath); if (serializedObj is IRasterFunctionTemplate) { Console.WriteLine("Success."); } else { Console.WriteLine("Failed."); } } Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } catch (Exception exc) { Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } }
/// <summary> /// Create a Mosaic Dataset in the geodatabase provided using the parameters defined by MDParamaters. /// </summary> /// <param name="gdbWorkspace">Geodatabase to create the Mosaic dataser in.</param> public void CreateMosaicDataset(IWorkspace gdbWorkspace) { try { #region Global Declarations IMosaicDataset theMosaicDataset = null; IMosaicDatasetOperation theMosaicDatasetOperation = null; IMosaicWorkspaceExtensionHelper mosaicExtHelper = null; IMosaicWorkspaceExtension mosaicExt = null; #endregion #region CreateMosaicDataset try { Console.WriteLine("Create Mosaic Dataset: " + MDParameters.mosaicDatasetName + ".amd"); /// Setup workspaces. /// Create Srs ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); // Create the mosaic dataset creation parameters object. ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass(); // Set the number of bands for the mosaic dataset. // If defined as zero leave defaults if (MDParameters.mosaicDatasetBands != 0) { creationPars.BandCount = MDParameters.mosaicDatasetBands; } // Set the pixel type of the mosaic dataset. // If defined as unknown leave defaults if (MDParameters.mosaicDatasetBits != rstPixelType.PT_UNKNOWN) { creationPars.PixelType = MDParameters.mosaicDatasetBits; } // Create the mosaic workspace extension helper class. mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass(); // Find the right extension from the workspace. mosaicExt = mosaicExtHelper.FindExtension(gdbWorkspace); // Default is none. if (MDParameters.productDefinitionKey.ToLower() != "none") { // Set the product definition keyword and properties. // (The property is called band definition keyword and band properties in the object). ((ICreateMosaicDatasetParameters2)creationPars).BandDefinitionKeyword = MDParameters.productDefinitionKey; MDParameters.productDefinitionProps = SetBandProperties(MDParameters.productDefinitionKey); if (MDParameters.productDefinitionProps.Count == 0) { Console.WriteLine("Setting production definition properties failed."); return; } ((ICreateMosaicDatasetParameters2)creationPars).BandProperties = MDParameters.productDefinitionProps; } // Use the extension to create a new mosaic dataset, supplying the // spatial reference and the creation parameters object created above. theMosaicDataset = mosaicExt.CreateMosaicDataset(MDParameters.mosaicDatasetName, MDParameters.mosaicDatasetSrs, creationPars, MDParameters.configKeyword); } catch (Exception exc) { Console.WriteLine("Exception Caught while creating Mosaic Dataset: " + exc.Message); return; } #endregion #region OpenMosaicDataset Console.WriteLine("Opening Mosaic Dataset"); theMosaicDataset = null; // Use the extension to open the mosaic dataset. theMosaicDataset = mosaicExt.OpenMosaicDataset(MDParameters.mosaicDatasetName); // The mosaic dataset operation interface is used to perform operations on // a mosaic dataset. theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset); #endregion #region Preparing Raster Type Console.WriteLine("Preparing Raster Type"); // Create a Raster Type Name object. IRasterTypeName theRasterTypeName = new RasterTypeNameClass(); // Assign the name of the Raster Type to the name object. // The Name field accepts a path to an .art file as well // the name for a built in Raster Type. theRasterTypeName.Name = MDParameters.rasterTypeName; // Use the Open function from the IName interface to get the Raster Type object. IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open()); if (theRasterType == null) { Console.WriteLine("Raster Type not found " + MDParameters.rasterTypeName); } // Set the URI Filter on the loaded raster type. if (MDParameters.rasterTypeProductFilter != "") { // Get the supported URI filters from the raster type object using the // raster type properties interface. IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters; IItemURIFilter productFilter = null; for (int i = 0; i < mySuppFilters.Count; ++i) { // Set the desired filter from the supported filters. productFilter = (IItemURIFilter)mySuppFilters.get_Element(i); if (productFilter.Name == MDParameters.rasterTypeProductFilter) { theRasterType.URIFilter = productFilter; } } } // Enable the correct templates in the raster type. string[] rasterProductNames = MDParameters.rasterTypeProductName.Split(';'); bool enableTemplate = false; if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != "")) { // Get the supported item templates from the raster type. IItemTemplateArray templateArray = theRasterType.ItemTemplates; for (int i = 0; i < templateArray.Count; ++i) { // Go through the supported item templates and enable the ones needed. IItemTemplate template = templateArray.get_Element(i); enableTemplate = false; for (int j = 0; j < rasterProductNames.Length; ++j) { if (template.Name == rasterProductNames[j]) { enableTemplate = true; } } if (enableTemplate) { template.Enabled = true; } else { template.Enabled = false; } } } if (MDParameters.dataSourceSrs != null) { ((IRasterTypeProperties)theRasterType).SynchronizeParameters.DefaultSpatialReference = MDParameters.dataSourceSrs; } #endregion #region Add DEM To Raster Type if (MDParameters.rasterTypeAddDEM && ((IRasterTypeProperties)theRasterType).SupportsOrthorectification) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile( System.IO.Path.GetDirectoryName(MDParameters.rasterTypeDemPath), 0);; IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset( System.IO.Path.GetFileName(MDParameters.rasterTypeDemPath)); IGeometricFunctionArguments geometricFunctionArguments = new GeometricFunctionArgumentsClass(); geometricFunctionArguments.DEM = myRasterDataset; ((IRasterTypeProperties)theRasterType).OrthorectificationParameters = geometricFunctionArguments; } #endregion #region Preparing Data Source Crawler Console.WriteLine("Preparing Data Source Crawler"); // Create a new property set to specify crawler properties. IPropertySet crawlerProps = new PropertySetClass(); // Specify a file filter crawlerProps.SetProperty("Filter", MDParameters.dataSourceFilter); // Specify whether to search subdirectories. crawlerProps.SetProperty("Recurse", true); // Specify the source path. crawlerProps.SetProperty("Source", MDParameters.dataSource); // Get the recommended crawler from the raster type based on the specified // properties using the IRasterBuilder interface. IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps); #endregion #region Add Rasters Console.WriteLine("Adding Rasters"); // Create a AddRaster parameters object. IAddRastersParameters AddRastersArgs = new AddRastersParametersClass(); // Specify the data crawler to be used to crawl the data. AddRastersArgs.Crawler = theCrawler; // Specify the raster type to be used to add the data. AddRastersArgs.RasterType = theRasterType; // Use the mosaic dataset operation interface to add // rasters to the mosaic dataset. theMosaicDatasetOperation.AddRasters(AddRastersArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Create a calculate cellsize ranges parameters object. ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass(); // Use the mosaic dataset operation interface to calculate cellsize ranges. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Building Boundary Console.WriteLine("Building Boundary"); // Create a build boundary parameters object. IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass(); // Set flags that control boundary generation. boundaryArgs.AppendToExistingBoundary = true; // Use the mosaic dataset operation interface to build boundary. theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null); #endregion if (MDParameters.buildOverviews) { #region Defining Overviews Console.WriteLine("Defining Overviews"); // Create a define overview parameters object. IDefineOverviewsParameters defineOvArgs = new DefineOverviewsParametersClass(); // Use the overview tile parameters interface to specify the overview factor // used to generate overviews. ((IOverviewTileParameters)defineOvArgs).OverviewFactor = 3; // Use the mosaic dataset operation interface to define overviews. theMosaicDatasetOperation.DefineOverviews(defineOvArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Calculate cell size ranges to update the Min/Max pixel sizes. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Generating Overviews Console.WriteLine("Generating Overviews"); // Create a generate overviews parameters object. IGenerateOverviewsParameters genPars = new GenerateOverviewsParametersClass(); // Set properties to control overview generation. IQueryFilter genQuery = new QueryFilterClass(); ((ISelectionParameters)genPars).QueryFilter = genQuery; genPars.GenerateMissingImages = true; genPars.GenerateStaleImages = true; // Use the mosaic dataset operation interface to generate overviews. theMosaicDatasetOperation.GenerateOverviews(genPars, null); #endregion } #region Report Console.WriteLine("Success."); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in CreateMD: " + exc.Message); Console.WriteLine("Shutting down."); #endregion } }
/// <summary> /// /// </summary> /// <param name="pSourceFeatureClass"></param> /// <param name="_pTWorkspaceFactory"></param> /// <param name="_pTWs"></param> /// <param name="_pTName"></param> public void ConvertQuery2FeatureClass( IFeatureClass pSourceFeatureClass , IWorkspaceFactory _pTWorkspaceFactory, String _pTWs, string _pTName) { IWorkspace pTWorkspace = _pTWorkspaceFactory.OpenFromFile(_pTWs, 0); IDataset pSDataset = pSourceFeatureClass as IDataset; IFeatureClassName pSourceFeatureClassName = pSDataset.FullName as IFeatureClassName; IDataset pTDataset = (IDataset)pTWorkspace; IName pTDatasetName = pTDataset.FullName; IWorkspaceName pTargetWorkspaceName = (IWorkspaceName)pTDatasetName; IFeatureClassName pTargetFeatureClassName = new FeatureClassNameClass(); IDatasetName pTargetDatasetName = (IDatasetName)pTargetFeatureClassName; // 验证要素类的名称是否合法,但是并没有对这个名称是否存在做检查 string pTableName = null; IFieldChecker pNameChecker = new FieldCheckerClass(); pNameChecker.ValidateWorkspace = pTWorkspace; int pFlag = pNameChecker.ValidateTableName(_pTName, out pTableName); pTargetDatasetName.Name = pTableName; pTargetDatasetName.WorkspaceName = pTargetWorkspaceName; // 创建字段检查对象 IFieldChecker pFieldChecker = new FieldCheckerClass(); IFields sourceFields = pSourceFeatureClass.Fields; IFields pTargetFields = null; IEnumFieldError pEnumFieldError = null; pFieldChecker.InputWorkspace = ((IDataset)pSourceFeatureClass).Workspace; pFieldChecker.ValidateWorkspace = pTWorkspace; // 验证字段 pFieldChecker.Validate(sourceFields, out pEnumFieldError, out pTargetFields); if (pEnumFieldError != null) { // 报错提示 Console.WriteLine("Errors were encountered during field validation."); } String pShapeFieldName = pSourceFeatureClass.ShapeFieldName; int pFieldIndex = pSourceFeatureClass.FindField(pShapeFieldName); IField pShapeField = sourceFields.get_Field(pFieldIndex); IGeometryDef pTargetGeometryDef = pShapeField.GeometryDef; // 创建要素转换对象 IFeatureDataConverter pFDConverter = new FeatureDataConverterClass(); IEnumInvalidObject pEnumInvalidObject = pFDConverter.ConvertFeatureClass(pSourceFeatureClassName, null, null, pTargetFeatureClassName, pTargetGeometryDef, pTargetFields, "", 1000, 0); // 检查是否有错误 IInvalidObjectInfo pInvalidInfo = null; pEnumInvalidObject.Reset(); while ((pInvalidInfo = pEnumInvalidObject.Next()) != null) { // 报错提示. Console.WriteLine("Errors occurred for the following feature: {0}", pInvalidInfo.InvalidObjectID); } }
private void OpenOleDbWorkspace(string tempMdbPathName, string datasetName, ref IWorkspaceFactory workspaceFactory, out IDataset attributeDataset, out ITable exportAttributes) { if (!File.Exists(tempMdbPathName)) throw new IOException("File not found"); IPropertySet propertySet = new PropertySet(); propertySet.SetProperty("CONNECTSTRING", String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", tempMdbPathName)); workspaceFactory = new OLEDBWorkspaceFactoryClass(); IWorkspace exportWorkspace = workspaceFactory.Open(propertySet, 0); exportAttributes = null; attributeDataset = null; IEnumDataset enumExportDatasets = exportWorkspace.get_Datasets(esriDatasetType.esriDTAny); while ((attributeDataset = enumExportDatasets.Next()) != null) { if (attributeDataset.Name == datasetName) { object attributeDatasetObject = attributeDataset.FullName.Open(); exportAttributes = attributeDataset as ITable; break; } } }
//Set the sampling size for one or all of the layers in the map //The sampling size determines how many messages are factored into the message rate calculation. //For instance a sampling size of 500 will store the times the last 500 messages were received. //The message rate is calculated as the (oldest timestamp - current time) / number of messages private void SetSampleSize() { try { int samplingSize = Convert.ToInt32(txtSampleSize.Text); ITemporalLayer temporalLayer = GetSelectedTemporalLayer(); if (temporalLayer == null) { if (m_amsWorkspaceFactory == null) { m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass(); } //Get the AMS Workspace Factory Statistics interface ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory; temporalWsfStatistics.SetAllSampleSizes(samplingSize); } else { ITemporalFeatureClassStatistics temporalFCStats = (ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass; temporalFCStats.SampleSize = samplingSize; } } catch (Exception ex) { statusBarXY.Text = ex.Message; } }
private IFeatureClass MakePointFC() { try { IGxCatalogDefaultDatabase Defaultgdb = ArcMap.Application as IGxCatalogDefaultDatabase; Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace pWorkspace = workspaceFactory.OpenFromFile(Defaultgdb.DefaultDatabaseName.PathName, 0); IFeatureWorkspace workspace = pWorkspace as IFeatureWorkspace; UID CLSID = new UID(); CLSID.Value = "esriGeodatabase.Feature"; IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; pFieldsEdit.FieldCount_2 = 6; IGeoDataset geoDataset = ArcMap.Document.ActiveView.FocusMap.get_Layer(0) as IGeoDataset; IGeometryDef pGeomDef = new GeometryDef(); IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit; pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGeomDefEdit.SpatialReference_2 = geoDataset.SpatialReference; IField pField; IFieldEdit pFieldEdit; //pField = new FieldClass(); //pFieldEdit = pField as IFieldEdit; //pFieldEdit.AliasName_2 = "ObjectID"; //pFieldEdit.Name_2 = "ObjectID"; //pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; //pFieldsEdit.set_Field(0, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "SHAPE"; pFieldEdit.Name_2 = "SHAPE"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; pFieldEdit.GeometryDef_2 = pGeomDef; pFieldsEdit.set_Field(0, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "LineOID"; pFieldEdit.Name_2 = "LineOID"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; pFieldsEdit.set_Field(1, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "Distance"; pFieldEdit.Name_2 = "Distance"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.set_Field(2, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "Elevation"; pFieldEdit.Name_2 = "Elevation"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.set_Field(3, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "X"; pFieldEdit.Name_2 = "X"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.set_Field(4, pFieldEdit); pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "Y"; pFieldEdit.Name_2 = "Y"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.set_Field(5, pFieldEdit); string strFCName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()); char[] chars = strFCName.ToCharArray(); if (Char.IsDigit(chars[0])) { strFCName = strFCName.Remove(0, 1); } KillExistingFeatureclass(strFCName); IFeatureClass pFeatureClass = workspace.CreateFeatureClass(strFCName, pFieldsEdit, CLSID, null, esriFeatureType.esriFTSimple, "SHAPE", ""); return(pFeatureClass); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); return(null); } }
private IFeatureClass MakeInMemoryFeatureClass(FusionTable ft, esriGeometryType geomType) { try { ISpatialReferenceFactory pSpatialRefFactory = new SpatialReferenceEnvironmentClass(); IGeographicCoordinateSystem pGeographicCoordSys = pSpatialRefFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); ISpatialReference pSpaRef = pGeographicCoordSys; pSpaRef.SetDomain(-180, 180, -90, 90); // Create an in-memory workspace factory. Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.InMemoryWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; // Create an in-memory workspace. IWorkspaceName workspaceName = workspaceFactory.Create("", "FusionTable", null, 0); // Cast for IName and open a reference to the in-memory workspace through the name object. IName name = workspaceName as IName; IWorkspace pWorkspace = name.Open() as IWorkspace; IFeatureWorkspace workspace = pWorkspace as IFeatureWorkspace; UID CLSID = new UID(); CLSID.Value = "esriGeodatabase.Feature"; IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; pFieldsEdit.FieldCount_2 = ft.columns.Count + 1; IGeometryDef pGeomDef = new GeometryDef(); IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit; pGeomDefEdit.GeometryType_2 = geomType; pGeomDefEdit.SpatialReference_2 = pSpaRef; IField pField; IFieldEdit pFieldEdit; pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = "SHAPE"; pFieldEdit.Name_2 = "SHAPE"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; pFieldEdit.GeometryDef_2 = pGeomDef; pFieldsEdit.set_Field(0, pFieldEdit); int k = 1; int i = 0; foreach (string col in ft.columns) { pField = new FieldClass(); pFieldEdit = pField as IFieldEdit; pFieldEdit.AliasName_2 = ft.columns[i]; pFieldEdit.Name_2 = ft.columns[i]; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldsEdit.set_Field(k, pFieldEdit); k++; i++; } string strFCName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()); char[] chars = strFCName.ToCharArray(); if (Char.IsDigit(chars[0])) { strFCName = strFCName.Remove(0, 1); } IFeatureClass pFeatureClass = workspace.CreateFeatureClass(strFCName, pFieldsEdit, CLSID, null, esriFeatureType.esriFTSimple, "SHAPE", ""); return(pFeatureClass); } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(ex.StackTrace); return(null); } }
public WorkspaceManagerViewModel(IWorkspaceFactory workspaceFactory) { _workspaceFactory = workspaceFactory; base.DisplayName = "Main Window"; }
static void Main(string[] args) { if (2 != args.Length) { System.Console.WriteLine("We need that GLRD csv file in this demo, dude! Also, tell me the State Name as filter please!"); return; } string gdb = string.Format(GDB_Name, args[1]); var prjs = ParseCSV(args[0], args[1]); if (prjs.Count > 0) { try { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork, esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst }); //print version info to console var runtimes = RuntimeManager.InstalledRuntimes; foreach (RuntimeInfo runtime in runtimes) { System.Console.WriteLine(runtime.Path); System.Console.WriteLine(runtime.Version); System.Console.WriteLine(runtime.Product.ToString()); } // Instantiate a file geodatabase workspace factory and create a file geodatabase. // The Create method returns a workspace name object. // Ugly way to create object through reflection Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); if (false == System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(args[0])) + "\\" + gdb)) { IWorkspaceName workspaceName = workspaceFactory.Create(System.IO.Path.GetDirectoryName(args[0]), gdb, null, 0); //ugly way to release raw COM Object ReleaseCOMObj(workspaceFactory); // Cast the workspace name object to the IName interface and open the workspace. IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); IFeatureWorkspace ftrspace = workspace as IFeatureWorkspace; List <dynamic> fldlst = new List <dynamic>(); fldlst.Add(new { Name = "Title", Type = esriFieldType.esriFieldTypeString }); IFeatureClass ftrClass = CreateFeatureClass(FtrClass_Name, ftrspace, esriGeometryType.esriGeometryPoint, 4326, fldlst); if (null != ftrClass) { IPoint pnt = null; double x, y; string title = null; int idxTitle = ftrClass.Fields.FindField("Title"); //http://edndoc.esri.com/arcobjects/9.2/NET/e7b33417-0373-4f87-93db-074910907898.htm // Create the feature buffer. IFeatureBuffer ftrBuffer = ftrClass.CreateFeatureBuffer(); // Create insert feature cursor using buffering. IFeatureCursor ftrCursor = ftrClass.Insert(true); foreach (var prj in prjs) { x = prj.X; y = prj.Y; title = prj.Name; pnt = new PointClass(); pnt.PutCoords(x, y); ftrBuffer.Shape = pnt; ftrBuffer.set_Value(idxTitle, title); ftrCursor.InsertFeature(ftrBuffer); } try { ftrCursor.Flush(); Console.WriteLine(string.Format("File GDB: {0} has been created!", gdb)); } catch (System.Runtime.InteropServices.COMException) { throw; } finally { ReleaseCOMObj(ftrCursor); } } } else { Console.WriteLine(string.Format("Dude, the GDB has been created already! Remove {0} and try again please.", gdb)); } //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); } catch (Exception e) { Console.WriteLine(e.Message); } } }
/// <summary> /// Export graphics to a shapefile /// </summary> /// <param name="fileNamePath">Path to shapefile</param> /// <param name="graphicsList">List of graphics for selected tab</param> /// <param name="ipSpatialRef">Spatial Reference being used</param> /// <returns>Created featureclass</returns> private IFeatureClass ExportToShapefile(string fileNamePath, List <Graphic> graphicsList, ISpatialReference ipSpatialRef, bool polyLineFC) { int index = fileNamePath.LastIndexOf('\\'); string folder = fileNamePath.Substring(0, index); string nameOfShapeFile = fileNamePath.Substring(index + 1); string shapeFieldName = "Shape"; IFeatureClass featClass = null; using (ComReleaser oComReleaser = new ComReleaser()) { try { IWorkspaceFactory workspaceFactory = null; workspaceFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFields fields = null; IFieldsEdit fieldsEdit = null; fields = new Fields(); fieldsEdit = (IFieldsEdit)fields; IField field = null; IFieldEdit fieldEdit = null; field = new FieldClass();///########### fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Shape"; fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry); IGeometryDef geomDef = null; IGeometryDefEdit geomDefEdit = null; geomDef = new GeometryDefClass();///######### geomDefEdit = (IGeometryDefEdit)geomDef; if (polyLineFC) { geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; } else { geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; } geomDefEdit.SpatialReference_2 = ipSpatialRef; fieldEdit.GeometryDef_2 = geomDef; fieldsEdit.AddField(field); string graphicsType = graphicsList[0].GraphicType.ToString(); switch (graphicsType) { case "Line": { field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Distance"; fieldEdit.AliasName_2 = "Geodetic Distance"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DistUnit"; fieldEdit.AliasName_2 = "Distance Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "OriginX"; fieldEdit.AliasName_2 = "Origin X"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "OriginY"; fieldEdit.AliasName_2 = "Origin Y"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DestX"; fieldEdit.AliasName_2 = "Dest X"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DestY"; fieldEdit.AliasName_2 = "Dest Y"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Angle"; fieldEdit.AliasName_2 = "Angle"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "AngleUnit"; fieldEdit.AliasName_2 = "Angle Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); break; } case "Circle": { field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Distance"; fieldEdit.AliasName_2 = "Distance"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DistUnit"; fieldEdit.AliasName_2 = "Distance Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DistType"; fieldEdit.AliasName_2 = "Distance Type"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterX"; fieldEdit.AliasName_2 = "Center X"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterY"; fieldEdit.AliasName_2 = "Center Y"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); break; } case "Ellipse": { field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "MajAxis"; fieldEdit.AliasName_2 = "Major Axis"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "MinAxis"; fieldEdit.AliasName_2 = "Minor Axis"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DistUnit"; fieldEdit.AliasName_2 = "Distance Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterX"; fieldEdit.AliasName_2 = "Center X"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterY"; fieldEdit.AliasName_2 = "Center Y"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Angle"; fieldEdit.AliasName_2 = "Angle"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "AngleUnit"; fieldEdit.AliasName_2 = "Angle Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); break; } case "RangeRing": { field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Rings"; fieldEdit.AliasName_2 = "Rings"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Distance"; fieldEdit.AliasName_2 = "Geodetic Distance"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "DistUnit"; fieldEdit.AliasName_2 = "Distance Unit"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "Radials"; fieldEdit.AliasName_2 = "Radials"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterX"; fieldEdit.AliasName_2 = "Center X"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); field = new FieldClass(); fieldEdit = (IFieldEdit)field; fieldEdit.Name_2 = "CenterY"; fieldEdit.AliasName_2 = "Center Y"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; fieldsEdit.AddField(field); break; } } featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); foreach (Graphic graphic in graphicsList) { if (graphic.Attributes == null) { continue; } IFeature feature = featClass.CreateFeature(); if (polyLineFC) { feature.Shape = graphic.Geometry; } else { feature.Shape = PolylineToPolygon(graphic.Geometry); } switch (graphic.GraphicType.ToString()) { case "Line": { System.Object dist; System.Object angle; System.Object angleunit; System.Object ox; System.Object oy; System.Object dx; System.Object dy; System.Object distunit; graphic.Attributes.TryGetValue("distance", out dist); graphic.Attributes.TryGetValue("distanceunit", out distunit); graphic.Attributes.TryGetValue("startx", out ox); graphic.Attributes.TryGetValue("starty", out oy); graphic.Attributes.TryGetValue("endx", out dx); graphic.Attributes.TryGetValue("endy", out dy); graphic.Attributes.TryGetValue("angle", out angle); graphic.Attributes.TryGetValue("angleunit", out angleunit); feature.set_Value(feature.Fields.FindField("Distance"), dist); feature.set_Value(feature.Fields.FindField("DistUnit"), distunit); feature.set_Value(feature.Fields.FindField("OriginX"), ox); feature.set_Value(feature.Fields.FindField("OriginY"), oy); feature.set_Value(feature.Fields.FindField("DestX"), dx); feature.set_Value(feature.Fields.FindField("DestY"), dy); feature.set_Value(feature.Fields.FindField("Angle"), angle); feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit); break; } case "Circle": { System.Object radius; System.Object disttype; System.Object distunit; System.Object centerx; System.Object centery; graphic.Attributes.TryGetValue("radius", out radius); graphic.Attributes.TryGetValue("distanceunit", out distunit); graphic.Attributes.TryGetValue("disttype", out disttype); graphic.Attributes.TryGetValue("centerx", out centerx); graphic.Attributes.TryGetValue("centery", out centery); feature.set_Value(feature.Fields.FindField("Distance"), radius); feature.set_Value(feature.Fields.FindField("DistUnit"), distunit); feature.set_Value(feature.Fields.FindField("DistType"), disttype); feature.set_Value(feature.Fields.FindField("CenterX"), centerx); feature.set_Value(feature.Fields.FindField("CenterY"), centery); break; } case "Ellipse": { System.Object majoraxis; System.Object minoraxis; System.Object angle; System.Object distunit; System.Object centerx; System.Object centery; System.Object angleunit; graphic.Attributes.TryGetValue("majoraxis", out majoraxis); graphic.Attributes.TryGetValue("minoraxis", out minoraxis); graphic.Attributes.TryGetValue("azimuth", out angle); graphic.Attributes.TryGetValue("distanceunit", out distunit); graphic.Attributes.TryGetValue("centerx", out centerx); graphic.Attributes.TryGetValue("centery", out centery); graphic.Attributes.TryGetValue("angleunit", out angleunit); feature.set_Value(feature.Fields.FindField("MajAxis"), majoraxis); feature.set_Value(feature.Fields.FindField("MinAxis"), minoraxis); feature.set_Value(feature.Fields.FindField("DistUnit"), distunit); feature.set_Value(feature.Fields.FindField("Angle"), angle); feature.set_Value(feature.Fields.FindField("CenterX"), centerx); feature.set_Value(feature.Fields.FindField("CenterY"), centery); feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit); break; } case "RangeRing": { System.Object rings; System.Object distance; System.Object radials; System.Object distunit; System.Object centerx; System.Object centery; graphic.Attributes.TryGetValue("rings", out rings); graphic.Attributes.TryGetValue("distance", out distance); graphic.Attributes.TryGetValue("radials", out radials); graphic.Attributes.TryGetValue("distanceunit", out distunit); graphic.Attributes.TryGetValue("centerx", out centerx); graphic.Attributes.TryGetValue("centery", out centery); feature.set_Value(feature.Fields.FindField("Rings"), rings); feature.set_Value(feature.Fields.FindField("Distance"), distance); feature.set_Value(feature.Fields.FindField("Radials"), radials); feature.set_Value(feature.Fields.FindField("DistUnit"), distunit); feature.set_Value(feature.Fields.FindField("CenterX"), centerx); feature.set_Value(feature.Fields.FindField("CenterY"), centery); break; } } feature.Store(); } IFeatureLayer featurelayer = null; featurelayer = new FeatureLayerClass(); featurelayer.FeatureClass = featClass; featurelayer.Name = featClass.AliasName; System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace); workspace = null; GC.Collect(); return(featClass); } catch (Exception ex) { return(featClass); } } }
private void BtConnectarClick(object sender, EventArgs e) { Ws = null; _pPropSet = new PropertySetClass(); _pSdeFact = new SdeWorkspaceFactory(); _pPropSet.SetProperty("SERVER", txtBoxServer.Text); _pPropSet.SetProperty("INSTANCE", txtBoxInstancia.Text); _pPropSet.SetProperty("DATABASE", txtBoxDB.Text); _pPropSet.SetProperty("USER", txtBoxUsuario.Text); _pPropSet.SetProperty("PASSWORD", txtBoxPassword.Text); _pPropSet.SetProperty("VERSION", txtBoxVersao.Text); try { System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; Ws = _pSdeFact.Open(_pPropSet, 0); treeViewDatasets.Nodes.Clear(); treeViewTables.Nodes.Clear(); if (chkBoxFeatueClass.Checked) _enumDsFeatureClasses = Ws.get_DatasetNames(esriDatasetType.esriDTFeatureDataset); if (chkBoxTables.Checked) _enumDsTables = Ws.get_DatasetNames(esriDatasetType.esriDTTable); if (_enumDsFeatureClasses != null) { IDatasetName dsName = _enumDsFeatureClasses.Next(); while (dsName != null) { treeViewDatasets.Nodes.Add(dsName.Name); dsName = _enumDsFeatureClasses.Next(); } } if (_enumDsTables != null) { IDatasetName dsName = _enumDsTables.Next(); while (dsName != null) { treeViewTables.Nodes.Add(dsName.Name); dsName = _enumDsTables.Next(); } } btGerar.Enabled = true; } catch (Exception ex) { MessageBox.Show("Impossible to Connect" + "\n\n" + ex.Message); } finally { System.Windows.Forms.Cursor.Current = Cursors.Default; } }
//根据连接字符串获取工作空间 //此处连接字符串是固定格式的连接串 Server|Service|Database|User|Password|Version private static IWorkspace GetWorkSpacefromConninfo(string conninfostr, int type) { //added by chulili 20111109 添加保护 if (conninfostr == "") { return(null); } if (type < 0) { return(null); } //end added by chulili 20111109 int index1 = conninfostr.IndexOf("|"); int index2 = conninfostr.IndexOf("|", index1 + 1); int index3 = conninfostr.IndexOf("|", index2 + 1); int index4 = conninfostr.IndexOf("|", index3 + 1); int index5 = conninfostr.IndexOf("|", index4 + 1); int index6 = conninfostr.IndexOf("|", index5 + 1); IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pWSFact = null; string sServer = ""; string sService = ""; string sDatabase = ""; string sUser = ""; string sPassword = ""; string strVersion = ""; switch (type) { case 1: //mdb pWSFact = new AccessWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 2: //gdb pWSFact = new FileGDBWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 3: //sde pWSFact = new SdeWorkspaceFactoryClass(); sServer = conninfostr.Substring(0, index1); sService = conninfostr.Substring(index1 + 1, index2 - index1 - 1); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); sUser = conninfostr.Substring(index3 + 1, index4 - index3 - 1); sPassword = conninfostr.Substring(index4 + 1, index5 - index4 - 1); strVersion = conninfostr.Substring(index5 + 1, index6 - index5 - 1); break; } pPropSet.SetProperty("SERVER", sServer); pPropSet.SetProperty("INSTANCE", sService); pPropSet.SetProperty("DATABASE", sDatabase); pPropSet.SetProperty("USER", sUser); pPropSet.SetProperty("PASSWORD", sPassword); pPropSet.SetProperty("VERSION", strVersion); try { IWorkspace pWorkspace = pWSFact.Open(pPropSet, 0); return(pWorkspace); } catch { return(null); } }
//Refresh the statistics for all tracking layers in the map //The AMSWorkspaceFactory provides easy access to query the statistics for every layer at once private void RefreshAllStatistics() { try { object oNames, oValues; string[] sNames; if (m_amsWorkspaceFactory == null) { m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass(); } //Get the AMS Workspace Factory Statistics interface ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory; //Get the message rates for all the tracking connections in the map IPropertySet psMessageRates = temporalWsfStatistics.AllMessageRates; psMessageRates.GetAllProperties(out oNames, out oValues); sNames = (string[])oNames; object[] oaMessageRates = (object[])oValues; //Get the feature counts for all the tracking connections in the map IPropertySet psTotalFeatureCounts = temporalWsfStatistics.AllTotalFeatureCounts; psTotalFeatureCounts.GetAllProperties(out oNames, out oValues); object[] oaFeatureCounts = (object[])oValues; //Get the connection status for all the tracking connections in the map IPropertySet psConnectionStatus = temporalWsfStatistics.ConnectionStatus; psConnectionStatus.GetAllProperties(out oNames, out oValues); string[] sConnectionNames = (string[])oNames; object[] oaConnectionStatus = (object[])oValues; Hashtable htConnectionStatus = new Hashtable(sConnectionNames.Length); for (int i = 0; i < sConnectionNames.Length; ++i) { htConnectionStatus.Add(sConnectionNames[i], oaConnectionStatus[i]); } //Get the track counts for all the tracking connections in the map IPropertySet psTrackCounts = temporalWsfStatistics.AllTrackCounts; psTrackCounts.GetAllProperties(out oNames, out oValues); object[] oaTrackCounts = (object[])oValues; //Get the sample sizes for all the tracking connections in the map IPropertySet psSampleSizes = temporalWsfStatistics.AllSampleSizes; psSampleSizes.GetAllProperties(out oNames, out oValues); object[] oaSampleSizes = (object[])oValues; //Clear the existing list view items and repopulate from the collection lvStatistics.BeginUpdate(); lvStatistics.Items.Clear(); //Create list view items from statistics' IPropertySets for (int i = 0; i < sNames.Length; ++i) { ListViewItem lvItem = new ListViewItem(sNames[i]); lvItem.SubItems.Add(Convert.ToString(oaMessageRates[i])); lvItem.SubItems.Add(Convert.ToString(oaFeatureCounts[i])); string sConnName = sNames[i].Split(new Char[] { '/' })[0]; esriWorkspaceConnectionStatus eWCS = (esriWorkspaceConnectionStatus)Convert.ToInt32(htConnectionStatus[sConnName]); lvItem.SubItems.Add(eWCS.ToString()); lvItem.SubItems.Add(Convert.ToString(oaTrackCounts[i])); lvItem.SubItems.Add(Convert.ToString(oaSampleSizes[i])); lvStatistics.Items.Add(lvItem); } lvStatistics.EndUpdate(); } catch (System.Exception ex) { statusBarXY.Text = ex.Message; } }
private bool loadGeometricNetworkFromPath(string path, ServerLogger logger) { bool result = false; if (true == System.IO.Directory.Exists(path)) { IWorkspaceFactory workspaceFactory = null; IWorkspace workspace = null; IFeatureDataset ftrDs = null; try { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); workspace = workspaceFactory.OpenFromFile(path, 0); IFeatureWorkspace ftrWorkspace = workspace as IFeatureWorkspace; ftrDs = ftrWorkspace.OpenFeatureDataset(this.networkName); IFeatureClassContainer fcContainer = ftrDs as IFeatureClassContainer; IFeatureClass fc = null; for (int i = 0; i < fcContainer.ClassCount; ++i) { fc = fcContainer.get_Class(i); if (esriFeatureType.esriFTSimpleEdge == fc.FeatureType) { this.addEdgeFeatureClass(fc); } else if (esriFeatureType.esriFTSimpleJunction == fc.FeatureType) { this.addJunctionFeatureClass(fc); } } if (this.edgeCount > 0 && this.junctionCount > 0) { INetworkCollection networkCollection = ftrDs as INetworkCollection; if (null != networkCollection && 0 < networkCollection.GeometricNetworkCount) { this.geometricNetwork = networkCollection.GeometricNetwork[0]; result = true; } } } catch (Exception e) { if (null != logger) { logger.LogMessage(ServerLogger.msgType.error, typeof(NetworkHelper).Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, GLC.AO.AOUtilities.ErrorCode, e.Message); } } finally { GLC.AO.AOUtilities.ReleaseCOMObj(ftrDs); GLC.AO.AOUtilities.ReleaseCOMObj(workspace); GLC.AO.AOUtilities.ReleaseCOMObj(workspaceFactory); } } else { if (null != logger) { logger.LogMessage(ServerLogger.msgType.error, typeof(NetworkHelper).Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, GLC.AO.AOUtilities.ErrorCode, "File geodatabase does not exist at " + path); } } return(result); }
//Reset the statistic's message rate for one or all of the layers in the map private void btnResetMsgRate_Click(object sender, EventArgs e) { try { ITemporalLayer temporalLayer = GetSelectedTemporalLayer(); if (temporalLayer == null) { if (m_amsWorkspaceFactory == null) { m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass(); } //Get the AMS Workspace Factory Statistics interface ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory; temporalWsfStatistics.ResetAllMessageRates(); } else { ITemporalFeatureClassStatistics temporalFCStats = (ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass; temporalFCStats.ResetMessageRate(); } } catch (Exception ex) { statusBarXY.Text = ex.Message; } }
static void Main(string[] args) { #region Initialize ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitialize(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion try { // Input database and Mosaic Dataset string MDWorkspaceFolder = @"e:\md\Samples\GetSetKP\RasterSamples.gdb"; string MDName = @"LAC"; // Command line setting of above input if provided. string[] commandLineArgs = Environment.GetCommandLineArgs(); if (commandLineArgs.GetLength(0) > 1) { MDWorkspaceFolder = commandLineArgs[1]; MDName = commandLineArgs[2]; } // Open MD Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory mdWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace mdWorkspace = mdWorkspaceFactory.OpenFromFile(MDWorkspaceFolder, 0); IRasterWorkspaceEx workspaceEx = (IRasterWorkspaceEx)(mdWorkspace); IMosaicDataset mosaicDataset = (IMosaicDataset)workspaceEx.OpenRasterDataset(MDName); // Set Mosaic Dataset item information. SetMosaicDatasetItemInformation(mosaicDataset); // Set Key Property 'DataType' on the Mosaic Dataset to value 'Processed' // The change will be reflected on the 'General' page of the mosaic dataset // properties under the 'Source Type' property. SetKeyProperty((IDataset)mosaicDataset, "DataType", "Processed"); // Set the Product Definition on the Mosaic Dataset to 'NATURAL_COLOR_RGB' // First set the 'BandDefinitionKeyword' key property to natural color RGB. SetKeyProperty((IDataset)mosaicDataset, "BandDefinitionKeyword", "NATURAL_COLOR_RGB"); // Then set band names and wavelengths on the mosaic dataset. SetBandProperties((IDataset)mosaicDataset); // Last and most important, refresh the mosaic dataset so the changes are saved. ((IRasterDataset3)mosaicDataset).Refresh(); #region Shutdown Console.WriteLine("Success."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Shutdown Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }
public IFeatureWorkspace OpenCadWorkspace(string cadPath) { m_workspaceFactory = new CadWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspce = m_workspaceFactory.OpenFromFile(cadPath, 0) as IFeatureWorkspace; return featureWorkspce; }
/// <summary> /// Opens the workspace. /// </summary> /// <param name="sFilePath">The s file path.</param> /// <param name="type">The type.</param> /// <returns>IWorkspace.</returns> public static IWorkspace OpenWorkspace(string sFilePath, DataType type) { IWorkspace result; try { sFilePath = sFilePath.TrimEnd(new char[] { '\\' }); IWorkspaceFactory workspaceFactory = null; if (type <= DataType.sde) { switch (type) { case DataType.shp: workspaceFactory = new ShapefileWorkspaceFactoryClass(); //关闭资源锁定 IWorkspaceFactoryLockControl ipWsFactoryLock = (IWorkspaceFactoryLockControl)workspaceFactory; if (ipWsFactoryLock.SchemaLockingEnabled) { ipWsFactoryLock.DisableSchemaLocking(); } break; case DataType.mdb: workspaceFactory = new AccessWorkspaceFactoryClass(); break; case (DataType)3: break; case DataType.gdb: workspaceFactory = new FileGDBWorkspaceFactoryClass(); break; default: if (type == DataType.sde) { workspaceFactory = new SdeWorkspaceFactoryClass(); } break; } } else if (type != DataType.cad) { if (type != DataType.raster) { if (type == DataType.coverage) { workspaceFactory = new ArcInfoWorkspaceFactoryClass(); } } else { workspaceFactory = new RasterWorkspaceFactoryClass(); } } else { workspaceFactory = new CadWorkspaceFactoryClass(); } result = workspaceFactory.OpenFromFile(sFilePath, 0); } catch { result = null; } return(result); }
public IFeatureWorkspace OpenSHPWorkspace(string shpPath) { m_workspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace featureWorkspce = m_workspaceFactory.OpenFromFile(shpPath, 0) as IFeatureWorkspace; return featureWorkspce; }
/// <summary> /// 连接更新目标数据库,获得工作空间与数据集 /// </summary> /// <param name="DesWorkspace">输出的工作空间</param> /// <returns></returns> private bool GetDBDataset(out IWorkspace DesWorkspace) { IWorkspaceFactory pWorkspaceFactory = null; IPropertySet pPropertySet = new PropertySetClass(); comboBoxEx2.Items.Clear(); try { if (comBoxType.SelectedIndex == 1) //SDE库 { pWorkspaceFactory = new SdeWorkspaceFactoryClass(); pPropertySet.SetProperty("SERVER", txtServer.Text); pPropertySet.SetProperty("INSTANCE", txtInstance.Text); pPropertySet.SetProperty("USER", txtUser.Text); pPropertySet.SetProperty("PASSWORD", txtPassWord.Text); pPropertySet.SetProperty("VERSION", txtVersion.Text); } else if (comBoxType.SelectedIndex == 0) //GDB库 { pWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); } else if (comBoxType.SelectedIndex == 2) //PDB库体 { pWorkspaceFactory = new AccessWorkspaceFactoryClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); } DesWorkspace = pWorkspaceFactory.Open(pPropertySet, 0); if (DesWorkspace == null) { return(false); } IEnumDatasetName pEnumDatasetName = DesWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset); if (pEnumDatasetName == null) { _DesDSName = null; return(true); } IDatasetName pDatasetName = pEnumDatasetName.Next(); while (pDatasetName != null) { comboBoxEx2.Items.Add(pDatasetName.Name); pDatasetName = pEnumDatasetName.Next(); } if (comboBoxEx2.Items.Count > 0) { comboBoxEx2.SelectedIndex = 0; } return(true); } catch (Exception e) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(e, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(e, null, DateTime.Now); } //******************************************************************** DesWorkspace = null; return(false); } }
private void TestConnectSDEData(string server, string instance,string database, string user, string password, string version) { try { m_pWorkspaceFactory = new SdeWorkspaceFactoryClass(); m_pPropSet = new PropertySetClass(); //���ãӣģ�����������Ϣ m_pPropSet.SetProperty("SERVER", server); m_pPropSet.SetProperty("INSTANCE", instance); m_pPropSet.SetProperty("Database", database); m_pPropSet.SetProperty("User", user); m_pPropSet.SetProperty("password", password); m_pPropSet.SetProperty("version", version); m_pWorkspace = m_pWorkspaceFactory.Open(m_pPropSet, 0); m_pFeatureWorkspace = m_pWorkspace as IFeatureWorkspace; ///////////////////////////////////////////////////////// IEnumDatasetName pEnumDSName = m_pWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset); IDatasetName pSDEDsName = pEnumDSName.Next(); treeView1.Nodes.Clear(); TreeNode node1; while (pSDEDsName != null) { node1=treeView1.Nodes.Add(pSDEDsName.Name); LoadAllFeatClass(node1,pSDEDsName.Name ); pSDEDsName = pEnumDSName.Next(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void TestThumbnailBuilder(string rasterTypeName, string rasterTypeProductFilter, string rasterTypeProductName, string dataSource, string dataSourceFilter, string fgdbParentFolder, bool saveToArt, string customTypeFilePath, bool clearGdbDirectory) { try { string[] rasterProductNames = rasterTypeProductName.Split(';'); string nameString = rasterTypeName.Replace(" ", "") + rasterTypeProductFilter.Replace(" ", "") + rasterProductNames[0].Replace(" ", ""); #region Directory Declarations string fgdbName = nameString + ".gdb"; string fgdbDir = fgdbParentFolder + "\\" + fgdbName; string MosaicDatasetName = nameString + "MD"; #endregion #region Global Declarations IMosaicDataset theMosaicDataset = null; IMosaicDatasetOperation theMosaicDatasetOperation = null; IMosaicWorkspaceExtensionHelper mosaicExtHelper = null; IMosaicWorkspaceExtension mosaicExt = null; #endregion #region Create File GDB Console.WriteLine("Creating File GDB: " + fgdbName); if (clearGdbDirectory) { try { Console.WriteLine("Emptying Gdb folder."); System.IO.Directory.Delete(fgdbParentFolder, true); System.IO.Directory.CreateDirectory(fgdbParentFolder); } catch (System.IO.IOException EX) { Console.WriteLine(EX.Message); return; } } // Create a File Gdb Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); FgdbFactory.Create(fgdbParentFolder, fgdbName, null, 0); #endregion #region Create Mosaic Dataset try { Console.WriteLine("Create Mosaic Dataset: " + MosaicDatasetName); // Setup workspaces. IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace fgdbWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0); // Create Srs ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference mosaicSrs = spatialrefFactory.CreateProjectedCoordinateSystem( (int)(esriSRProjCSType.esriSRProjCS_World_Mercator)); // Create the mosaic dataset creation parameters object. ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass(); // Create the mosaic workspace extension helper class. mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass(); // Find the right extension from the workspace. mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace); // Use the extension to create a new mosaic dataset, supplying the // spatial reference and the creation parameters object created above. theMosaicDataset = mosaicExt.CreateMosaicDataset(MosaicDatasetName, mosaicSrs, creationPars, ""); theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset); } catch (Exception exc) { Console.WriteLine("Error: Failed to create Mosaic Dataset : {0}.", MosaicDatasetName + " " + exc.Message); return; } #endregion #region Create Custom Raster Type Console.WriteLine("Preparing Raster Type"); // Create a Raster Type Name object. IRasterTypeName theRasterTypeName = new RasterTypeNameClass(); // Assign the name of the Raster Type to the name object. // The Name field accepts a path to an .art file as well // the name for a built in Raster Type. theRasterTypeName.Name = rasterTypeName; // Use the Open function from the IName interface to get the Raster Type object. IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open()); if (theRasterType == null) { Console.WriteLine("Error:Raster Type not found " + rasterTypeName); return; } #endregion #region Prepare Raster Type // Set the URI Filter on the loaded raster type. if (rasterTypeProductFilter != "") { // Get the supported URI filters from the raster type object using the // raster type properties interface. IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters; IItemURIFilter productFilter = null; for (int i = 0; i < mySuppFilters.Count; ++i) { // Set the desired filter from the supported filters. productFilter = (IItemURIFilter)mySuppFilters.get_Element(i); if (productFilter.Name == rasterTypeProductFilter) { theRasterType.URIFilter = productFilter; } } } // Enable the correct templates in the raster type. bool enableTemplate = false; if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != "")) { // Get the supported item templates from the raster type. IItemTemplateArray templateArray = theRasterType.ItemTemplates; for (int i = 0; i < templateArray.Count; ++i) { // Go through the supported item templates and enable the ones needed. IItemTemplate template = templateArray.get_Element(i); enableTemplate = false; for (int j = 0; j < rasterProductNames.Length; ++j) { if (template.Name == rasterProductNames[j]) { enableTemplate = true; } } if (enableTemplate) { template.Enabled = true; } else { template.Enabled = false; } } } ((IRasterTypeProperties)theRasterType).DataSourceFilter = dataSourceFilter; #endregion #region Save Custom Raster Type if (saveToArt) { IRasterTypeProperties rasterTypeProperties = (IRasterTypeProperties)theRasterType; IRasterTypeEnvironment rasterTypeHelper = new RasterTypeEnvironmentClass(); rasterTypeProperties.Name = customTypeFilePath; IMemoryBlobStream ipBlob = rasterTypeHelper.SaveRasterType(theRasterType); ipBlob.SaveToFile(customTypeFilePath); } #endregion #region Preparing Data Source Crawler Console.WriteLine("Preparing Data Source Crawler"); // Create a new property set to specify crawler properties. IPropertySet crawlerProps = new PropertySetClass(); // Specify a file filter crawlerProps.SetProperty("Filter", dataSourceFilter); // Specify whether to search subdirectories. crawlerProps.SetProperty("Recurse", true); // Specify the source path. crawlerProps.SetProperty("Source", dataSource); // Get the recommended crawler from the raster type based on the specified // properties using the IRasterBuilder interface. // Pass on the Thumbnailtype to the crawler... IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps); #endregion #region Add Rasters try { Console.WriteLine("Adding Rasters"); // Create a AddRaster parameters object. IAddRastersParameters AddRastersArgs = new AddRastersParametersClass(); // Specify the data crawler to be used to crawl the data. AddRastersArgs.Crawler = theCrawler; // Specify the Thumbnail raster type to be used to add the data. AddRastersArgs.RasterType = theRasterType; // Use the mosaic dataset operation interface to add // rasters to the mosaic dataset. theMosaicDatasetOperation.AddRasters(AddRastersArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Add raster Failed." + ex.Message); return; } #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges."); try { // Create a calculate cellsize ranges parameters object. ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass(); // Use the mosaic dataset operation interface to calculate cellsize ranges. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Compute Pixel Size Failed." + ex.Message); return; } #endregion #region Building Boundary Console.WriteLine("Building Boundary"); try { // Create a build boundary parameters object. IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass(); // Set flags that control boundary generation. boundaryArgs.AppendToExistingBoundary = true; // Use the mosaic dataset operation interface to build boundary. theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Build Boundary Failed." + ex.Message); return; } #endregion #region Report Console.WriteLine("Successfully created MD: " + MosaicDatasetName + ". "); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in TestThumbnailBuilder: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Shutting down."); #endregion } }