User Tools

Site Tools


source_code_serviceseditionsample_oledbfeaturesource_cs_121018.zip

Source Code ServicesEditionSample OledbFeatureSource CS 121018.zip

OledbFeatureLayer.cs

 using ThinkGeo.MapSuite.Core;  
 
 namespace OledbFeatureSource  
 {  
     // The FeatureLayer is a wrapper to the FeatureSource and provides all of the drawing specific  
     // methods such as the ZoomLevels and Styles.  As you can see it is just a simple wrapper and the  
     // real work is already done for you in the FeatureLayer base class.  
     public class OledbFeatureLayer : FeatureLayer  
     {  
         OledbFeatureSource oledbFeatureSource;  
 
         // It is important for compatability that you always have a default constructor that  
         // takes no parameters.  This constructor will just chain to the more complex one.  
         public OledbFeatureLayer()  
             : this(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty)  
         { }  
 
         // We have provided another constructor that has all of the parameters we need for the FeatureSource  
         // to work.  
         public OledbFeatureLayer(string tableName, string idColumnName, string wellKnownTestColumnName, string boundaryUpperLeftXColumnName, string boundaryUpperLeftYColumnName, string boundaryLowerRightXColumnName, string boundaryLowerRightYColumnName, string connectionString)  
             : base()  
         {  
             oledbFeatureSource = new OledbFeatureSource();  
             this.FeatureSource = oledbFeatureSource;  
 
             TableName = tableName;  
             IdColumnName = idColumnName;  
             WellKnownTextColumnName = wellKnownTestColumnName;  
 
             BoundaryUpperLeftXColumnName = boundaryUpperLeftXColumnName;  
             BoundaryUpperLeftYColumnName = boundaryUpperLeftYColumnName;  
             BoundaryLowerRightXColumnName = boundaryLowerRightXColumnName;  
             BoundaryLowerRightYColumnName = boundaryLowerRightYColumnName;  
 
             ConnectionString = connectionString;  
         }  
 
         // The next dozen lines are all of the properties we need.  It is good form to always match  
         // the parameters in your constructors with properties of the exact same name.  
         public string ConnectionString  
         {  
             get { return oledbFeatureSource.ConnectionString; }  
             set { oledbFeatureSource.ConnectionString = value; }  
         }  
 
         public string TableName  
         {  
             get { return oledbFeatureSource.TableName; }  
             set { oledbFeatureSource.TableName = value; }  
         }  
 
         public string IdColumnName  
         {  
             get { return oledbFeatureSource.IdColumnName; }  
             set { oledbFeatureSource.IdColumnName = value; }  
         }  
 
         public string WellKnownTextColumnName  
         {  
             get { return oledbFeatureSource.WellKnownTextColumnName; }  
             set { oledbFeatureSource.WellKnownTextColumnName = value; }  
         }  
 
         public string BoundaryUpperLeftXColumnName  
         {  
             get { return oledbFeatureSource.BoundaryUpperLeftXColumnName; }  
             set { oledbFeatureSource.BoundaryUpperLeftXColumnName = value; }  
         }  
 
         public string BoundaryUpperLeftYColumnName  
         {  
             get { return oledbFeatureSource.BoundaryUpperLeftYColumnName; }  
             set { oledbFeatureSource.BoundaryUpperLeftYColumnName = value; }  
         }  
 
         public string BoundaryLowerRightXColumnName  
         {  
             get { return oledbFeatureSource.BoundaryLowerRightXColumnName; }  
             set { oledbFeatureSource.BoundaryLowerRightXColumnName = value; }  
         }  
 
         public string BoundaryLowerRightYColumnName  
         {  
             get { return oledbFeatureSource.BoundaryLowerRightYColumnName; }  
             set { oledbFeatureSource.BoundaryLowerRightYColumnName = value; }  
         }  
     }  
 }  
 

