/// <summary> /// 创建工作空间(地理数据库) /// </summary> /// <param name="workspaceFactory">工作空间工厂</param> /// <param name="parentDirectory">工作空间所在目录</param> /// <param name="strWorkspaceName">工作空间名称</param> /// <returns></returns> public static IWorkspace NewWorkspace(IWorkspaceFactory workspaceFactory, string parentDirectory, string strWorkspaceName) { IWorkspaceName workspaceName = workspaceFactory.Create(parentDirectory, strWorkspaceName, null, 0); IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); Marshal.ReleaseComObject(workspaceFactory); return(workspace); }
public IWorkspace CreateInMemoryWorkspace() { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.InMemoryWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspaceName workspaceName = workspaceFactory.Create("", "MyWorkspace", null, 0); IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); return(workspace); }
public IWorkspace CreateFileGDB(string fgdbParentFolder, string fgdbName) { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspaceName wkname = FgdbFactory.Create(fgdbParentFolder, fgdbName, null, 0); IName name = wkname as IName; IWorkspace wk = name.Open() as IWorkspace; return(wk); }
/// <summary> /// crea un file geodatabase /// </summary> /// <param name="path">percorso e nome del geodatabase</param> /// <param name="nameWithExtension">nome del file con estensione</param> /// <returns>IWorkspace del file geodatabase</returns> internal static IWorkspace CreateFileGdbWorkspace(string path, string nameWithExtension) { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(path, nameWithExtension, null, 0); IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); return(workspace); }
public static IWorkspaceName GetInMemoryWorkspaceName(string name) { if (null != inMemoryWorkspaceFactory && false == string.IsNullOrWhiteSpace(name)) { return(inMemoryWorkspaceFactory.Create(null, name, null, 0)); } else { return(null); } }
/// <summary> /// Create a Personal Geodatabase given the name and parent folder. /// </summary> /// <param name="gdbParentFolder">Folder to create the new gdb in.</param> /// <param name="gdbName">Name of the gdb to be created.</param> /// <returns>Workspace reference to the new geodatabase.</returns> public static IWorkspace CreateAccessWorkspace(string gdbParentFolder, string gdbName) { // Instantiate an Access workspace factory and create a personal geodatabase. // The Create method returns a workspace object. Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory) Activator.CreateInstance(factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(gdbParentFolder, gdbName, null, 0); // Cast the workspace name object to the IName interface and open the workspace. IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); return(workspace); }
/// <summary> /// Creates a FileGeodatabase. /// </summary> /// <param name="path"></param> /// <param name="gdbName"></param> /// <returns></returns> public static IWorkspace CreateFileGdbWorkspace(String path, string gdbName) { // Instantiate a file geodatabase workspace factory and create a file geodatabase. // The Create method returns a workspace name object. Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(path, gdbName, null, 0); // Cast the workspace name object to the IName interface and open the workspace. IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); return(workspace); }
/// <summary> /// create a memory workspace /// </summary> /// <returns>memory workspace</returns> public static IWorkspace CreateInMemoryWorkspace() { // Create an in-memory workspace factory. Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.InMemoryWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory) Activator.CreateInstance(factoryType); // Create an in-memory workspace. IWorkspaceName workspaceName = workspaceFactory.Create(string.Empty, "memoryWorkspace", null, 0); // Cast for IName and open a reference to the in-memory workspace through the name object. Guid.NewGuid().ToString() IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); return(workspace); }
public static IWorkspace CreateGDB(string WStype, string name, string path) { IWorkspace workspace = null; Type factoryType = Type.GetTypeFromProgID(WStype); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); if (workspaceFactory.IsWorkspace(path + name)) { workspace = workspaceFactory.OpenFromFile(path + name, 0); } else { IWorkspaceName workspaceName = workspaceFactory.Create(path, name, null, 0); IName pName = (IName)workspaceName; workspace = (IWorkspace)pName.Open(); } return(workspace); }
public void CreateAccessWorkspace(string path) { try { // Instantiate an Access workspace factory and create a personal geodatabase. // The Create method returns a workspace name object. Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.AccessWorkspaceFactory"); string guid = Guid.NewGuid().ToString(); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(path, guid + ".mdb", null, 0); // Cast the workspace name object to the IName interface and open the workspace. IName name = (IName)workspaceName; IWorkspace workspace = (IWorkspace)name.Open(); WorkspacePath = path + guid + ".mdb"; PersonalWorkspace = workspace; } catch (Exception ex) { } }
public bool CheckOut(IWorkspace source, string dir, string dbname, string template, IPolygon area, string taskName, string dept) { m_message = ""; //检查文件是否已经存在 string mdbpath = dir + @"\" + dbname + ".mdb"; bool isExist = File.Exists(mdbpath); if (isExist) { File.Delete(mdbpath); } Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(dir, dbname, null, 0); IWorkspace workspace = workspaceFactory.OpenFromFile(mdbpath, 0); //导入库结构 IGdbXmlImport importer = new GdbImporterClass(); IEnumNameMapping mapping = null; bool isConflict = false; isConflict = importer.GenerateNameMapping(template, workspace, out mapping); importer.ImportWorkspace(template, mapping, workspace, true); IDataset ds = workspace as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace source_ws = source as IFeatureWorkspace; IFeatureWorkspace target_ws = workspace as IFeatureWorkspace; IWorkspaceEdit wse = target_ws as IWorkspaceEdit; foreach (string fcname in fcNames) { IWorkspace2 source_ws2 = source_ws as IWorkspace2; if (!source_ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, fcname)) { continue; } IFeatureClass source_fc = source_ws.OpenFeatureClass(fcname); IFeatureClass target_fc = target_ws.OpenFeatureClass(fcname); AddSyncFields(target_fc); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = area as IGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; wse.StartEditing(false); IFeatureCursor target_cur = target_fc.Insert(true); IFeatureBuffer buffer = target_fc.CreateFeatureBuffer(); IFeatureCursor source_cur = source_fc.Search(filter, true); IFeature source_fea = source_cur.NextFeature(); while (source_fea != null) { buffer.set_Value(target_fc.FindField("SyncID"), source_fea.OID); for (int i = 0; i < source_fc.Fields.FieldCount; i++) { IField source_field = source_fc.Fields.get_Field(i); if (source_field.Name != source_fc.OIDFieldName) { int target_field_index = target_fc.FindField(source_field.Name); if (target_field_index != -1) { object source_value = source_fea.get_Value(source_fc.FindField(source_field.Name)); buffer.set_Value(target_field_index, source_value); } } } target_cur.InsertFeature(buffer); source_fea = source_cur.NextFeature(); } target_cur.Flush(); wse.StopEditing(true); } IFeatureClass log_fc = source_ws.OpenFeatureClass("TaskLog"); IWorkspaceEdit source_wse = source_ws as IWorkspaceEdit; source_wse.StartEditing(false); IFeature log_fea = log_fc.CreateFeature(); log_fea.set_Value(log_fc.FindField("CheckOutDate"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); log_fea.set_Value(log_fc.FindField("TaskName"), taskName); log_fea.set_Value(log_fc.FindField("Dept"), dept); log_fea.set_Value(log_fc.FindField("Status"), Task.TaskManager.CHECKOUT_STATUS); log_fea.Shape = area; log_fea.Store(); source_wse.StopEditing(true); return(true); }
private void btnOK_Click(object sender, EventArgs e) { bool resultErr = false; if (txtCtrlPtPath.Text == "" || txtSrcPath.Text == "" || txtToPath.Text == "") { return; } if (lstFC.CheckedItems.Count == 0) { return; } try { initTransformation(); } catch (Exception ex) { ErrorHandle.ShowFrmErrorHandle("提示", ex.Message); return; } if (rdoMDB.Checked)//personal GDB { try { pWF = new AccessWorkspaceFactoryClass(); string path = txtToPath.Text.Substring(0, txtToPath.Text.LastIndexOf("\\") + 1); string name = txtToPath.Text.Substring(txtToPath.Text.LastIndexOf("\\") + 1); IWorkspaceName pToWN = pWF.Create(path, name, null, 0); if (pToWN == null) { return; } pToWorkspace = pWF.OpenFromFile(txtToPath.Text, 0); } catch { } if (pToWorkspace == null) { return; } } else if (rdoGDB.Checked)//file GDB { pWF = new FileGDBWorkspaceFactoryClass(); string path = txtToPath.Text.Substring(0, txtToPath.Text.LastIndexOf("\\") + 1); string name = txtToPath.Text.Substring(txtToPath.Text.LastIndexOf("\\") + 1); IWorkspaceName pToWN = pWF.Create(path, name, null, 0); if (pToWN == null) { return; } try { pToWorkspace = pWF.OpenFromFile(txtToPath.Text, 0); } catch { } if (pToWorkspace == null) { return; } } else if (rdoSHP.Checked)//shp { pWF = new ShapefileWorkspaceFactoryClass(); try { pToWorkspace = pWF.OpenFromFile(txtToPath.Text, 0); } catch { } if (pToWorkspace == null) { return; } } try { toPath = txtToPath.Text;//保存目标路径,因转换结束要清空目标文本框防止用户再次点击转换,查看日志需要知道目标路径 pbCoorTran.Value = 0; pbCoorTran.Minimum = 0; pbCoorTran.Maximum = lstFC.CheckedItems.Count; pbCoorTran.Step = 1; pbCoorTran.Visible = true; start = DateTime.Now;//开始时间 Application.DoEvents(); pResult = new Dictionary <string, string>(); IWorkspaceEdit pWorkSpaceEdit = pToWorkspace as IWorkspaceEdit; pWorkSpaceEdit.StartEditing(false); foreach (ListViewItem lvi in lstFC.CheckedItems) { IDataset pToD = null; try { IFeatureClass pFc = (pSrcWorkspace as IFeatureWorkspace).OpenFeatureClass(lvi.Text); IDataset pD = pFc as IDataset; lblRMS.Text = "正在转换要素类" + pD.Name + "..."; Application.DoEvents(); IFeatureClass pToFC = TransFeatures.CreateFeatureClass(pD.Name, pFc, pToWorkspace, null, null, pFc.ShapeType); pToD = pToFC as IDataset; TransFeatures.CopyFeatureAndTran(pFc.Search(null, false), pToFC, pTransformation); IGeoDataset pGD = pToD as IGeoDataset; IGeoDatasetSchemaEdit pGDS = pGD as IGeoDatasetSchemaEdit; if (pSR != null && pGDS.CanAlterSpatialReference) { pGDS.AlterSpatialReference(pSR);//定义空间参考 } pResult.Add(pToD.Name, "转换成功"); pbCoorTran.PerformStep(); } catch (Exception ex) { pResult.Add(pToD.Name, "转换失败/" + ex.Message); if (ex.Message == "The coordinates or measures are out of bounds.") { pResult[pToD.Name] = "转换失败/控制点坐标超出该要素类坐标域边界"; } pToD.Delete(); resultErr = true; } //if (rdoSHP.Checked) // pD.Copy(pD.Name, pToWorkspace); //else // CopyPasteGDBData.CopyPasteGeodatabaseData(pSrcWorkspace, pToWorkspace, pD.Name, esriDatasetType.esriDTFeatureClass); }//foreach #region 20110815前代码 //IWorkspaceEdit pWorkSpaceEdit = pToWorkspace as IWorkspaceEdit; //pWorkSpaceEdit.StartEditing(false); //IEnumDataset enumDS = pToWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass); //IDataset pDs = enumDS.Next(); //while (pDs != null) //{ // lblRMS.Text = "正在转换要素类"+pDs.Name+"..."; // try // { // IFeatureClass pFC = pDs as IFeatureClass; // coordTransfermation(pFC, pTransformation); // pResult.Add(pDs.Name, "转换成功"); // } // catch (Exception ex) // { // pResult.Add(pDs.Name, "转换失败/" + ex.Message); // if (ex.Message == "The coordinates or measures are out of bounds.") // pResult[pDs.Name] = "转换失败/控制点坐标超出该要素类坐标域边界"; // pDs.Delete(); // resultErr = true; // } // finally // { // pbCoorTran.PerformStep(); // pDs = enumDS.Next(); // } //} //IEnumDataset enumDS1 = pToWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset); //IDataset pDs1 = enumDS1.Next(); //while (pDs1 != null) //{ // lblRMS.Text = "正在转换要素集" + pDs1.Name + "..."; // IEnumDataset pED = pDs1.Subsets; // IDataset pDs2 = pED.Next(); // while (pDs2 != null) // { // try // { // IFeatureClass pFC2 = pDs2 as IFeatureClass; // coordTransfermation(pFC2, pTransformation); // pResult.Add(pDs2.Name, "转换成功"); // } // catch (Exception ex) // { // pResult.Add(pDs2.Name, "转换失败/" + ex.Message); // if (ex.Message == "The coordinates or measures are out of bounds.") // pResult[pDs2.Name] = "转换失败/控制点坐标超出该要素类坐标域边界"; // pDs2.Delete(); // resultErr = true; // } // finally // { // pDs2 = pED.Next(); // } // } // pbCoorTran.PerformStep(); // pDs1 = enumDS1.Next(); //} //} //foreach (KeyValuePair<string, string> kvp in pResult) //{ // ListViewItem lvi = lstViewResult.Items.Add(kvp.Key); // lvi.SubItems.Add(kvp.Value); //} //lstViewResult.Refresh(); //this.Height = 529; #endregion pWorkSpaceEdit.StopEditing(true); } catch (Exception ex) { MessageBox.Show("坐标转换失败!" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { //vProgress.Close(); pToWorkspace = null; txtToPath.Text = ""; pbCoorTran.Visible = false; } if (!resultErr) { lblRMS.Text = "转换成功!"; } else { lblRMS.Text = "转换结束!但是部分要素转换失败,请查看日志。"; } stop = DateTime.Now;//结束时间 }
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 } }
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); } }
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); } } }