Cursor/*PERMUDA*/Proxy(
    ICursor/*PERMUDA*//*PERMUDA FROMSUFFIX*/ from
)
{
    NonNull.CheckParameter( from, "from" );
    this.From = from;
}
 public Hand(Color color)
 {
     cursorImage[(int)InputStatus.CURSOR] = getColoredImage(Resources.DiscImage, color);
     cursorImage[(int)InputStatus.UNKNOWN] = getColoredImage(Resources.DiscImage, color);
     cursorImage[(int)InputStatus.TOUCHED] = getColoredImage(Resources.DiscImageFilled, color);
     cursor = CursorFactory.getCursor(cursorImage[(int)status]);
 }
Пример #3
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.HomeScreen);
            listView = FindViewById<ListView>(Resource.Id.List);

            string[] projection = new string[] { VegetableProvider.InterfaceConsts.Id, VegetableProvider.InterfaceConsts.Name };
            string[] fromColumns = new string[] { VegetableProvider.InterfaceConsts.Name };
            int[] toControlIds = new int[] { Android.Resource.Id.Text1 };

            // ManagedQuery is deprecated in Honeycomb (3.0, API11)
            cursor = ManagedQuery(VegetableProvider.CONTENT_URI, projection, null, null, null);
            
            // ContentResolver requires you to close the query yourself
            //cursor = ContentResolver.Query(VegetableProvider.CONTENT_URI, projection, null, null, null);
            //StartManagingCursor(cursor);

            // CursorLoader introduced in Honeycomb (3.0, API11)
            var loader = new CursorLoader(this,
                VegetableProvider.CONTENT_URI, projection, null, null, null);
            cursor = (ICursor)loader.LoadInBackground();

            // create a SimpleCursorAdapter
            adapter = new SimpleCursorAdapter(this, Android.Resource.Layout.SimpleListItem1, cursor, 
                fromColumns, toControlIds);

            listView.Adapter = adapter;
            
            listView.ItemClick += OnListItemClick;
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);

            SetContentView (Resource.Layout.Main);

            MyList = FindViewById<ListView> (Resource.Id.myListView);

            // create the cursor
            vdb = new SuperheroesDatabase(this);
            cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM Superheroes", null);
            StartManagingCursor(cursor);

            // which columns map to which layout controls
            string[] fromColumns = new string[] { "name" };
            int[] toControlIds = new int [] {Android.Resource.Id.Text1};

            // use a SimpleCursorAdapter
            MyList.Adapter = new SimpleCursorAdapter(this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIds);

            //			if (MyList.SelectedItem.ToString () != null) {
            //				selected = MyList.SelectedItem.ToString ();
            //			}

            MyList.ItemClick += OnListItemClick;
        }
Пример #5
0
        public ActiveArea(string name, int x, int y, int width, int height)
			: base(name, x, y, width, height)
		{
            Enabled = true;
			fIsDepressed = false;
			fTracking = false;
			fCursor = null ; // BUGBUG - Cursor.Arrow;
        }
Пример #6
0
		public override ICharSequence ConvertToStringFormatted (ICursor cursor)
		{
			var convertMe = new string[1];
			convertMe [0] = cursor.GetString (COLUMN_DISPLAY_NAME);

			var converted = CharSequence.ArrayFromStringArray (convertMe);
			return converted [0];
		}
Пример #7
0
        public StatementResult(ICursor cursor, ConstraintInfo[] constraints)
        {
            if (cursor == null)
                throw new ArgumentNullException("cursor");

            Cursor = cursor;
            Constraints = constraints;
            Type = StatementResultType.CursorRef;
        }
 private Note mapNote(ICursor cursor)
 {
     return new Note
     {
         Id = cursor.GetInt(0),
         Title = cursor.GetString(1),
         Contents = cursor.GetString(2)
     };
 }
Пример #9
0
 public static Transaction createTransaction(ICursor cursor)
 {
     Transaction purchase = new Transaction();
     purchase.orderId = cursor.GetString(0);
     purchase.productId = cursor.GetString(1);
     purchase.purchaseState = (PurchaseState)Enum.Parse(typeof(PurchaseState), cursor.GetInt(2).ToString());
     purchase.purchaseTime = cursor.GetLong(3);
     purchase.developerPayload = cursor.GetString(4);
     return purchase;
 }
Пример #10
0
 protected override void LoadContent()
 {
     debugTexture = myGame.Content.Load<Texture2D>("Textures\\DebugColor");
     cursorR = new KinectAbsoluteScreenspaceCursor(myGame.Services.GetService(typeof(KinectService)) as KinectService, KinectAbsoluteScreenspaceCursor.Handedness.Left, myGame);
     cursorL = new KinectAbsoluteScreenspaceCursor(myGame.Services.GetService(typeof(KinectService)) as KinectService, KinectAbsoluteScreenspaceCursor.Handedness.Right, myGame);
     cursorM = new MouseCursor();
     player = new BackgroundSubtractedPlayer(myGame);
     myGame.Components.Add(player);
     base.LoadContent();
 }
Пример #11
0
 public override View NewView(Context context, ICursor cursor, ViewGroup viewGroup)
 {
     View itemLayout = inflater.Inflate(Resource.Layout.sample_contacts_activity_item, viewGroup, false);
     itemLayout.Tag = new ViewHolder
     {
         text1 = itemLayout.FindViewById<TextView>(Android.Resource.Id.Text1),
         icon = itemLayout.FindViewById<QuickContactBadge>(Android.Resource.Id.Icon)
     };
     return itemLayout;
 }
Пример #12
0
        public NoteListCursorAdapter(Context context, int layout, ICursor c, string[] from, int[] to, int selectedIndex)
            : base(context, layout, c, from, to)
        {
            this.layout = layout;
            this.context = context;
            this.selectedIndex = selectedIndex;

            localeDateFormat = DateFormat.getDateFormat(context);
            localeTimeFormat = DateFormat.getTimeFormat(context);
        }
Пример #13
0
        public override View NewView(Context context, ICursor cursor, ViewGroup parent)
        {
            var grid = (GridView)parent;

            var imageView = new ImageView(context);
            imageView.LayoutParameters = new GridView.LayoutParams(grid.ColumnWidth, grid.ColumnWidth);
            imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
            imageView.SetPadding(8, 8, 8, 8);

            return imageView;
        }
Пример #14
0
            public override void BindView(View view, Context context, ICursor cursor)
            {
                string type = cursor.GetString(BlocksQuery.BLOCK_TYPE);
                string blockId = cursor.GetString(BlocksQuery.BLOCK_ID);
                string blockTitle = cursor.GetString(BlocksQuery.BLOCK_TITLE);
                long blockStart = cursor.GetLong(BlocksQuery.BLOCK_START);
                long blockEnd = cursor.GetLong(BlocksQuery.BLOCK_END);
                string blockMeta = cursor.GetString(BlocksQuery.BLOCK_META);

                //TODO: Fix it
                //String blockTimeString = UIUtils.FormatBlockTimeString(blockStart, blockEnd,
                //    context);
            }
Пример #15
0
        public void Create_Database()
        {
            HashSet<String> tableNameHashSet = new HashSet<String> ();
            tableNameHashSet.Add (WeatherContractOpen.LocationEntryOpen.TABLE_NAME);
            tableNameHashSet.Add (WeatherContractOpen.WeatherEntryOpen.TABLE_NAME);

            context.DeleteDatabase (WeatherDbOpenHelper.DATABASE_NAME);
            SQLiteDatabase db = new WeatherDbOpenHelper (
                                    this.context).WritableDatabase;
            Assert.AreEqual (true, db.IsOpen);

            // have we created the tables we want?
            c = db.RawQuery ("SELECT name FROM sqlite_master WHERE type='table'", null);

            Assert.IsTrue (c.MoveToFirst (), "Error: This means that the database has not been created correctly");

            // verify that the tables have been created
            do {
                tableNameHashSet.Remove (c.GetString (0));
            } while(c.MoveToNext ());

            // if this fails, it means that your database doesn't contain both the location entry
            // and weather entry tables
            Assert.IsTrue (tableNameHashSet.Count == 0, "Error: Your database was created without both the location entry and weather entry tables");

            // now, do our tables contain the correct columns?
            c = db.RawQuery ("PRAGMA table_info(" + WeatherContractOpen.LocationEntryOpen.TABLE_NAME + ")",
                null);

            Assert.IsTrue (c.MoveToFirst (), "Error: This means that we were unable to query the database for table information.");

            // Build a HashSet of all of the column names we want to look for
            HashSet<String> locationColumnHashSet = new HashSet<String> ();
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen._ID);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_CITY_NAME);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_COORD_LAT);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_COORD_LONG);
            locationColumnHashSet.Add (WeatherContractOpen.LocationEntryOpen.COLUMN_LOCATION_SETTING);

            int columnNameIndex = c.GetColumnIndex ("name");
            do {
                String columnName = c.GetString (columnNameIndex);
                locationColumnHashSet.Remove (columnName);
            } while(c.MoveToNext ());

            // if this fails, it means that your database doesn't contain all of the required location
            // entry columns
            Assert.IsTrue (locationColumnHashSet.Count == 0, "Error: The database doesn't contain all of the required location entry columns");
            db.Close ();
        }