OledbFeatureSource.cs

 using System;  
 using System.Collections.Generic;  
 using System.Collections.ObjectModel;  
 using System.Data.OleDb;  
 using System.Diagnostics;  
 using System.Globalization;  
 using System.IO;  
 using System.Text;  
 using ThinkGeo.MapSuite.Core;  
 
 namespace OledbFeatureSource  
 {  
     public class OledbFeatureSource : FeatureSource  
     {  
         private OleDbConnection connection;  
 
         private string connectionString;  
         private string tableName;  
         private string idColumnName;  
         private string wellKnownBinaryColumnName;  
 
         private string boundaryUpperLeftXColumnName;  
         private string boundaryUpperLeftYColumnName;  
         private string boundaryLowerRightXColumnName;  
         private string boundaryLowerRightYColumnName;  
 
         // It is important for compatability that you always have a default constructor that  
         // takes no parameters.  This constructor will just chain to the more complex one.  
         public OledbFeatureSource()  
             : this(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty)  
         { }  
 
         // We have provided another constructor that has all of the parameters we need for the FeatureSource  
         // to work.  
         public OledbFeatureSource(string tableName, string idColumnName, string wellKnownBinaryColumnName, string boundaryUpperLeftXColumnName, string boundaryUpperLeftYColumnName, string boundaryLowerRightXColumnName, string boundaryLowerRightYColumnName, string connectionString)  
             : base()  
         {  
             TableName = tableName;  
             IdColumnName = idColumnName;  
             WellKnownTextColumnName = wellKnownBinaryColumnName;  
 
             BoundaryUpperLeftXColumnName = boundaryUpperLeftXColumnName;  
             BoundaryUpperLeftYColumnName = boundaryUpperLeftYColumnName;  
             BoundaryLowerRightXColumnName = boundaryLowerRightXColumnName;  
             BoundaryLowerRightYColumnName = boundaryLowerRightYColumnName;  
 
             ConnectionString = connectionString;  
         }  
 
         // The next dozen lines are all of the properties we need.  It is good form to always match  
         // the parameters in your constructors with properties of the exact same name.  
         public string TableName  
         {  
             get { return tableName; }  
             set { tableName = value; }  
         }  
 
         public string ConnectionString  
         {  
             get { return connectionString; }  
             set { connectionString = value; }  
         }  
 
         public string WellKnownTextColumnName  
         {  
             get { return wellKnownBinaryColumnName; }  
             set { wellKnownBinaryColumnName = value; }  
         }  
 
         public string BoundaryUpperLeftXColumnName  
         {  
             get { return boundaryUpperLeftXColumnName; }  
             set { boundaryUpperLeftXColumnName = value; }  
         }  
 
         public string BoundaryUpperLeftYColumnName  
         {  
             get { return boundaryUpperLeftYColumnName; }  
             set { boundaryUpperLeftYColumnName = value; }  
         }  
 
         public string BoundaryLowerRightXColumnName  
         {  
             get { return boundaryLowerRightXColumnName; }  
             set { boundaryLowerRightXColumnName = value; }  
         }  
 
         public string BoundaryLowerRightYColumnName  
         {  
             get { return boundaryLowerRightYColumnName; }  
             set { boundaryLowerRightYColumnName = value; }  
         }  
 
         public string IdColumnName  
         {  
             get { return idColumnName; }  
             set { idColumnName = value; }  
         }  
 
         // Use the OpenCore to initialize your underlying data source.  The concreat Open method will ensure  
         // that if the user calls the Open method multiple times in a row that you only get one call to  
         // OpenCore.  
         protected override void OpenCore()  
         {  
             connection = new OleDbConnection(connectionString);  
             connection.Open();  
         }  
 
         // This proerpty indicates that we implmented editing through the CommitTransactionCore  
         public override bool IsEditable  
         {  
             get  
             {  
                 return true;  
             }  
         }  
 
         // Use the CloseCore to close your underlying data source.  It is important to note that the  
         // CloseCore is not like the Dispose on other objects.  The FeatureSource is meant to be opened  
         // and closed many times durring its lifetime.  Make sure that you clean up any objects that have  
         // unmanaged resources but do not put the object in a state that when Open is called it will fail.  
         // The concreat Close method will ensure that if the user calle the Close multiple times in  
         // a row that you only get one call to CloseCore.  
         protected override void CloseCore()  
         {  
             connection.Close();  
         }  
 
         // Here you need to query all of the features in your data source.  We use this method  
         // as the basis of nearly all other virtual methods.  For example if you choose not to  
         // override the GetCountCore then we will get all the features and count them as the default.  
         // This is ineffecient however it produces the correct results.  
         protected override Collection<Feature> GetAllFeaturesCore(IEnumerable<string> columnNames)  
         {  
             OleDbCommand command = null;  
             OleDbDataReader dataReader = null;  
             Collection<Feature> returnFeatures = new Collection<Feature>();  
 
             // Alays be sure to wrap imporant code that accesses resources that need  
             // to be closed.  In the Finally we will ensure they always get cleaned up.  
             try  
             {  
                 // We need to construct the part of the SQL statement for retuning the  
                 // column data.  We only return the columns asked for byt the columnNames  
                 // parameter of the function.  This ensures we do not get more than we need.  
                 string columnsSQL = string.Empty;  
                 foreach (string columnName in columnNames)  
                 {  
                     columnsSQL += "," + columnName;  
                 }  
 
                 // Here we build up and execute the query string using the columns the users defined in the properties  
                 command = new OleDbCommand("SELECT " + wellKnownBinaryColumnName + ", " + idColumnName + " " + columnsSQL + " FROM " + tableName, connection);  
                 dataReader = command.ExecuteReader();  
 
                 // We now loop though all of the results and build up our features that we need to return.  
                 while (dataReader.Read())  
                 {  
                     // Read the well known binary and create the feature  
                     Feature feature = GetFeatureFromDataReader(dataReader);  
 
                     // This small part populates the column values that were requested.  They are data  
                     // such as columns used for ClassBreakStyles or TextStyles for labeling.  
                     foreach (string columnName in columnNames)  
                     {  
                         if (!IsReservedColumnName(columnName))  
                             feature.ColumnValues.Add(columnName, dataReader[columnName].ToString());  
                     }  
                     returnFeatures.Add(feature);  
                 }  
             }  
             finally  
             {  
                 // Cleanup any of the objects that need to be closed or disposed.  
                 if (command != null) { command.Dispose(); }  
                 if (dataReader != null) { dataReader.Dispose(); }  
             }  
 
             return returnFeatures;  
         }  
 
         // This method extracts the well known binary from the data reader and uses it to create and return a feature  
         private Feature GetFeatureFromDataReader(OleDbDataReader dataReader)  
         {  
             int bufferSize = 1000;  
 
             byte[] buffer = new byte[bufferSize];  
             long startIndex = 0;  
             long numberOfBytes = 0;  
 
             MemoryStream memoryStream = new MemoryStream();  
             BinaryWriter writer = new System.IO.BinaryWriter(memoryStream);  
             try  
             {  
                 do  
                 {  
                     numberOfBytes = dataReader.GetBytes(0, startIndex, buffer, 0, bufferSize);  
                     if (numberOfBytes == 0)  
                         break;  
 
                     writer.Write(buffer, 0, (int)numberOfBytes);  
                     startIndex += numberOfBytes;  
                 } while (true);  
                 writer.Close();  
 
                 Feature feature = new Feature(memoryStream.GetBuffer(), dataReader[idColumnName].ToString());  
 
                 return feature;  
             }  
             finally  
             {  
                 if (writer != null) { writer.Dispose(); }  
                 if (memoryStream != null) { memoryStream.Dispose(); }  
             }  
         }  
 
         // Check if the column passed in is one of the reserved columns we use for store data such as the WKB or the bounding box  
         private bool IsReservedColumnName(string columnName)  
         {  
             return (columnName == idColumnName || columnName == wellKnownBinaryColumnName || columnName == boundaryUpperLeftXColumnName || columnName == boundaryUpperLeftYColumnName || columnName == boundaryLowerRightXColumnName || columnName == boundaryLowerRightYColumnName);  
         }  
 
         // Though this method is not required for creating our new class it is an important one.  
         // This method is used to get only the features inside of the bounding box passed in.  The reason  
         // this is critical is that many other methods on the QueryTools such as Touches, Overlaps, Intersects,  
         // and many others use this method as a first pass filter.  If you do not override this method then  
         // the default code calls the GetAllFeatures and look at each to see if it is in the bounding box.  
         // While this method will produce the correct result it will not perform as well as your custom code.  
         protected override Collection<Feature> GetFeaturesInsideBoundingBoxCore(RectangleShape boundingBox, IEnumerable<string> returningColumnNames)  
         {  
             OleDbCommand command = null;  
             OleDbDataReader dataReader = null;  
             Collection<Feature> returnFeatures = new Collection<Feature>();  
 
             // Alays be sure to wrap imporant code that accesses resources that need  
             // to be closed.  In the Finally we will ensure they always get cleaned up.  
             try  
             {  
                 // We need to construct the part of the SQL statement for retuning the  
                 // column data.  We only return the columns asked for byt the columnNames  
                 // parameter of the function.  This ensures we do not get more than we need.  
                 string columnsSQL = string.Empty;  
                 foreach (string columnName in returningColumnNames)  
                 {  
                     columnsSQL += "," + columnName;  
                 }  
 
                 // Build up the where string based on the bounding box passes in  
                 string whereSql = " (" + boundingBox.UpperLeftPoint.X + " <= " + BoundaryLowerRightXColumnName + ") AND (" + boundingBox.LowerRightPoint.X + " >= " + boundaryUpperLeftXColumnName + ") AND (" + boundingBox.LowerRightPoint.Y + " <= " + boundaryUpperLeftYColumnName + ") AND (" + boundingBox.UpperLeftPoint.Y + " >= " + boundaryLowerRightYColumnName + ") ";  
 
                 // Build the SQL String from the previous parts  
                 string sqlString = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1}, {2}, {3}, {4}, {5} {6} FROM {7} WHERE {8}", wellKnownBinaryColumnName, idColumnName, boundaryUpperLeftXColumnName, boundaryUpperLeftYColumnName, boundaryLowerRightXColumnName, boundaryLowerRightYColumnName, columnsSQL, tableName, whereSql);  
 
                 command = new OleDbCommand(sqlString, connection);  
                 dataReader = command.ExecuteReader();  
 
                 while (dataReader.Read())  
                 {  
                     // Read the well known binary and create the feature  
                     Feature feature = GetFeatureFromDataReader(dataReader);  
 
                     // This small part populates the column values that were requested.  They are data  
                     // such as columns used for ClassBreakStyles or TextStyles for labeling.  
                     foreach (string columnName in returningColumnNames)  
                     {  
                         if (!IsReservedColumnName(columnName))  
                             feature.ColumnValues.Add(columnName, dataReader[columnName].ToString());  
                     }  
                     returnFeatures.Add(feature);  
                 }  
             }  
             finally  
             {  
                 // Cleanup any of the objects that need to be closed or disposed.  
                 if (command != null) { command.Dispose(); }  
                 if (dataReader != null) { dataReader.Dispose(); }  
             }  
 
             Debug.WriteLine(returnFeatures.Count);  
 
             return returnFeatures;  
         }  
 
         // This method returns all of the columns in the data source.  This method is not required however  
         // if it is not overridden then the FeatureSource will not have any columns available to it.  
         // Since having access to the column data is usefull for labeling and such we suggest you override it.  
         protected override Collection<FeatureSourceColumn> GetColumnsCore()  
         {  
             OleDbCommand command = null;  
             OleDbDataReader dataReader = null;  
             Collection<FeatureSourceColumn> returnColumns = new Collection<FeatureSourceColumn>();  
 
             // Alays be sure to wrap imporant code that accesses resources that need  
             // to be closed.  In the Finally we will ensure they always get cleaned up.  
             try  
             {  
                 // Here we have a query that will quickly return nothing.  As strange as it sounds it is a  
                 // good way to get the table structure back without having to return any column data.  
                 command = new OleDbCommand("SELECT * FROM " + tableName + " WHERE 1=2", connection);  
                 dataReader = command.ExecuteReader();  
 
                 // We now loop through and create our column list.  In the FeatureSourceColumn we can  
                 // optionally provide the column type but it is just informational so we didn't code it.  
                 for (int i = 0; i < dataReader.FieldCount; i++)  
                 {  
                     string columnName = dataReader.GetName(i);  
 
                     if (!IsReservedColumnName(columnName))  
                     {  
                         FeatureSourceColumn featureSourceColumn = new FeatureSourceColumn(columnName);  
                         returnColumns.Add(featureSourceColumn);  
                     }  
                 }  
             }  
             finally  
             {  
                 // Cleanup any of the objects that need to be closed or disposed.  
                 if (command != null) { command.Dispose(); }  
                 if (dataReader != null) { dataReader.Dispose(); }  
             }  
 
             return returnColumns;  
         }  
 
         // This is another method that does not need to be overridden but we suggest that you do.  
         // This method gets the cound of all the features in the data source.  If you choose not to  
         // override it then the default will call the GetAllFeatures and count them.  This is not very  
         // effecient so we suggest you override it.  
         protected override int GetCountCore()  
         {  
             OleDbCommand command = null;  
             int count = 0;  
 
             // Alays be sure to wrap imporant code that accesses resources that need  
             // to be closed.  In the Finally we will ensure they always get cleaned up.  
             try  
             {  
                 // Here we do a standard SQL count statement and return the results.  
                 command = new OleDbCommand("SELECT COUNT(*) FROM " + tableName, connection);  
                 count = Convert.ToInt32(command.ExecuteScalar());  
             }  
             finally  
             {  
                 // Cleanup any of the objects that need to be closed or disposed.  
                 if (command != null) { command.Dispose(); }  
             }  
             return count;  
         }  
 
         // We override this to add editing to this feature source.  In this method we are expected  
         // to handle add, edits and deletes to the data source.  We have created seperate helper methods  
         // that encapsulate the various actions.  
         protected override TransactionResult CommitTransactionCore(TransactionBuffer transactions)  
         {  
             TransactionResult transactionResult = new TransactionResult();  
 
             ProcessAddBuffer(transactions.AddBuffer, transactionResult);  
             ProcessDeleteBuffer(transactions.DeleteBuffer, transactionResult);  
             ProcessEditBuffer(transactions.EditBuffer, transactionResult);  
             return transactionResult;  
         }  
 
         private void ProcessAddBuffer(Dictionary<string, Feature> addBuffer, TransactionResult result)  
         {  
             foreach (Feature feature in addBuffer.Values)  
             {  
                 try  
                 {  
                     StringBuilder stringBuilder = new StringBuilder();  
 
                     stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0} ({1},{2},{3},{4},{5},{6}", tableName, idColumnName, wellKnownBinaryColumnName, boundaryUpperLeftXColumnName, boundaryUpperLeftYColumnName, boundaryLowerRightXColumnName, boundaryLowerRightYColumnName));  
 
                     if (feature.ColumnValues != null)  
                     {  
                         foreach (string columnName in feature.ColumnValues.Keys)  
                         {  
                             stringBuilder.Append("," + columnName);  
                         }  
                     }  
 
                     RectangleShape boundingBox = feature.GetBoundingBox();  
 
                     stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, ") VALUES('{0}',@wellKnownBinary,{1},{2},{3},{4}", feature.Id, boundingBox.UpperLeftPoint.X, boundingBox.UpperLeftPoint.Y, boundingBox.LowerRightPoint.X, boundingBox.LowerRightPoint.Y));  
                     if (feature.ColumnValues != null)  
                     {  
                         foreach (string columnName in feature.ColumnValues.Keys)  
                         {  
                             stringBuilder.Append(",'" + feature.ColumnValues[columnName].Replace("'", "") + "'");  
                         }  
                     }  
                     stringBuilder.Append(");");  
 
                     string sqlStatement = stringBuilder.ToString();  
 
                     OleDbCommand command = null;  
 
                     try  
                     {  
                         command = new OleDbCommand(sqlStatement, connection);  
                         OleDbParameter parameter = command.Parameters.Add("@wellKnownBinary", OleDbType.Binary);  
                         parameter.Value = feature.WellKnownBinary;  
                         command.ExecuteNonQuery();  
                     }  
                     finally  
                     {  
                         // Cleanup any of the objects that need to be closed or disposed.  
                         if (command != null) { command.Dispose(); }  
                     };  
                     result.TotalSuccessCount++;  
                 }  
                 catch (Exception e)  
                 {  
                     result.FailureReasons.Add(feature.Id, e.Message);  
                     result.TotalFailureCount++;  
                 }  
             }  
         }  
 
         private void ProcessDeleteBuffer(Collection<string> deleteBuffer, TransactionResult transactionResult)  
         {  
             OleDbCommand command = null;  
 
             if (deleteBuffer.Count == 0)  
             {  
                 return;  
             }  
 
             StringBuilder stringBuilder = new StringBuilder();  
             stringBuilder.Append("DELETE FROM " + tableName + " WHERE ");  
             stringBuilder.Append(idColumnName + "='" + deleteBuffer[0] + "'");  
 
             for (int i = 1; i < deleteBuffer.Count; i++)  
             {  
                 stringBuilder.Append(" OR " + idColumnName + "='" + deleteBuffer[i] + "'");  
             }  
             stringBuilder.Append(";");  
 
             string sqlStatement = stringBuilder.ToString();  
 
             int count = 0;  
 
             try  
             {  
                 // Here we do a standard SQL count statement and return the results.  
                 command = new OleDbCommand(sqlStatement, connection);  
                 count = Convert.ToInt32(command.ExecuteScalar());  
             }  
             finally  
             {  
                 // Cleanup any of the objects that need to be closed or disposed.  
                 if (command != null) { command.Dispose(); }  
                 transactionResult.TotalSuccessCount += count;  
             }  
         }  
 
         private void ProcessEditBuffer(Dictionary<string, Feature> editBuffer, TransactionResult transactionResult)  
         {  
             foreach (string id in editBuffer.Keys)  
             {  
                 try  
                 {  
                     Feature feature = editBuffer[id];  
                     StringBuilder stringBuilder = new StringBuilder();  
 
                     RectangleShape boundingBox = feature.GetBoundingBox();  
                     stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "UPDATE {0} SET WellKnownBinary = @wellKnownBinary,{1} = {2},{3} = {4},{5} = {6},{7} = {8} ",  
                         tableName,  
                         boundaryUpperLeftXColumnName, boundingBox.UpperLeftPoint.X,  
                         boundaryUpperLeftYColumnName, boundingBox.UpperLeftPoint.Y,  
                         boundaryLowerRightXColumnName, boundingBox.LowerRightPoint.X,  
                         boundaryLowerRightYColumnName, boundingBox.LowerRightPoint.Y  
                         ));  
                     if (feature.ColumnValues != null)  
                     {  
                         foreach (string columnName in feature.ColumnValues.Keys)  
                         {  
                             if (String.Compare(columnName, idColumnName, true, CultureInfo.InvariantCulture) == 0)  
                             {  
                                 stringBuilder.Append("," + columnName + "='" + feature.Id + "'");  
                             }  
                             else  
                             {  
                                 stringBuilder.Append("," + columnName + "='" + feature.ColumnValues[columnName] + "'");  
                             }  
                         }  
                     }  
                     stringBuilder.Append(" WHERE " + idColumnName + "='" + id + "'");  
                     stringBuilder.Append(";");  
 
                     string sqlStatement = stringBuilder.ToString();  
 
                     OleDbCommand command = null;  
 
                     try  
                     {  
                         command = new OleDbCommand(sqlStatement, connection);  
                         OleDbParameter parameter = command.Parameters.Add("@wellKnownBinary", OleDbType.Binary);  
                         parameter.Value = feature.WellKnownBinary;  
                         command.ExecuteNonQuery();  
                     }  
                     finally  
                     {  
                         // Cleanup any of the objects that need to be closed or disposed.  
                         if (command != null) { command.Dispose(); }  
                     }  
                     transactionResult.TotalSuccessCount++;  
                 }  
                 catch (Exception e)  
                 {  
                     transactionResult.FailureReasons.Add(id, e.Message);  
                     transactionResult.TotalFailureCount++;  
                 }  
             }  
         }  
     }  
 }  
 