Пример #16
0
        private static void AssertRC(int expected, ICursor cursor, string message = "")
        {
            var actual = 0;
            while (cursor.MoveNext())
                actual++;

            var ok = (expected == actual);
            Console.WriteLine(ok ? "SUCCES {2} expected {0}, actual {1}" : "FAILED {2} expected {0}, actual {1}",
                              expected, actual, message);

            Total++;
            if (ok)
                Succeeded++;
        }
 private static List<Transaction> cursorToList(ICursor c)
 {
     List<Transaction> transactions = new List<Transaction>();
     if (c != null)
     {
         while (c.MoveToNext())
         {
             Transaction purchase = BillingDB.createTransaction(c);
             transactions.Add(purchase);
         }
         c.Close();
     }
     return transactions;
 }
Пример #18
0
        public override View NewView(Context context, ICursor cursor, ViewGroup parent)
        {
            var gv = parent as GridView;

            int px = Utils.GetPixFromGridView(context, parent as GridView);
            px = gv.ColumnWidth;

            var imageView = new ImageView(context);
            imageView.LayoutParameters = new GridView.LayoutParams(px, px);
            imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
            imageView.SetPadding(8, 8, 8, 8);

            return imageView;
        }
Пример #19
0
		public void ReloadFromArguments (Bundle arguments)
		{
			// Teardown from previous arguments
			if (mCursor != null) {
				Activity.StopManagingCursor (mCursor);
				mCursor = null;
			}
	
			mCheckedPosition = -1;
			ListAdapter = null;
	
			mHandler.CancelOperation (SearchQuery._TOKEN);
			mHandler.CancelOperation (SessionsQuery._TOKEN);
			mHandler.CancelOperation (TracksQuery._TOKEN);
	
			// Load new arguments
			Intent intent = BaseActivity.FragmentArgumentsToIntent (arguments);
			Uri sessionsUri = intent.Data;
			int sessionQueryToken;
	
			if (sessionsUri == null) {
				return;
			}
	
			String[] projection;
			if (!ScheduleContract.Sessions.IsSearchUri (sessionsUri)) {
				mAdapter = new SessionsAdapter (Activity, this);
				projection = SessionsQuery.PROJECTION;
				sessionQueryToken = SessionsQuery._TOKEN;
	
			} else {
				mAdapter = new SearchAdapter (Activity, this);
				projection = SearchQuery.PROJECTION;
				sessionQueryToken = SearchQuery._TOKEN;
			}
	
			ListAdapter = mAdapter;
	
			// Start background query to load sessions
			mHandler.StartQuery (sessionQueryToken, null, sessionsUri, projection, null, null, ScheduleContract.Sessions.DEFAULT_SORT);
	
			// If caller launched us with specific track hint, pass it along when
			// launching session details. Also start a query to load the track info.
			mTrackUri = (Android.Net.Uri)intent.GetParcelableExtra (SessionDetailFragment.EXTRA_TRACK);
			mTrackUri = null;
			if (mTrackUri != null) {
				mHandler.StartQuery (TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION);
			}
		}
Пример #20
0
 public void DeleteNote(ICursor cursor)
 {
     new AlertDialog.Builder(_context)
         .SetTitle(_context.Resources.GetString(Resource.String.delete_title))
         .SetMessage(Resource.String.delete_message)
         .SetPositiveButton(Resource.String.yes_button, (object sender, DialogClickEventArgs e) =>
         {
             Uri noteUri = ContentUris.WithAppendedId(WikiNote.Notes.ALL_NOTES_URI,
                 cursor.GetInt(0));
             _context.ContentResolver.Delete(noteUri, null, null);
             _context.SetResult(Result.Ok);
             _context.Finish();
         })
         .SetNegativeButton(Resource.String.no_button, delegate { }).Show();
 }
        public IEnumerable RunQuery(string server, string database, string port, string query)
        {
            if (database == string.Empty)
                throw new QueryValidationException("You must specify a non-empty database name");

            if (query == string.Empty)
                throw new QueryValidationException("You must specify a non-empty query");

            _db = new Mongo(string.Format("Server={0}:{1}", server, port));
            IList<DictionaryBase> documents = new List<DictionaryBase>();

            try
            {
                _db.Connect();
            }
            catch (SocketException ex)
            {
                throw new UnknownServerException(string.Format("Unknown server: {0}:{1}", server, port), ex);
            }

            string[] queryParts = query.Split(':');
            string collection = queryParts[0];

            if (queryParts.Length > 1)
            {
                Document spec = new Document();
                string where = queryParts[1];
                const string LIMIT_TEXT = " limit ";
                int limitIndex = where.IndexOf(LIMIT_TEXT);
                int limit = 0;

                if (limitIndex > -1)
                {
                    string limitText;

                    if (int.TryParse(where.Substring(limitIndex + LIMIT_TEXT.Length), out limit))
                        where = where.Substring(0, limitIndex);
                }

                spec.Append("$where", new Code(where));
                _cursor = _db[database][collection].Find(spec, limit, 0);
            }
            else
                _cursor = _db[database][collection].FindAll();

            return _cursor.Documents;
            //Document d = db[database].SendCommand("db.test.find();");
        }
Пример #22
0
        public override void BindView(View view, Context context, ICursor cursor)
        {
            Uri contactUri = ContactsContract.Contacts.GetLookupUri(
                cursor.GetLong(SampleContactsActivity.ContactsQuery.Id),
                cursor.GetString(SampleContactsActivity.ContactsQuery.LookupKey));

            ViewHolder holder = (ViewHolder)view.Tag;
            holder.text1.Text = cursor.GetString(SampleContactsActivity.ContactsQuery.DisplayName);
            holder.icon.AssignContactUri(contactUri);

            Picasso.With(context)
                   .Load(contactUri)
                   .Placeholder(Resource.Drawable.contact_picture_placeholder)
                   .Tag(context)
                   .Into(holder.icon);
        }
Пример #23
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.HomeScreen);
            listView = FindViewById<ListView>(Resource.Id.List);

            // create the cursor
            vdb = new VegetableDatabase(this);
            cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM vegetables", null);
            StartManagingCursor(cursor);

            // create the CursorAdapter
            listView.Adapter = (IListAdapter)new HomeScreenCursorAdapter(this, cursor, false);

            listView.ItemClick += OnListItemClick;
        }
Пример #24
0
        public override void BindView(View view, Context context, ICursor cursor)
        {
            int image_column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id);
            var imageView = (ImageView)view;
            int id = cursor.GetInt(image_column_index);

            Bitmap bm = MediaStore.Images.Thumbnails.GetThumbnail(context.ContentResolver, id, ThumbnailKind.MicroKind, null);

            BitmapDrawable drawable = imageView.Drawable as BitmapDrawable;

            if (drawable != null && drawable.Bitmap != null)
            {
                drawable.Bitmap.Recycle();
            }

            imageView.SetImageBitmap(bm);
        }
Пример #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Intent intent = Intent;
            Uri uri = null;
            String query = null;

            if (Intent.ActionSearch.Equals(intent.Action))
            {
                query = intent.GetStringExtra(SearchManager.Query);
            }
            else if (bundle != null)
            {
                query = bundle.GetString(SearchManager.Query);
            }

            if (query != null && query.Length > 0)
            {
                uri = Uri.WithAppendedPath(WikiNote.Notes.SEARCH_URI, Uri.Encode(query));
            }

            if (uri == null)
            {
                // somehow we got called w/o a query so fall back to a reasonable
                // default (all notes)
                uri = WikiNote.Notes.ALL_NOTES_URI;
            }

            // Do the query
            ICursor c = ManagedQuery(uri, WikiNote.WIKI_LISTNOTES_PROJECTION, null, null,
                        WikiNote.Notes.BY_TITLE_SORT_ORDER);
            _cursor = c;

            _helper = new WikiActivityHelper(this);

            // Bind the results of the search into the list
            ListAdapter = new SimpleCursorAdapter(
                                      this,
                                      Android.Resource.Layout.SimpleListItem1,
                                      _cursor,
                                      new String[] { WikiNote.Notes.TITLE },
                                      new int[] { Android.Resource.Id.Text1 });
            SetDefaultKeyMode(DefaultKey.Shortcut);
        }
        public Quaternion GetModifiedRotation(ICursor cursor)
        {
            Quaternion rotation;

            Vector3 forward = UseGazeBasedNormal ? -GazeManager.Instance.GazeNormal : HostTransform.rotation * CursorNormal;

            // Determine the cursor forward
            if (forward.magnitude > 0)
            {
                rotation = Quaternion.LookRotation(forward, Vector3.up);
            }
            else
            {
                rotation = cursor.Rotation;
            }

            return rotation;
        }
        public Vector3 GetModifiedPosition(ICursor cursor)
        {
            Vector3 position;

            if (SnapCursor)
            {
                // Snap if the targeted object has a cursor modifier that supports snapping
                position = HostTransform.position +
                           HostTransform.TransformVector(CursorOffset);
            }
            else
            {
                // Else, consider the modifiers on the cursor modifier, but don't snap
                position = GazeManager.Instance.HitPosition + HostTransform.TransformVector(CursorOffset);
            }

            return position;
        }
Пример #28
0
 /// <summary>
 /// Create an intent to start the WikiNoteEditor using the current title
 /// and body information (if any).
 /// </summary>
 public void EditNote(string mNoteName, ICursor cursor)
 {
     // This intent could use the android.intent.action.EDIT for a wiki note
     // to invoke, but instead I wanted to demonstrate the mechanism for invoking
     // an intent on a known class within the same application directly. Note
     // also that the title and body of the note to edit are passed in using the extras bundle.
     Intent i = new Intent(_context, typeof(WikiNoteEditor));
     i.PutExtra(WikiNote.Notes.TITLE, mNoteName);
     String body;
     if (cursor != null)
     {
         body = cursor.GetString(cursor.GetColumnIndexOrThrow(WikiNote.Notes.BODY));
     }
     else
     {
         body = string.Empty;
     }
     i.PutExtra(WikiNote.Notes.BODY, body);
     _context.StartActivityForResult(i, ACTIVITY_EDIT);
 }
Пример #29
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.HomeScreen);
            listView = FindViewById<ListView>(Resource.Id.List);

            // create the cursor
            vdb = new VegetableDatabase(this);
            cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM vegetables", null);
            StartManagingCursor(cursor);

            // which columns map to which layout controls
            string[] fromColumns = new string[] { "name" };
            int[] toControlIds = new int [] {Android.Resource.Id.Text1};

            // use a SimpleCursorAdapter
            listView.Adapter = new SimpleCursorAdapter(this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIds);

            listView.ItemClick += OnListItemClick;
        }
Пример #30
0
        public override void BindView(View view, Context context, ICursor cursor)
        {
            //var textView = view.FindViewById<TextView>(Android.Resource.Id.Text1);
            //textView.Text = cursor.GetString(1); // 'name' is column 1

            int image_column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Id);
            var imageView = (ImageView)view;
            int id = cursor.GetInt(image_column_index);

            Bitmap bm = MediaStore.Images.Thumbnails.GetThumbnail(context.ContentResolver, id, ThumbnailKind.MicroKind, null);
            //Bitmap bm = MediaStore.Images.Media.GetBitmap(context.ContentResolver, id);

            BitmapDrawable drawable = imageView.Drawable as BitmapDrawable;

            if (drawable != null && drawable.Bitmap != null)
            {
                //drawable.Bitmap.Dispose();
                drawable.Bitmap.Recycle();
            }

            imageView.SetImageBitmap(bm);
        }
Пример #31
0
        public override List <IFreeDocument> TryFindEntities(string tableName,
                                                             IDictionary <string, object> search
                                                             , Type type = null, int count = -1, DBSearchStrategy searchStrategy = DBSearchStrategy.Contains)
        {
            if (type == null)
            {
                type = typeof(FreeDocument);
            }
            if (IsUseable == false)
            {
                return(new List <IFreeDocument>());
            }
            IMongoCollection <Document> collection = DB.GetCollection <Document>(tableName);

            var querydoc = new Document();

            foreach (var r in search)
            {
                querydoc.Add(r.Key, r.Value);
            }
            if (count != 1)
            {
                ICursor <Document> document = collection.Find(querydoc);
                if (document == null)
                {
                    return(new List <IFreeDocument>());
                }
                var results = new List <IFreeDocument>();

                foreach (Document item in document.Documents)
                {
                    if (count > 0)
                    {
                        count--;
                    }
                    if (count == 0)
                    {
                        break;
                    }
                    var result = Activator.CreateInstance(type) as IFreeDocument;

                    result.DictDeserialize(item);
                    results.Add(result);
                }


                return(results);
            }
            else
            {
                var document = collection.FindOne(querydoc);
                if (document == null)
                {
                    return(new List <IFreeDocument>());
                }
                var results = new List <IFreeDocument>();


                var result = Activator.CreateInstance(type) as IFreeDocument;

                result.DictDeserialize(document);
                results.Add(result);
                return(results);
            }
        }
Пример #32
0
        private void 坐标检查ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DBHelper.VEC_TABLE == null || DBHelper.RAS_TABLE == null)
            {
                MessageBox.Show("还未初始化");
                return;
            }
            IName  vec_Name  = DBHelper.VEC_TABLE as IName;
            IName  ras_Name  = DBHelper.RAS_TABLE as IName;
            ITable vec_table = vec_Name.Open() as ITable;
            ITable ras_table = ras_Name.Open() as ITable;

            DataTable pTable = new DataTable();
            //设置自增列
            DataColumn autoIncrease = new DataColumn("序号", typeof(int));

            autoIncrease.AutoIncrement     = true;
            autoIncrease.AutoIncrementStep = 1;
            autoIncrease.AutoIncrementSeed = 1;
            //添加字段
            pTable.Columns.Add(autoIncrease);
            pTable.Columns.Add("Name", typeof(String));
            pTable.Columns.Add("Message", typeof(String));

            String tempName = null;//该变量用来记录NAME字段的值
            //vec_Table
            ICursor vec_Cursor = vec_table.Search(null, false);
            IRow    vec_Rrow   = vec_Cursor.NextRow();

            while (vec_Rrow != null)
            {
                DataRow pRow = pTable.NewRow();
                //string[] StrRow = new string[pRrow.Fields.FieldCount];
                for (int i = 0; i < vec_Rrow.Fields.FieldCount; i++)
                {
                    if (vec_Rrow.Fields.get_Field(i).Name.Equals("NAME"))
                    {
                        tempName = vec_Rrow.get_Value(i).ToString();
                    }
                    if (vec_Rrow.Fields.get_Field(i).Name.Equals("COOR"))
                    {
                        if (vec_Rrow.get_Value(i).ToString() == "")
                        {
                            pRow["Name"]    = tempName;
                            pRow["Message"] = "坐标信息有误,没有空间参考信息!";
                        }
                    }
                    //StrRow[i] = pRrow.get_Value(i).ToString();
                }
                //pRow.ItemArray = StrRow;
                pTable.Rows.Add(pRow);
                vec_Rrow = vec_Cursor.NextRow();
            }

            //ras_Table
            ICursor ras_Cursor = ras_table.Search(null, false);
            IRow    ras_Rrow   = ras_Cursor.NextRow();

            while (ras_Rrow != null)
            {
                DataRow pRow = pTable.NewRow();
                //string[] StrRow = new string[pRrow.Fields.FieldCount];
                for (int i = 0; i < ras_Rrow.Fields.FieldCount; i++)
                {
                    if (ras_Rrow.Fields.get_Field(i).Name.Equals("NAME"))
                    {
                        tempName = ras_Rrow.get_Value(i).ToString();
                    }
                    if (ras_Rrow.Fields.get_Field(i).Name.Equals("COOR"))
                    {
                        if (ras_Rrow.get_Value(i).ToString() == "")
                        {
                            pRow["Name"]    = tempName;
                            pRow["Message"] = "坐标信息有误,没有空间参考信息!";
                        }
                    }
                    //StrRow[i] = pRrow.get_Value(i).ToString();
                }
                //pRow.ItemArray = StrRow;
                pTable.Rows.Add(pRow);
                ras_Rrow = ras_Cursor.NextRow();
            }
            //弹出显示框
            CoordinateCheck cc = new CoordinateCheck();

            cc.dataGridView1.DataSource       = pTable;
            cc.dataGridView1.Columns[1].Width = 200;
            cc.dataGridView1.Columns[2].Width = 300;
            cc.Show();
        }