Program.cs

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Windows.Forms;  
 
 namespace OledbFeatureSource  
 {  
     static class Program  
     {  
         /// <summary>  
         /// The main entry point for the application.  
         /// </summary>  
         [STAThread]  
         static void Main()  
         {  
             Application.EnableVisualStyles();  
             Application.SetCompatibleTextRenderingDefault(false);  
             Application.Run(new TestForm());  
         }  
     }  
 }  
 

TestForm.cs

 using System;  
 using System.Collections.ObjectModel;  
 using System.Drawing;  
 using System.Windows.Forms;  
 using ThinkGeo.MapSuite.Core;  
 
 namespace OledbFeatureSource  
 {  
     public partial class TestForm : Form  
     {  
         private MapEngine mapEngine = new MapEngine();  
         private Bitmap bitmap;  
 
         public TestForm()  
         {  
             InitializeComponent();  
             BaseShape.GeometryLibrary = GeometryLibrary.Managed;  
             Feature.GeometryLibrary = GeometryLibrary.Managed;  
         }  
 
         private void TestForm_Load(object sender, System.EventArgs e)  
         {  
             // Set the current extent and background color  
             mapEngine.CurrentExtent = ExtentHelper.GetDrawingExtent(new RectangleShape(-180.0, 83.0, 180.0, -90.0), picMap.Width, picMap.Height);  
             mapEngine.BackgroundFillBrush = new GeoSolidBrush(GeoColor.GeographicColors.DeepOcean);  
 
             // Display OledbFeatureLayer  
             string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\data\Countries.mdb;User Id=admin;Password=;";  
             OledbFeatureLayer countriesLayer = new OledbFeatureLayer("Countries", "ID", "WellKnownBinary", "BoundaryUpperLeftX", "BoundaryUpperLeftY", "BoundaryLowerRightX", "BoundaryLowerRightY", connectionString);  
             countriesLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;  
             countriesLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.City1("CountryName");  
             countriesLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle.FittingPolygon = true;  
             countriesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;  
 
             // Add the new layer to the MapEngine  
             mapEngine.StaticLayers.Add("CountriesLayer", countriesLayer);  
             DrawImage();  
         }  
 
         private void btnEdit_Click(object sender, System.EventArgs e)  
         {  
             FeatureLayer countriesLayer = (FeatureLayer)mapEngine.StaticLayers["CountriesLayer"];  
             if (Validator.CheckMdbHasRecords((OledbFeatureSource)countriesLayer.FeatureSource))  
             {  
                 // Edit the shape itself  
                 countriesLayer.Open();  
                 Collection<Feature> features = countriesLayer.FeatureSource.GetAllFeatures(ReturningColumnsType.AllColumns);  
                 countriesLayer.EditTools.BeginTransaction();  
 
                 foreach (Feature feature in features)  
                 {  
                     // Change the country name  
                     feature.ColumnValues["CountryName"] += "(Modified)";  
                     // Scale down the country  
                     BaseShape baseShape = feature.GetShape();  
                     baseShape.ScaleTo(0.5);  
                     feature.WellKnownBinary = baseShape.GetWellKnownBinary();  
 
                     countriesLayer.EditTools.Update(feature);  
                 }  
                 countriesLayer.EditTools.CommitTransaction();  
                 countriesLayer.Close();  
 
                 DrawImage();  
             }  
             else  
             {  
                 MessageBox.Show("No records in the specified .mdb file, please check it.");  
             }  
         }  
 
         private void btnDelete_Click(object sender, System.EventArgs e)  
         {  
             FeatureLayer countriesLayer = (FeatureLayer)mapEngine.StaticLayers["CountriesLayer"];  
 
             countriesLayer.Open();  
             countriesLayer.EditTools.BeginTransaction();  
             Collection<Feature> features = countriesLayer.FeatureSource.GetAllFeatures(ReturningColumnsType.AllColumns);  
             foreach (Feature feature in features)  
             {  
                 countriesLayer.EditTools.Delete(feature.Id);  
             }  
             countriesLayer.EditTools.CommitTransaction();  
             countriesLayer.Close();  
 
             DrawImage();  
         }  
 
         private void btnImport_Click(object sender, System.EventArgs e)  
         {  
             FeatureLayer countriesLayer = (FeatureLayer)mapEngine.StaticLayers["CountriesLayer"];  
             if (!Validator.CheckMdbHasRecords((OledbFeatureSource)countriesLayer.FeatureSource))  
             {  
                 // Import the records of shape file into .mdb file  
                 string shpPath = @"..\..\Data\Countries02.shp";  
                 ShapeFileFeatureSource worldShpFeatureSource = new ShapeFileFeatureSource(shpPath, ShapeFileReadWriteMode.ReadOnly);  
                 worldShpFeatureSource.Open();  
                 Collection<Feature> features = worldShpFeatureSource.GetAllFeatures(ReturningColumnsType.AllColumns);  
                 worldShpFeatureSource.Close();  
 
                 countriesLayer.Open();  
                 countriesLayer.EditTools.BeginTransaction();  
                 foreach (Feature feature in features)  
                 {  
                     string countryName = feature.ColumnValues["CNTRY_NAME"].ToString();  
                     feature.ColumnValues.Clear();  
                     feature.ColumnValues.Add("CountryName", countryName);  
                     countriesLayer.EditTools.Add(feature);  
                 }  
                 countriesLayer.EditTools.CommitTransaction();  
                 countriesLayer.Close();  
             }  
             else  
             {  
                 MessageBox.Show("Failed to import the data, please make sure there is't any records in the specified .mdb file.");  
             }  
             DrawImage();  
         }  
 
         private void btnGetCount_Click(object sender, EventArgs e)  
         {  
             FeatureLayer countriesLayer = (FeatureLayer)mapEngine.StaticLayers["CountriesLayer"];  
             countriesLayer.Open();  
             int featureCount = countriesLayer.FeatureSource.GetCount();  
             MessageBox.Show("Number of Countries: " + featureCount, "Get Count");  
             countriesLayer.Close();  
         }  
 
         private void btnClose_Click(object sender, EventArgs e)  
         {  
             this.Close();  
         }  
 
         private void DrawImage()  
         {  
             if (bitmap != null)  
             {  
                 bitmap.Dispose();  
             }  
             bitmap = new Bitmap(picMap.Width, picMap.Height);  
             mapEngine.OpenAllLayers();  
             mapEngine.DrawStaticLayers(bitmap, GeographyUnit.DecimalDegree);  
             mapEngine.CloseAllLayers();  
             picMap.Image = bitmap;  
         }  
 
         private void toolBar_ButtonClick(object sender, ToolBarButtonClickEventArgs e)  
         {  
             switch (e.Button.Tag.ToString())  
             {  
                 case "Zoom In":  
                     mapEngine.CurrentExtent.ScaleDown(50);  
                     break;  
                 case "Zoom Out":  
                     mapEngine.CurrentExtent.ScaleUp(50);  
                     break;  
                 case "Full Extent":  
                     mapEngine.CurrentExtent = ExtentHelper.GetDrawingExtent(new RectangleShape(-180.0, 83.0, 180.0, -90.0), picMap.Width, picMap.Height);  
                     break;  
                 case "Pan Left":  
                     mapEngine.CurrentExtent = ExtentHelper.Pan(mapEngine.CurrentExtent, PanDirection.Left, 40);  
                     break;  
                 case "Pan Right":  
                     mapEngine.CurrentExtent = ExtentHelper.Pan(mapEngine.CurrentExtent, PanDirection.Right, 40);  
                     break;  
                 case "Pan Up":  
                     mapEngine.CurrentExtent = ExtentHelper.Pan(mapEngine.CurrentExtent, PanDirection.Up, 20);  
                     break;  
                 case "Pan Down":  
                     mapEngine.CurrentExtent = ExtentHelper.Pan(mapEngine.CurrentExtent, PanDirection.Down, 20);  
                     break;  
                 default:  
                     break;  
             }  
             DrawImage();  
         }  
     }  
 }  
 

Validator.cs

 using ThinkGeo.MapSuite.Core;  
 
 namespace OledbFeatureSource  
 {  
     internal static class Validator  
     {  
         internal static bool CheckMdbHasRecords(OledbFeatureSource featureSource)  
         {  
             bool result = false;  
 
             featureSource.Open();  
             int featureCount = featureSource.GetCount();  
             featureSource.Close();  
             if (featureCount > 0)  
             {  
                 result = true;  
             }  
             else  
             {  
                 result = false;  
             }  
             return result;  
         }  
     }  
 }  
 
source_code_serviceseditionsample_oledbfeaturesource_cs_121018.zip.txt · Last modified: 2015/09/09 03:19 by admin