Пример #33
0
 public void InitCursor(ICursor cursor) => cursor.Cursor = 0;
Пример #34
0
 public void OnCursorRemoved(ICursor cursor)
 {
     // no op
 }
Пример #35
0
 /// <summary>
 /// Initializes the given Cursor to the oldest buffer entry that is still available.
 /// </summary>
 /// <param name="cursor">TBD</param>
 public void InitCursor(ICursor cursor) => cursor.Cursor = _readIndex;
Пример #36
0
        public static Dictionary <string, string> CountUniques(ITable table, string fldName)
        {
            int idx = table.Fields.FindField(fldName);

            if (idx == -1)
            {
                throw new Exception(string.Format(
                                        "field {0} not found in {1}",
                                        fldName, ((IDataset)table).Name));
            }
            IQueryFilter qf = new QueryFilterClass();

            qf.AddField(fldName);

            var     outDict = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase);
            ICursor cur     = null;
            IRow    row     = null;

            try
            {
                cur = table.Search(qf, true);
                while ((row = cur.NextRow()) != null)
                {
                    try
                    {
                        string key = row.get_Value(idx) is DBNull ? "<Null>" :
                                     row.get_Value(idx).ToString();
                        if (outDict.ContainsKey(key))
                        {
                            outDict[key] = "";
                        }
                        else
                        {
                            outDict.Add(key, "");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(row);
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = row == null ? "error getting value" :
                             "error getting value for row " + row.OID.ToString();
                throw new Exception(msg, ex);
            }
            finally
            {
                if (cur != null)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cur);
                }
            }

            return(outDict);
        }
Пример #37
0
        /// <summary>
        /// format is "array"(default) or "complex"
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="signal"></param>
        /// <param name="fragment">fragment: "start=t1&end=t2&decimation=2&count=1000" decimation is optional, if end is no bigger then start then return all</param>
        /// <param name="format">format is "array"(default) or "complex" </param>
        /// <returns></returns>
        public async Task <object> GetDataAsync(Signal signal, string fragment, string format)
        {
            //  var waveSig = signal as FixedIntervalWaveSignal<T>;
            var waveSig = signal as FixedIntervalWaveSignal;

            if (waveSig == null)
            {
                throw new Exception(ErrorMessages.NotValidSignalError);
            }
            WaveFragment frag = null;

            try
            {
                frag = WaveFragment.Parse(waveSig, fragment);
            }
            catch (Exception)
            {
                throw new Exception("Fragment parse error!");
            }

            var startPoint = (long)Math.Ceiling((frag.Start - waveSig.StartTime) / waveSig.SampleInterval);
            var count      = (long)Math.Floor((frag.End - frag.Start) / waveSig.SampleInterval / frag.DecimationFactor) + 1;
            //   Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")+ "  getCursor");
            ICursor <T> cursor = await myStorageEngine.GetCursorAsync <T>(waveSig.Id, new List <long> {
                startPoint
            }, new List <long> {
                count
            }, new List <long> {
                frag.DecimationFactor
            });

            List <T> resultArray = new List <T>();

            //   Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "   getData");
            //防止读时越界 review cursor 目前一次只能读1000个点?
            while (cursor.LeftPoint > 1000)
            {
                resultArray.AddRange(await cursor.Read(1000));
            }
            if (cursor.LeftPoint > 0)
            {
                resultArray.AddRange(await cursor.Read(cursor.LeftPoint));
            }
            //   Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + "   readFinish");
            if (format == "complex")
            {
                return(new FixedIntervalWaveComplex <T>
                {
                    Title = waveSig.Path,
                    Start = startPoint * waveSig.SampleInterval + waveSig.StartTime,
                    End = waveSig.StartTime + ((count - 1) * frag.DecimationFactor + startPoint) * waveSig.SampleInterval,
                    Count = count,
                    Data = resultArray,
                    DecimatedSampleInterval = waveSig.SampleInterval * frag.DecimationFactor,
                    OrignalSampleInterval = waveSig.SampleInterval,
                    DecimationFactor = frag.DecimationFactor,
                    StartIndex = startPoint,
                    Unit = waveSig.Unit
                });
            }
            else if (format == "point")
            {
                var points = new List <SignalPoint <T> >();
                //添加中间详细点
                double x = frag.Start;
                foreach (var data in resultArray)
                {
                    points.Add(new SignalPoint <T>(x, data));
                    x += waveSig.SampleInterval * frag.DecimationFactor;
                }
                return(points);
            }
            else
            {
                return(resultArray);
            }
        }
Пример #38
0
 private void m_pDataTable_ColumnChanged(object sender, DataColumnChangeEventArgs e)
 {
     if (this.m_InEditing && this.m_CanDo)
     {
         object[] itemArray = e.Row.ItemArray;
         try
         {
             IRow           row;
             int            num;
             IField         field;
             int            num2;
             IWorkspaceEdit workspace = (this.m_pTable as IDataset).Workspace as IWorkspaceEdit;
             if (itemArray[0] is DBNull)
             {
                 if (!(this.m_pTable is IFeatureClass))
                 {
                     workspace.StartEditOperation();
                     row = this.m_pTable.CreateRow();
                     num = row.Fields.FindFieldByAliasName(e.Column.ColumnName);
                     if (num != -1)
                     {
                         field = row.Fields.get_Field(num);
                         if (field.Domain is ICodedValueDomain)
                         {
                             for (num2 = 0; num2 < (field.Domain as ICodedValueDomain).CodeCount; num2++)
                             {
                                 if (e.ProposedValue.ToString() ==
                                     (field.Domain as ICodedValueDomain).get_Name(num2))
                                 {
                                     row.set_Value(num, (field.Domain as ICodedValueDomain).get_Value(num2));
                                     break;
                                 }
                             }
                         }
                         else
                         {
                             row.set_Value(num, e.ProposedValue);
                         }
                         row.Store();
                     }
                     workspace.StopEditOperation();
                     this.m_CanDo = false;
                     e.Row[this.m_pTable.OIDFieldName] = row.OID;
                     this.m_CanDo = true;
                 }
             }
             else
             {
                 int          num3        = Convert.ToInt32(itemArray[0]);
                 IQueryFilter queryFilter = new QueryFilterClass
                 {
                     WhereClause = this.m_pTable.OIDFieldName + " = " + num3.ToString()
                 };
                 ICursor o = this.m_pTable.Search(queryFilter, false);
                 row = o.NextRow();
                 if (row != null)
                 {
                     workspace.StartEditOperation();
                     num = row.Fields.FindFieldByAliasName(e.Column.ColumnName);
                     if (num != -1)
                     {
                         field = row.Fields.get_Field(num);
                         if (field.Domain is ICodedValueDomain)
                         {
                             for (num2 = 0; num2 < (field.Domain as ICodedValueDomain).CodeCount; num2++)
                             {
                                 if (e.ProposedValue.ToString() ==
                                     (field.Domain as ICodedValueDomain).get_Name(num2))
                                 {
                                     row.set_Value(num, (field.Domain as ICodedValueDomain).get_Value(num2));
                                     break;
                                 }
                             }
                         }
                         else
                         {
                             row.set_Value(num, e.ProposedValue);
                         }
                     }
                     row.Store();
                     workspace.StopEditOperation();
                 }
                 row = null;
                 ComReleaser.ReleaseCOMObject(o);
                 o = null;
             }
         }
         catch (COMException exception)
         {
             if (exception.ErrorCode == -2147467259)
             {
                 MessageBox.Show("输入数据大于字段长度");
             }
             else
             {
                 MessageBox.Show(exception.Message);
             }
             e.Row.CancelEdit();
         }
         catch (Exception exception2)
         {
             MessageBox.Show(exception2.Message);
             e.Row.CancelEdit();
         }
     }
 }
Пример #39
0
        public bool DeleteByInClause(IWorkspace TheWorkSpace, ITable inTable, IField QueryIntegerField,
                                     List <string> InClauseIDs, bool IsVersioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel)
        {
            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

            IQueryFilter pQF = new QueryFilterClass();

            ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace;
            string     sPref      = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
            string     sSuff      = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);

            ICursor ipCursor = null;
            IRow    pRow     = null;
            //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database)
            //this code assumes that InClauseIDs holds an arraylist of comma separated OIDs with no more than 995 id's per list item
            string sWhereClauseLHS = sPref + QueryIntegerField.Name + sSuff + " in (";

            try
            {
                ITableWrite pTableWr = (ITableWrite)inTable;
                bool        bCont    = true;

                Int32 count = InClauseIDs.Count - 1;
                for (int k = 0; k <= count; k++)
                {
                    pQF.WhereClause = sWhereClauseLHS + InClauseIDs[k] + ")"; //left-hand side of the where clause
                    if (pQF.WhereClause.Contains("()"))
                    {
                        continue;
                    }
                    if (!IsVersioned)
                    {
                        ipCursor = pTableWr.UpdateRows(pQF, false);
                    }
                    else
                    {
                        ipCursor = inTable.Update(pQF, false);
                    }

                    pRow = ipCursor.NextRow();
                    while (pRow != null)
                    {
                        ipCursor.DeleteRow();
                        Marshal.ReleaseComObject(pRow);
                        if (StepProgressor != null)
                        {
                            //Check if the cancel button was pressed. If so, stop process
                            if (TrackCancel != null)
                            {
                                bCont = TrackCancel.Continue();
                            }
                            if (!bCont)
                            {
                                break;
                            }
                            if (StepProgressor.Position < StepProgressor.MaxRange)
                            {
                                StepProgressor.Step();
                            }
                        }
                        pRow = ipCursor.NextRow();
                    }

                    if (!bCont)
                    {
                        AbortEditing(TheWorkSpace);
                        if (ipCursor != null)
                        {
                            Marshal.ReleaseComObject(ipCursor);
                        }
                        if (pRow != null)
                        {
                            Marshal.ReleaseComObject(pRow);
                        }
                        return(false);
                    }
                    Marshal.ReleaseComObject(ipCursor);
                }
                return(true);
            }

            catch (Exception ex)
            {
                if (ipCursor != null)
                {
                    Marshal.ReleaseComObject(ipCursor);
                }
                if (pRow != null)
                {
                    Marshal.ReleaseComObject(pRow);
                }
                MessageBox.Show(Convert.ToString(ex.Message));
                return(false);
            }
        }
Пример #40
0
        internal static IEnumerable <Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources, string[] ids)
        {
            ICursor c = null;

            string column = (rawContacts)
                ? ContactsContract.RawContactsColumns.ContactId
                : ContactsContract.ContactsColumns.LookupKey;

            StringBuilder whereb = new StringBuilder();

            for (int i = 0; i < ids.Length; i++)
            {
                if (i > 0)
                {
                    whereb.Append(" OR ");
                }

                whereb.Append(column);
                whereb.Append("=?");
            }

            int x   = 0;
            var map = new Dictionary <string, Contact>(ids.Length);

            try
            {
                Contact currentContact = null;

                c = content.Query(ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey);
                if (c == null)
                {
                    yield break;
                }

                int idIndex = c.GetColumnIndex(column);
                int dnIndex = c.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName);
                while (c.MoveToNext())
                {
                    string id = c.GetString(idIndex);
                    if (currentContact == null || currentContact.Id != id)
                    {
                        // We need to yield these in the original ID order
                        if (currentContact != null)
                        {
                            if (currentContact.Id == ids[x])
                            {
                                yield return(currentContact);

                                x++;
                            }
                            else
                            {
                                map.Add(currentContact.Id, currentContact);
                            }
                        }

                        currentContact = new Contact(id, !rawContacts)
                        {
                            Tag = content
                        };
                        currentContact.DisplayName = c.GetString(dnIndex);
                    }

                    FillContactWithRow(resources, currentContact, c);
                }

                if (currentContact != null)
                {
                    map.Add(currentContact.Id, currentContact);
                }

                for (; x < ids.Length; x++)
                {
                    yield return(map[ids[x]]);
                }
            }
            finally
            {
                if (c != null)
                {
                    c.Close();
                }
            }
        }
Пример #41
0
 public SuggestionsAdapter(Context context, ICursor c)
     : base(context, c, 0)
 {
 }
Пример #42
0
        //internal static WebsiteType ToWebsiteType (this WebsiteDataKind websiteKind)
        //{
        //    switch (websiteKind)
        //    {
        //        case WebsiteDataKind.Work:
        //            return WebsiteType.Work;
        //        case WebsiteDataKind.Home:
        //            return WebsiteType.Home;

        //        default:
        //            return WebsiteType.Other;
        //    }
        //}

        internal static string GetString(this ICursor c, string colName)
        {
            return(c.GetString(c.GetColumnIndex(colName)));
        }
Пример #43
0
 internal static Note GetNote(ICursor c, Resources resources)
 {
     return(new Note {
         Contents = GetString(c, ContactsContract.DataColumns.Data1)
     });
 }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

                if (TrackCancel == null)
                {
                    TrackCancel = new CancelTrackerClass();
                }

                IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
                IGPValue     inputFeatureDatasetGPValue   = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
                IGPValue     outputOSMFileGPValue         = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));

                // get the name of the feature dataset
                int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");

                string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);


                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;

                System.Xml.XmlWriter xmlWriter = null;

                try
                {
                    xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
                }
                catch (Exception ex)
                {
                    message.AddError(120021, ex.Message);
                    return;
                }

                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("osm");                                             // start the osm root node
                xmlWriter.WriteAttributeString("version", "0.6");                               // add the version attribute
                xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute

                // write all the nodes
                // use a feature search cursor to loop through all the known points and write them out as osm node

                IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;

                if (osmFeatureClasses == null)
                {
                    message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
                    return;
                }

                IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");

                if (osmPointFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
                    return;
                }

                // check the extension of the point feature class to determine its version
                int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();

                IFeatureCursor searchCursor = null;

                System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
                xmlnsEmpty.Add("", "");

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
                int pointCounter = 0;

                string nodesExportedMessage = String.Empty;

                // collect the indices for the point feature class once
                int pointOSMIDFieldIndex     = osmPointFeatureClass.Fields.FindField("OSMID");
                int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
                int pointVersionFieldIndex   = osmPointFeatureClass.Fields.FindField("osmversion");
                int pointUIDFieldIndex       = osmPointFeatureClass.Fields.FindField("osmuid");
                int pointUserFieldIndex      = osmPointFeatureClass.Fields.FindField("osmuser");
                int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
                int pointVisibleFieldIndex   = osmPointFeatureClass.Fields.FindField("osmvisible");
                int pointTagsFieldIndex      = osmPointFeatureClass.Fields.FindField("osmTags");

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPointFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));

                    IFeature currentFeature = searchCursor.NextFeature();

                    IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == true)
                        {
                            // convert the found point feature into a osm node representation to store into the OSM XML file
                            node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

                            // increase the point counter to later status report
                            pointCounter++;

                            currentFeature = searchCursor.NextFeature();
                        }
                        else
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loader so far
                            nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                            message.AddMessage(nodesExportedMessage);

                            return;
                        }
                    }
                }

                nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                message.AddMessage(nodesExportedMessage);

                // next loop through the line and polygon feature classes to export those features as ways
                // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
                IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");

                if (osmLineFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
                    return;
                }

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg"));

                // as we are looping through the line and polygon feature classes let's collect the multi-part features separately
                // as they are considered relations in the OSM world
                List <relation> multiPartElements = new List <relation>();

                System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
                int    lineCounter         = 0;
                int    relationCounter     = 0;
                string waysExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmLineFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int lineOSMIDFieldIndex     = osmLineFeatureClass.Fields.FindField("OSMID");
                    int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
                    int lineVersionFieldIndex   = osmLineFeatureClass.Fields.FindField("osmversion");
                    int lineUIDFieldIndex       = osmLineFeatureClass.Fields.FindField("osmuid");
                    int lineUserFieldIndex      = osmLineFeatureClass.Fields.FindField("osmuser");
                    int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
                    int lineVisibleFieldIndex   = osmLineFeatureClass.Fields.FindField("osmvisible");
                    int lineTagsFieldIndex      = osmLineFeatureClass.Fields.FindField("osmTags");
                    int lineMembersFieldIndex   = osmLineFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }


                IFeatureClass     osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
                IFeatureWorkspace commonWorkspace        = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;

                if (osmPolygonFeatureClass == null)
                {
                    message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPolygonFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int polygonOSMIDFieldIndex     = osmPolygonFeatureClass.Fields.FindField("OSMID");
                    int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
                    int polygonVersionFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmversion");
                    int polygonUIDFieldIndex       = osmPolygonFeatureClass.Fields.FindField("osmuid");
                    int polygonUserFieldIndex      = osmPolygonFeatureClass.Fields.FindField("osmuser");
                    int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
                    int polygonVisibleFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmvisible");
                    int polygonTagsFieldIndex      = osmPolygonFeatureClass.Fields.FindField("osmTags");
                    int polygonMembersFieldIndex   = osmPolygonFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }

                waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                message.AddMessage(waysExportedMessage);


                // now let's go through the relation table
                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
                ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");

                if (relationTable == null)
                {
                    message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
                    return;
                }


                System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
                string relationsExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    ICursor rowCursor = relationTable.Search(null, false);
                    comReleaser.ManageLifetime(rowCursor);

                    IRow currentRow = rowCursor.NextRow();

                    // collect the indices for the relation table once
                    int relationOSMIDFieldIndex     = relationTable.Fields.FindField("OSMID");
                    int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
                    int relationVersionFieldIndex   = relationTable.Fields.FindField("osmversion");
                    int relationUIDFieldIndex       = relationTable.Fields.FindField("osmuid");
                    int relationUserFieldIndex      = relationTable.Fields.FindField("osmuser");
                    int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
                    int relationVisibleFieldIndex   = relationTable.Fields.FindField("osmvisible");
                    int relationTagsFieldIndex      = relationTable.Fields.FindField("osmTags");
                    int relationMembersFieldIndex   = relationTable.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;


                    while (currentRow != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement();  // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close();            // closing the document

                            // report the number of elements loaded so far
                            relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                            message.AddMessage(relationsExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
                        relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);

                        // increase the line counter for later status report
                        relationCounter++;

                        currentRow = rowCursor.NextRow();
                    }
                }

                // lastly let's serialize the collected multipart-geometries back into relation elements
                foreach (relation currentRelation in multiPartElements)
                {
                    if (TrackCancel.Continue() == false)
                    {
                        // properly close the document
                        xmlWriter.WriteEndElement();  // closing the osm root element
                        xmlWriter.WriteEndDocument(); // finishing the document

                        xmlWriter.Close();            // closing the document

                        // report the number of elements loaded so far
                        relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                        message.AddMessage(relationsExportedMessage);

                        return;
                    }

                    relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
                    relationCounter++;
                }

                relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                message.AddMessage(relationsExportedMessage);


                xmlWriter.WriteEndElement();  // closing the osm root element
                xmlWriter.WriteEndDocument(); // finishing the document

                xmlWriter.Close();            // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(120026, ex.Message);
            }
        }
Пример #45
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.detalle, container, false);

            Button btnRegistroDatos = view.FindViewById <Button>(Resource.Id.btnRegistrarDatos);

            expandable = view.FindViewById <LinearLayout>(Resource.Id.linearLayoutFillData);

            //Definicion de los diferentes espacios de texto a mostrar
            mExpediente            = view.FindViewById <TextView>(Resource.Id.txtExpediente);
            mSector                = view.FindViewById <TextView>(Resource.Id.txtSector);
            mFormaNotificacion     = view.FindViewById <TextView>(Resource.Id.txtFormaNotificacion);
            mProvincia             = view.FindViewById <TextView>(Resource.Id.txtProvincia);
            mCanton                = view.FindViewById <TextView>(Resource.Id.txtCanton);
            mDistrito              = view.FindViewById <TextView>(Resource.Id.textDistrito);
            mDireccion             = view.FindViewById <TextView>(Resource.Id.txtDireccion);
            mCopias                = view.FindViewById <TextView>(Resource.Id.txtCopias);
            mOficial               = view.FindViewById <TextView>(Resource.Id.txtOficialNombreDatos);
            mFechaNotificacion     = view.FindViewById <TextView>(Resource.Id.txtFechaNotificacion);
            mresultadoNotificacion = view.FindViewById <TextView>(Resource.Id.txtResultadoNotificacion);
            mFechaResolucion       = view.FindViewById <TextView>(Resource.Id.txtFechaResolucion);
            mDespacho              = view.FindViewById <TextView>(Resource.Id.txtDespacho);
            mNotificando           = view.FindViewById <TextView>(Resource.Id.txtNotificandoNombre);
            mUrgente               = view.FindViewById <TextView>(Resource.Id.txtUrgente);
            mHorario               = view.FindViewById <TextView>(Resource.Id.txtHorario);

            Switch mSwitch = view.FindViewById <Switch>(Resource.Id.monitored_switch);

            mSwitch.CheckedChange += delegate(object sender, CompoundButton.CheckedChangeEventArgs e)
            {
                mSwitch.Text = "Resultado " + (e.IsChecked ? "Positivo" : "Negativo");
            };
            expandable.Visibility   = ViewStates.Gone;
            btnRegistroDatos.Click += (s, e) =>
            {
                if (expandable.Visibility.Equals(ViewStates.Gone))
                {
                    expandable.Visibility = ViewStates.Visible;
                    int widthSpec  = View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
                    int heightSpec = View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified);
                    expandable.Measure(widthSpec, heightSpec);
                    ValueAnimator mAnimator = slideAnimator(0, expandable.MeasuredHeight);
                    mAnimator.Start();
                }
                else
                {
                    int           finalHeight = expandable.Height;
                    ValueAnimator mAnimator   = slideAnimator(finalHeight, 0);
                    mAnimator.Start();
                    mAnimator.AnimationEnd += (object IntentSender, EventArgs arg) => {
                        expandable.Visibility = ViewStates.Gone;
                    };
                }
            };
            //
            if (!string.IsNullOrEmpty(codNotificacion))
            {
                string query = "SELECT * FROM Notificaciones WHERE CodigoNotificacion=" + codNotificacion + "";
                ManejoBaseDatos.Abrir();
                ICursor mCursor = ManejoBaseDatos.Seleccionar(query);
                if (mCursor.MoveToFirst())
                {
                    do
                    {
                        mExpediente.Text        = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Expediente"))) ? mCursor.GetString(mCursor.GetColumnIndex("Expediente")) : "");
                        mSector.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Sector"))) ? mCursor.GetString(mCursor.GetColumnIndex("Sector")) : "");
                        mProvincia.Text         = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Provincia"))) ? mCursor.GetString(mCursor.GetColumnIndex("Provincia")) : "");
                        mCanton.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Canton"))) ? mCursor.GetString(mCursor.GetColumnIndex("Canton")) : "");
                        mDireccion.Text         = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Direccion"))) ? mCursor.GetString(mCursor.GetColumnIndex("Direccion")) : "");
                        mSector.Text            = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Sector"))) ? "S-" + mCursor.GetString(mCursor.GetColumnIndex("Sector")) : "");
                        mDistrito.Text          = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Distrito"))) ? mCursor.GetString(mCursor.GetColumnIndex("Distrito")) : "");
                        mFechaResolucion.Text   = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("FechaDocumento"))) ? mCursor.GetString(mCursor.GetColumnIndex("FechaDocumento")) : "");
                        mDespacho.Text          = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("DespachoDescripcion"))) ? mCursor.GetString(mCursor.GetColumnIndex("DespachoDescripcion")) : "");
                        mNotificando.Text       = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Notificando"))) ? mCursor.GetString(mCursor.GetColumnIndex("Notificando")) : "");
                        mFormaNotificacion.Text = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Medio"))) ? mCursor.GetString(mCursor.GetColumnIndex("Medio")) : "");
                        mUrgente.Text           = (mCursor.GetString(mCursor.GetColumnIndex("Urgente")).Equals("True") || (mCursor.GetString(mCursor.GetColumnIndex("Urgente")).Equals("true")) ? "Sí" : "No");
                        mHorario.Text           = (!string.IsNullOrEmpty(mCursor.GetString(mCursor.GetColumnIndex("Medio"))) ? "Sí" : "No");
                    } while (mCursor.MoveToNext());
                }
                mCursor.Close();
                ManejoBaseDatos.Cerrar();
            }
            else
            {
                AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context);
                alerta.SetTitle("Mensaje de alerta");
                alerta.SetIcon(Resource.Drawable.alertaNuevo);
                alerta.SetMessage("El usuario tiene una jornada abierta.");
                alerta.SetPositiveButton("Regresar", HandleButtonClick);
                //alerta.SetNegativeButton("Continuar", HandleButonContinuar);
                alerta.SetCancelable(false);
                alerta.Create();
                alerta.Show();
            }
            return(view);
        }
Пример #46
0
 /// <summary>
 /// Returns the value of the requested column as an int.
 /// </summary>
 /// <returns>The int.</returns>
 /// <param name="cursor">Cursor.</param>
 /// <param name="column">Column name.</param>
 public static int GetInt(this ICursor cursor, string column)
 {
     return(cursor.GetInt(cursor.GetColumnIndex(column)));
 }
Пример #47
0
 /// <summary>
 /// Returns the number of elements that the buffer currently contains for the given cursor.
 /// </summary>
 /// <param name="cursor">TBD</param>
 /// <returns>TBD</returns>
 public long Count(ICursor cursor) => _writeIndex - cursor.Cursor;
Пример #48
0
 /// <summary>
 /// Returns the value of the requested column as a long.
 /// </summary>
 /// <returns>The long.</returns>
 /// <param name="cursor">Cursor.</param>
 /// <param name="column">Column name.</param>
 public static long GetLong(this ICursor cursor, string column)
 {
     return(cursor.GetLong(cursor.GetColumnIndex(column)));
 }
Пример #49
0
        /// <summary>
        /// Returns the value of the requested column as a DateTime
        /// </summary>
        /// <returns>The DateTime.</returns>
        /// <param name="cursor">Cursor.</param>
        /// <param name="column">Column name.</param>
        public static DateTime GetDateTime(this ICursor cursor, string column)
        {
            var ms = cursor.GetLong(cursor.GetColumnIndex(column));

            return(DateConversions.GetDateFromAndroidMS(ms));
        }
Пример #50
0
 /// <summary>
 /// Returns the value of the requested column as a boolean.
 /// </summary>
 /// <returns>The boolean.</returns>
 /// <param name="cursor">Cursor.</param>
 /// <param name="column">Column name.</param>
 public static bool GetBoolean(this ICursor cursor, string column)
 {
     return(cursor.GetInt(cursor.GetColumnIndex(column)) != 0);
 }
Пример #51
0
 /// <summary>
 /// Returns the number of elements that the buffer currently contains for the given cursor.
 /// </summary>
 /// <param name="cursor">TBD</param>
 /// <returns>TBD</returns>
 public long Count(ICursor cursor) => Length - cursor.Cursor;
 public NoteslistCursorAdapter(Activity context, ICursor c)
     : base(context, c)
 {
     this.context = context;
 }
Пример #53
0
 public Decimal(ICursor <XElement> p, T t)
 {
     _parent = p;
     _target = t;
 }
Пример #54
0
 private void dataGrid1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
 {
     if (e.Button.ButtonType == NavigatorButtonType.Remove)
     {
         if ((this.m_InEditing && this.m_CanDo) && (((GridView)this.dataGrid1.MainView).SelectedRowsCount > 0))
         {
             IFeatureLayer pTable = this.m_pTable as IFeatureLayer;
             if (pTable.FeatureClass != null)
             {
                 string oIDFieldName = pTable.FeatureClass.OIDFieldName;
                 int[]  selectedRows = ((GridView)this.dataGrid1.MainView).GetSelectedRows();
                 this.m_CanDoFeatureLayerSelectChange = false;
                 IWorkspaceEdit workspace = (this.m_pTable as IDataset).Workspace as IWorkspaceEdit;
                 for (int i = 0; i < selectedRows.Length; i++)
                 {
                     object obj2 = ((GridView)this.dataGrid1.MainView).GetRow(selectedRows[i]);
                     if (obj2 is DataRowView)
                     {
                         int          num2        = Convert.ToInt32((obj2 as DataRowView).Row[oIDFieldName]);
                         IQueryFilter queryFilter = new QueryFilterClass
                         {
                             WhereClause = this.m_pTable.OIDFieldName + " = " + num2.ToString()
                         };
                         ICursor o   = this.m_pTable.Search(queryFilter, false);
                         IRow    row = o.NextRow();
                         if (row != null)
                         {
                             workspace.StartEditOperation();
                             row.Delete();
                             workspace.StopEditOperation();
                         }
                         row = null;
                         ComReleaser.ReleaseCOMObject(o);
                         o = null;
                     }
                 }
                 this.m_CanDoFeatureLayerSelectChange = true;
                 if (this.m_pTable is IFeatureLayer)
                 {
                     try
                     {
                         (this.m_pMap as IActiveView).Refresh();
                     }
                     catch
                     {
                     }
                 }
             }
         }
     }
     else if (e.Button.ButtonType == NavigatorButtonType.Last)
     {
         if (this.m_pDataTable.Rows.Count < this.m_RecordNum)
         {
             this.AddRecordToListView(true);
         }
     }
     else if (((e.Button.ButtonType == NavigatorButtonType.Next) &&
               (((GridView)this.dataGrid1.MainView).GetSelectedRows()[0] == (this.m_pDataTable.Rows.Count - 2))) &&
              (this.m_pDataTable.Rows.Count < this.m_RecordNum))
     {
         this.AddRecordToListView(false);
     }
 }
Пример #55
0
        /// <summary>
        /// 获得当前字段的唯一值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGetValue_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxFields.SelectedIndex == -1)
                {
                    return;
                }

                string currentFieldName = this.listBoxFields.Text;//当前字段名
                string currentLayerName = this.comboBoxLayers.Text;
                this.pEnumLayer.Reset();
                for (this.pLayer = this.pEnumLayer.Next(); this.pLayer != null; this.pLayer = this.pEnumLayer.Next())
                {
                    if (this.pLayer.Name == currentLayerName)
                    {
                        break;
                    }
                }
                this.pLayerFields = this.pLayer as ILayerFields;
                IField        pField     = this.pLayerFields.get_Field(this.pLayerFields.FindField(currentFieldName));
                esriFieldType pFieldType = pField.Type;

                //对Table中当前字段进行排序,把结果赋给Cursor
                ITable     pTable     = this.pLayer as ITable;
                ITableSort pTableSort = new TableSortClass();
                pTableSort.Table  = pTable;
                pTableSort.Fields = currentFieldName;
                pTableSort.set_Ascending(currentFieldName, true);
                pTableSort.set_CaseSensitive(currentFieldName, true); //这两句的意思我还不懂,照猫画虎写的。
                pTableSort.Sort(null);                                //排序
                ICursor pCursor = pTableSort.Rows;

                //字段统计
                IDataStatistics pDataStatistics = new DataStatisticsClass();
                pDataStatistics.Cursor = pCursor;
                pDataStatistics.Field  = currentFieldName;
                System.Collections.IEnumerator pEnumeratorUniqueValues = pDataStatistics.UniqueValues; //唯一值枚举
                int uniqueValueCount = pDataStatistics.UniqueValueCount;                               //唯一值的个数

                this.listBoxValues.Items.Clear();
                string currentValue = null;
                pEnumeratorUniqueValues.Reset();

                //别人的答案

                if (pFieldType == esriFieldType.esriFieldTypeString)
                {
                    while (pEnumeratorUniqueValues.MoveNext())
                    {
                        currentValue = pEnumeratorUniqueValues.Current.ToString();
                        this.listBoxValues.Items.Add("'" + currentValue + "'");
                    }
                }
                else
                {
                    while (pEnumeratorUniqueValues.MoveNext())
                    {
                        currentValue = pEnumeratorUniqueValues.Current.ToString();
                        this.listBoxValues.Items.Add(currentValue);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #56
0
        private void FillDataTable(ITable table, esriGeometryType type, DataTable pDataTable)
        {
            try
            {
                List <int> dataTableIndex = new List <int>();
                List <int> fieldIndex     = new List <int>();
                for (int i = 0; i < pDataTable.Columns.Count; i++)
                {
                    int index = table.Fields.FindField(pDataTable.Columns[i].ColumnName);
                    if (index != -1)
                    {
                        dataTableIndex.Add(i);
                        fieldIndex.Add(index);
                    }
                }

                //取得图层类型
                string shapeType = GetShapeType(type);
                //创建DataTable的行对象
                DataRow pDataRow = null;
                //从ILayer查询到ITable
                ICursor pCursor = table.Search(null, false);
                //取得ITable中的行信息
                IRow pRow = pCursor.NextRow();

                List <Fiel> fiel  = new List <Fiel>();
                int         count = fieldIndex.Count;
                if (pRow != null)
                {
                    for (int i = count - 1; i >= 0; i--)
                    {
                        //如果字段类型为esriFieldTypeGeometry,则根据图层类型设置字段值
                        int dtIndex = dataTableIndex[i];
                        int index   = fieldIndex[i];
                        if (pRow.Fields.get_Field(index).Type == esriFieldType.esriFieldTypeGeometry)
                        {
                            Fiel f = new Fiel();
                            f.dtIndex = dtIndex;
                            f.value   = shapeType;
                            fiel.Add(f);
                            fieldIndex.RemoveAt(i);
                            dataTableIndex.RemoveAt(i);
                        }
                        //当图层类型为Anotation时,要素类中会有esriFieldTypeBlob类型的数据,
                        //其存储的是标注内容,如此情况需将对应的字段值设置为Element
                        else if (pRow.Fields.get_Field(index).Type == esriFieldType.esriFieldTypeBlob)
                        {
                            Fiel f = new Fiel();
                            f.dtIndex = dtIndex;
                            f.value   = "Element";
                            fiel.Add(f);
                            fieldIndex.RemoveAt(i);
                            dataTableIndex.RemoveAt(i);
                        }
                    }
                }

                while (pRow != null)
                {
                    pDataRow = pDataTable.NewRow();
                    for (int i = 0; i < fieldIndex.Count; i++)
                    {
                        pDataRow[dataTableIndex[i]] = pRow.get_Value(fieldIndex[i]);
                    }
                    for (int i = 0; i < fiel.Count; i++)
                    {
                        pDataRow[fiel[i].dtIndex] = fiel[i].value;
                    }

                    pDataTable.Rows.Add(pDataRow);
                    pRow = pCursor.NextRow();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Пример #57
0
        /// <summary>
        ///     获取一定范围的实体
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="type"></param>
        /// <param name="mount"></param>
        /// <param name="skip"></param>
        /// <returns></returns>
        public override IEnumerable <IFreeDocument> GetEntities(
            string tableName, Type type, int mount = -1, int skip = 0)
        {
            if (IsUseable == false)
            {
                yield break;
            }
            if (TableNames == null)
            {
                IsUseable = false;
                yield break;
            }
            if (TableNames == null)
            {
                IsUseable = false;
                yield break;
            }
            TableInfo table = TableNames.Collection.FirstOrDefault(d => d.Name == tableName);

            if (table == null)
            {
                yield break;
            }

            ICursor <Document> collection = null;

            if (table.ColumnInfos != null && table.ColumnInfos.FirstOrDefault(d => d.Name == AutoIndexName) != null)
            {
                var query = new Document();

                query[AutoIndexName] = new Document("$gt", skip);


                collection = DB.GetCollection <Document>(tableName).Find(query).Sort(AutoIndexName, IndexOrder.Ascending);
            }
            else
            {
                collection = DB.GetCollection <Document>(tableName).FindAll();
                if (skip != 0)
                {
                    collection.Skip(skip);
                }
            }
            if (mount != -1)
            {
                collection = collection.Limit(mount);
            }


            foreach (Document document in collection.Documents)
            {
                IFreeDocument data = null;
                if (type == null)
                {
                    data = new FreeDocument();
                }
                else
                {
                    data = (IFreeDocument)Activator.CreateInstance(type);
                }


                data.DictDeserialize(document);
                yield return(data);
            }
        }
Пример #58
0
        public ITable DataTableToAETable(DataTable table, IFeatureWorkspace featureWorkspace, string[] fieldsName, string name)
        {
            if (table != null && featureWorkspace != null)
            {
                IFields     pFileds     = new FieldsClass();
                IFieldsEdit pFieldsEdit = (IFieldsEdit)pFileds;

                Dictionary <string, string> fieldLookUp = new Dictionary <string, string>();
                string[] fName = FieldNameCopy(table, fieldsName, fieldLookUp);

                int count = fName.Length;
                if (count > 50)
                {
                    count = 50;
                }

                for (int i = 0; i < count; i++)
                {
                    esriFieldType type = GetAEFieldType(table.Columns[fieldLookUp[fName[i]]]);
                    if (type == esriFieldType.esriFieldTypeGeometry)
                    {
                        continue;
                    }

                    IField     pField     = new FieldClass();
                    IFieldEdit pFieldEdit = (IFieldEdit)pField;
                    pFieldEdit.Name_2 = fName[i];
                    pFieldEdit.Type_2 = type;
                    //pFieldEdit.Length_2 = 50;

                    pFieldsEdit.AddField(pField);
                }

                ITable pTable = featureWorkspace.CreateTable(name, pFileds, null, null, "");

                try
                {
                    if (count < fName.Length)
                    {
                        for (int i = count; i < fName.Length; i++)
                        {
                            esriFieldType type = GetAEFieldType(table.Columns[i]);

                            if (type == esriFieldType.esriFieldTypeGeometry || fName[i] == "ObjectId" || pFileds.FindField(fName[i]) != -1)
                            {
                                continue;
                            }

                            IField     pField     = new FieldClass();
                            IFieldEdit pFieldEdit = (IFieldEdit)pField;
                            pFieldEdit.Name_2 = fName[i];
                            pFieldEdit.Type_2 = type;
                            pTable.AddField(pField);
                        }
                    }

                    List <string> fNames = new List <string>();
                    List <int>    index  = new List <int>();
                    for (int i = 0; i < fName.Length; i++)
                    {
                        int id = pTable.Fields.FindField(fName[i]);
                        if (id != -1)
                        {
                            index.Add(id);
                            fNames.Add(fName[i]);
                        }
                    }
                    fName = fNames.ToArray();

                    ICursor cursor = pTable.Insert(true);
                    //添加内容
                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        IRowBuffer rowBuffer = pTable.CreateRowBuffer();
                        DataRow    myRow     = table.Rows[j];
                        for (int i = 0; i < fName.Length; i++)
                        {
                            string dataTableField = fieldLookUp[fName[i]];
                            object obj            = myRow[dataTableField];
                            if (obj.ToString() != "")
                            {
                                rowBuffer.set_Value(index[i], obj);
                            }
                        }
                        cursor.InsertRow(rowBuffer);
                    }
                    if (pFileds != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFileds);
                    }
                    if (pFieldsEdit != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFieldsEdit);
                    }
                    if (featureWorkspace != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(featureWorkspace);
                    }
                    return(pTable);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            return(null);
        }
Пример #59
0
        /// <summary>
        /// Gets the file for URI asynchronous.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uri">The URI.</param>
        /// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
        /// <returns>Task&lt;Tuple&lt;System.String, System.Boolean&gt;&gt;.</returns>
        internal static Task <Tuple <string, bool> > GetFileForUriAsync(Context context, Uri uri, bool isPhoto)
        {
            var tcs = new TaskCompletionSource <Tuple <string, bool> >();

            var fixedUri = FixUri(uri.Path);

            if (fixedUri != null)
            {
                uri = fixedUri;
            }

            if (uri.Scheme == "file")
            {
                tcs.SetResult(new Tuple <string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
            }
            else if (uri.Scheme == "content")
            {
                Task.Factory.StartNew(() =>
                {
                    ICursor cursor = null;
                    try
                    {
                        cursor = context.ContentResolver.Query(uri, null, null, null, null);
                        if (cursor == null || !cursor.MoveToNext())
                        {
                            tcs.SetResult(new Tuple <string, bool>(null, false));
                        }
                        else
                        {
                            int column         = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
                            string contentPath = null;

                            if (column != -1)
                            {
                                contentPath = cursor.GetString(column);
                            }

                            bool copied = false;

                            // If they don't follow the "rules", try to copy the file locally
//							if (contentPath == null || !contentPath.StartsWith("file"))
//							{
//								copied = true;
//								Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto);
//
//								try
//								{
//									using (Stream input = context.ContentResolver.OpenInputStream(uri))
//									using (Stream output = File.Create(outputPath.Path))
//										input.CopyTo(output);
//
//									contentPath = outputPath.Path;
//								}
//								catch (FileNotFoundException)
//								{
//									// If there's no data associated with the uri, we don't know
//									// how to open this. contentPath will be null which will trigger
//									// MediaFileNotFoundException.
//								}
//							}

                            tcs.SetResult(new Tuple <string, bool>(contentPath, copied));
                        }
                    }
                    finally
                    {
                        if (cursor != null)
                        {
                            cursor.Close();
                            cursor.Dispose();
                        }
                    }
                }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            }
            else
            {
                tcs.SetResult(new Tuple <string, bool>(null, false));
            }

            return(tcs.Task);
        }
Пример #60
0
        internal static Contact GetContact(bool rawContact, ContentResolver content, Resources resources, ICursor cursor)
        {
            string id = (rawContact)
              ? cursor.GetString(cursor.GetColumnIndex(ContactsContract.RawContactsColumns.ContactId))
              : cursor.GetString(cursor.GetColumnIndex(ContactsContract.ContactsColumns.LookupKey));

            var contact = new Contact(id, !rawContact)
            {
                Tag = content
            };

            contact.DisplayName = GetString(cursor, ContactsContract.ContactsColumns.DisplayName);

            FillContactExtras(rawContact, content, resources, id, contact);

            return(contact);
        }