/// <summary>
        /// The cut.
        /// </summary>
        /// <param name="parameters">
        /// The current parameters for segmentation.
        /// </param>
        /// <returns>
        /// The convoluted chain <see cref="ComplexChain"/>.
        /// </returns>
        public override ComplexChain Cut(ContentValues parameters)
        {
            int maxWindowLen = (int)parameters.Get(Enum.GetName(typeof(Parameter), Parameter.Window));
            int windowDec = (int)parameters.Get(Enum.GetName(typeof(Parameter), Parameter.WindowDecrement));

            convoluted = (ComplexChain)parameters.Get(Formalism.GetName(typeof(Formalism), Formalism.Sequence));
            alphabet = new FrequencyDictionary();

            for (int winLen = maxWindowLen; (winLen >= windowDec) && (winLen > 1); winLen -= windowDec)
            {
                bool flag = true;
                while (flag)
                {
                    UpdateParams(parameters, winLen);
                    KeyValuePair<List<string>, List<int>>? pair = WordExtractorFactory.GetSeeker(extractor).Find(parameters);
                    flag = pair != null;
                    if (flag)
                    {
                        pair.Value.Value.Reverse();
                        foreach (int position in pair.Value.Value)
                        {
                            convoluted.Join(position, winLen);
                        }

                        alphabet.Add(Helper.ToString(pair.Value.Key), pair.Value.Value);
                    }
                }
            }

            FindLastWords();

            return convoluted;
        }
        /// <summary>
        /// The find.
        /// </summary>
        /// <param name="par">
        /// The par.
        /// </param>
        /// <returns>
        /// The <see cref="T:KeyValuePair{List{string},List{int}}?"/>.
        /// </returns>
        public override sealed KeyValuePair<List<string>, List<int>>? Find(ContentValues par)
        {
            var convoluted = (ComplexChain)par.Get(Enum.GetName(typeof(Formalism), Formalism.Sequence));
            double pbalance = (int)par.Get(Enum.GetName(typeof(Parameter), Parameter.Balance)) / 100.0;
            int windowLen = (int)par.Get(Enum.GetName(typeof(Parameter), Parameter.Window));
            var alphabet = (FrequencyDictionary)par.Get(Enum.GetName(typeof(Formalism), Formalism.Alphabet));
            var level = (double)par.Get(Enum.GetName(typeof(Parameter), Parameter.CurrentThreshold));
            int scanStep = 1;
            int disp = 0;
            int length = convoluted.GetLength();

            fullEntry = new DataCollector();
            minusOneEntry = new DataCollector();
            minusTwoEntry = new DataCollector();

            var it = new StartIterator(convoluted, windowLen, scanStep);
            CriterionMethod criteriaCalculator = new ConvolutedCriterionMethod();

            while (it.HasNext())
            {
                it.Next();
                fullEntry.Add(it, disp);
                FindLess(it);
            }

            CalculateStd(convoluted, pbalance, windowLen, length, criteriaCalculator);

            return DiscardCompositeWords(alphabet, level);
        }
	  /// <summary>
	  /// Parse an announcement. </summary>
	  /// <param name="campaignId"> already parsed campaign id. </param>
	  /// <param name="values"> campaign data. </param>
	  /// <param name="params"> special parameters to inject in the action URL of the announcement. </param>
	  /// <exception cref="JSONException"> if a parsing error occurs. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: EngagementAbstractAnnouncement(CampaignId campaignId, android.content.ContentValues values, java.util.Map<String, String> params) throws org.json.JSONException
	  internal EngagementAbstractAnnouncement(CampaignId campaignId, ContentValues values, IDictionary<string, string> @params) : base(campaignId, values)
	  {
		string actionURL = values.getAsString(ACTION_URL);
		foreach (KeyValuePair<string, string> param in @params.SetOfKeyValuePairs())
		{
		  if (actionURL != null)
		  {
			actionURL = actionURL.Replace(param.Key, param.Value);
		  }
		}
		mActionURL = actionURL;
	  }
Esempio n. 4
0
        public void Save()
        {
            SQLiteDatabase sqlDatabase = null;

            try
            {
                Globals dbHelp = new Globals();
                dbHelp.OpenDatabase();
                sqlDatabase = dbHelp.GetSQLiteDatabase();
                if (sqlDatabase != null)
                {
                    if (sqlDatabase.IsOpen)
                    {
                        ContentValues values = new ContentValues();
                        values.Put("ProblemText", ProblemText.Trim());

                        if (IsNew)
                        {
                            ProblemID = (int)sqlDatabase.Insert("Problems", null, values);
                            IsNew     = false;
                            IsDirty   = false;
                        }
                        if (IsDirty)
                        {
                            string whereClause = "ProblemID = ?";
                            sqlDatabase.Update("Problems", values, whereClause, new string[] { ProblemID.ToString() });
                            IsDirty = false;
                        }
                        sqlDatabase.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(TAG, "Save: Exception - " + e.Message);
                if (sqlDatabase != null && sqlDatabase.IsOpen)
                {
                    sqlDatabase.Close();
                }
            }
        }
Esempio n. 5
0
        void ListEvents2()
        {
            var eventsUri = CalendarContract.Events.ContentUri;

            ContentValues eventValues = new ContentValues();

            eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId);
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Please remember to fill in your planner today");
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "Planner");
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS2(0, 0, 0, 0, 0));
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS2(0, 0, 0, 0, 0));
            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");

            try
            {
                var uri = Application.Context.ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues);

                Console.WriteLine("Uri for new event: {0}", uri);

                long   eventID = long.Parse(uri.LastPathSegment);
                string Tags    = eventID.ToString();
                Console.WriteLine("Here it is:D {0}", Tags);

                var reminderValues = new ContentValues();
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID);
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, (int)RemindersMethod.Alert);
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 1);

                var reminderUri = Application.Context.ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues);
                Console.WriteLine("Uri for new event: {0}", reminderUri);
            }
            catch (SQLiteException ex)
            {
                System.Diagnostics.Debug.WriteLine("Hit an error: " + ex.Message);
            }

            _TimesDb.InsertData(new Times {
                Time = DateTime.Now.Day
            });
        }
        public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!String.IsNullOrWhiteSpace(nullColumnHack))
            {
                var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag));
                Log.E(Tag, "Unsupported use of nullColumnHack", e);
                throw e;
            }

            var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);

            var lastInsertedId = -1L;

            try {
                var result = command.Step();

                // Get the new row's id.
                // TODO.ZJG: This query should ultimately be replaced with a call to sqlite3_last_insert_rowid.
                var lastInsertedIndexCommand = Connection.Prepare("select last_insert_rowid()");
                var rowidResult = lastInsertedIndexCommand.Step();
                if (rowidResult != SQLiteResult.ERROR)
                {
                    throw new CouchbaseLiteException(lastInsertedIndexCommand.Connection.ErrorMessage(), StatusCode.DbError);
                }
                lastInsertedId = Convert.ToInt64(lastInsertedIndexCommand[0]);
                lastInsertedIndexCommand.Dispose();
                if (lastInsertedId == -1L)
                {
                    Log.E(Tag, "Error inserting " + initialValues + " using " + command);
                }
                else
                {
                    Log.V(Tag, "Inserting row " + lastInsertedId + " from " + initialValues + " using " + command);
                }
            } catch (Exception ex) {
                Log.E(Tag, "Error inserting into table " + table, ex);
            } finally {
                command.Dispose();
            }
            return(lastInsertedId);
        }
Esempio n. 7
0
        public bool addUser(User user)
        {
            if (mDBHelper == null)
            {
                return(false);
            }
            try
            {
                mDatabase = mDBHelper.WritableDatabase;
                beginTransaction(mDatabase);
                ContentValues cv = new ContentValues();
                cv.Put("user_id", user.getUserId());
                cv.Put("user_info", user.getUserInfo());
                cv.Put("group_id", user.getGroupId());
                cv.Put("update_time", DateTime.Now.Millisecond);
                cv.Put("ctime", DateTime.Now.Millisecond);

                long rowId = mDatabase.Insert(DBHelper.TABLE_USER, null, cv);
                if (rowId < 0)
                {
                    return(false);
                }

                foreach (Feature feature in user.getFeatureList())
                {
                    if (!addFeature(feature, mDatabase))
                    {
                        return(false);
                    }
                }

                setTransactionSuccessful(mDatabase);
                LogUtil.i("info", "insert user success:" + rowId);
            }
            catch (Java.Lang.Exception)
            {
                endTransaction(mDatabase);
            }

            return(true);
        }
Esempio n. 8
0
        public long SaveConfig(Dictionary <string, string> dic)
        {
            if (dic == null || dic.Count == 0)
            {
                return(0);
            }

            var db = helper.WritableDatabase;

            db.Delete("smsconfig", "", null);
            ContentValues values = new ContentValues();

            if (dic.ContainsKey("messagetemplate"))
            {
                values.Put("messagetemplate", dic["messagetemplate"].Trim());
            }
            if (dic.ContainsKey("smtpserver"))
            {
                values.Put("smtpserver", dic["smtpserver"].Trim());
            }
            if (dic.ContainsKey("smtpaccount"))
            {
                values.Put("smtpaccount", dic["smtpaccount"].Trim());
            }
            if (dic.ContainsKey("smtppassword"))
            {
                values.Put("smtppassword", dic["smtppassword"].Trim());
            }
            if (dic.ContainsKey("controlphone"))
            {
                values.Put("controlphone", dic["controlphone"].Trim());
            }
            if (dic.ContainsKey("smtpport"))
            {
                values.Put("smtpport", dic["smtpport"].Trim());
            }
            long result = db.Insert("smsconfig", null, values);

            db.Dispose();
            return(result);
        }
Esempio n. 9
0
        public async Task SaveImageAsync(string fileName, string url)
        {
            ContentResolver resolver = this.Context?.ContentResolver;

            if (resolver != null)
            {
                Android.Net.Uri imagesCollection;
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q)
                {
                    imagesCollection = MediaStore.Images.Media.GetContentUri(MediaStore.VolumeExternalPrimary);
                }
                else
                {
                    imagesCollection = MediaStore.Images.Media.ExternalContentUri;
                }

                try
                {
                    var imageData = await GetImageFromUriAsync(url);

                    ContentValues image     = new ContentValues();
                    var           imageName = fileName.Split('.').First();
                    image.Put(MediaStore.Images.ImageColumns.DisplayName, string.Join(string.Empty, imageName.Split('_')));
                    image.Put(MediaStore.Images.ImageColumns.MimeType, "image/jpeg");

                    Android.Net.Uri savedImageUri = resolver.Insert(imagesCollection, image);

                    using (Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length))
                    {
                        using (Stream stream = resolver.OpenOutputStream(savedImageUri))
                        {
                            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ImageService.SaveImageAsync Exception: {ex}");
                }
            }
        }
Esempio n. 10
0
        private static async Task <Android.Net.Uri> WriteContentValuesAsync(string tempfilename, string filename, string mimeType)
        {
            using var stream        = System.IO.File.OpenRead(tempfilename);
            using var contentValues = new ContentValues();
            contentValues.Put(MediaStore.IMediaColumns.DisplayName, filename);
            contentValues.Put(MediaStore.IMediaColumns.MimeType, mimeType);

            var uri = MainActivity.Instance.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);

            if (uri == null)
            {
                return(null);
            }

            using (var outputStream = MainActivity.Instance.ContentResolver.OpenOutputStream(uri))
            {
                await stream.CopyToAsync(outputStream).ConfigureAwait(false);
            }

            return(uri);
        }
        public override void ExecuteBadge(int badgeCount)
        {
            try
            {
                ContentValues contentValues = new ContentValues();
                contentValues.Put(Tag, string.Format(IntentTagValueFormat, ContextPackageName, EntryActivityName));
                contentValues.Put(Count, badgeCount);
                _context.ContentResolver.Insert(Android.Net.Uri.Parse(ContentUri), contentValues);
            }
            catch (Java.Lang.IllegalArgumentException)
            {
                /* Fine, TeslaUnread is not installed. */
            }
            catch (Exception ex)
            {
                /* Some other error, possibly because the format
                 * of the ContentValues are incorrect. */

                throw new ShortcutBadgeException(ex.Message);
            }
        }
Esempio n. 12
0
        public void clearResourcesInDownloadQueue()
        {
            ContentValues values = new ContentValues();

            values.Put(STATE, SKToolsDownloadItem.NotQueued);
            values.Put(NO_DOWNLOADED_BYTES, 0);
            try
            {
                resourcesDAO.getDatabase().BeginTransaction();
                resourcesDAO.getDatabase().Update(MAPS_TABLE, values, STATE + "=? OR " + STATE + "=? OR " + STATE + "=?", new string[] { SKToolsDownloadItem.Downloading.ToString(), SKToolsDownloadItem.Paused.ToString(), SKToolsDownloadItem.Queued.ToString() });
                resourcesDAO.getDatabase().SetTransactionSuccessful();
            }
            catch (SQLException e)
            {
                SKLogging.WriteLog(TAG, "SQL EXCEPTION SAVE MAP DATA " + e.Message, SKLogging.LogError);
            }
            finally
            {
                resourcesDAO.getDatabase().EndTransaction();
            }
        }
Esempio n. 13
0
        void InsertValues()
        {
            ContentValues values = new ContentValues();

            // Don't set _ID if you want to auto increment it.
            //values.Put(LocationContentProvider._ID, 1);
            values.Put(LocationContentProvider.NAME, "Brüel & Kjær");
            values.Put(LocationContentProvider.LATITUTDE, 55.816932);
            values.Put(LocationContentProvider.LONGITUDE, 12.532697);
            Android.Net.Uri uri = ContentResolver.Insert(LocationContentProvider.CONTENT_URI, values);
            System.Diagnostics.Debug.WriteLine("Insert: " + uri.ToString());

            values.Clear();

            //values.Put(LocationContentProvider._ID, 2);
            values.Put(LocationContentProvider.NAME, "Technical University of Denmark");
            values.Put(LocationContentProvider.LATITUTDE, 55.786323);
            values.Put(LocationContentProvider.LONGITUDE, 12.524135);
            uri = ContentResolver.Insert(LocationContentProvider.CONTENT_URI, values);
            System.Diagnostics.Debug.WriteLine("Insert: " + uri.ToString());
        }
        //Сюди будемо передавати одиницю, якщо хочемо здійснити запис в базу даних
        protected override bool RunInBackground(params int[] @params)
        {
            int param = @params[0];

            if (param == 1)
            {
                SQLiteOpenHelper updateCleannessOfTask = new RationalCleaningDatabaseHelper(context);

                try
                {
                    SQLiteDatabase db = updateCleannessOfTask.WritableDatabase;

                    ContentValues taskValues = new ContentValues();

                    if (cleanness == 0 || cleanness == 1)
                    {
                        taskValues.Put("CLEANNESS", cleanness);
                        taskValues.Put("YEAR", year);
                        taskValues.Put("MONTH", month);
                        taskValues.Put("DAY_OF_MONTH", dayOfMonth);
                        taskValues.Put("DATE_DEFAULT", dateDefault);
                        taskValues.Put("YEAR_OF_CHANGE", yearOfChange);
                        taskValues.Put("MONTH_OF_CHANGE", monthOfChange);
                        taskValues.Put("DAY_OF_MONTH_OF_CHANGE", dayOfMonthOfChange);
                    }

                    db.Update("CLEANING_TASK_TABLE", taskValues, "_id = ?", new string[] { taskId.ToString() });

                    db.Close();

                    return(true);
                }
                catch (SQLException)
                {
                    return(false);
                }
            }

            return(false);
        }
        public override void SetBadge(int count)
        {
            try {
                /*ContentResolver contentResolver = mContext.ContentResolver;
                 * var cursor = contentResolver.Query(CONTENT_URI, new string[]{ COLUMN_ID }, COLUMN_PACKAGE + "=?", new string[]{ GetPackageName() }, null);
                 *
                 * if (cursor == null || !cursor.MoveToFirst()) {
                 * var contentValues = new ContentValues();
                 * contentValues.Put(COLUMN_PACKAGE, GetPackageName());
                 * contentValues.Put(COLUMN_CLASS, GetMainActivityClassName());
                 * contentValues.Put(COLUMN_BADGE_COUNT, count);
                 * contentResolver.Insert(CONTENT_URI, contentValues);
                 * } else {
                 * int idColumnIndex = cursor.GetColumnIndex(COLUMN_ID);
                 *
                 * var contentValues = new ContentValues();
                 * contentValues.Put(COLUMN_BADGE_COUNT, count);
                 *      contentResolver.Update(CONTENT_URI, contentValues, COLUMN_ID + "=?", new string[]{ cursor.GetInt(idColumnIndex).ToString() });
                 * }*/

                var cv = new ContentValues();
                cv.Put("package", GetPackageName());
                cv.Put("class", GetMainActivityClassName());
                cv.Put("badgecount", count);                 // integer count you want to display

                ContentResolver contentResolver = mContext.ContentResolver;

                int updated = contentResolver.Update(CONTENT_URI, cv, "package=?", new string[] { GetPackageName() });

                if (updated == 0)
                {
                    contentResolver.Insert(CONTENT_URI, cv);
                }
            } catch (Exception e) {
                // Some Samsung devices are throwing SecurityException or RuntimeException when
                // trying to set the badge saying the app needs permission which are already added,
                // this try/catch protect us from these "crappy phones" :)
                throw new Java.Lang.UnsupportedOperationException();
            }
        }
Esempio n. 16
0
        public void SaveShiftsEntry(ShiftsEntry item, bool overwrite)
        {
            //Datensatz erstellen
            string read = DatabaseHelper.BOOL_FALSE;

            if (item.MarkedRead)
            {
                read = DatabaseHelper.BOOL_TRUE;
            }

            ContentValues values = new ContentValues();

            values.Put(DatabaseHelper.SHIFT_TABLE_COL_KEY, item.Key);
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_TITLE, item.Title);
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_MONTH, item.Month);
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_YEAR, item.Year);
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_UPDATE, TBL.EncodeDateToString(item.LastUpdate));
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_VERSION, item.LastVersion);
            values.Put(DatabaseHelper.SHIFT_TABLE_COL_READ, read);

            //Datenbank aktualisieren
            if (item.ID < 0)
            {
                //Neuen Eintrag anlegen
                int ID = (int)database.Insert(DatabaseHelper.SHIFT_TABLE, null, values);
                item.ID = ID;
            }
            else
            {
                if (overwrite)
                {
                    //Bestehenden Eintrag überschreiben
                    string id_filter = DatabaseHelper.SHIFT_TABLE_COL_ID + "='" + item.ID + "'";
                    database.Update(DatabaseHelper.SHIFT_TABLE, values, id_filter, null);
                }
            }

            //Feed-Anhänge aktualisieren
            SaveAttachment(item.ShiftAttachment, DatabaseHelper.OWNER_SHIFTS, item.ID, overwrite);
        }
        public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs)
        {
            Debug.Assert(!String.IsNullOrWhiteSpace(table));
            Debug.Assert(values != null);

            var          command = GetUpdateCommand(table, values, whereClause, whereArgs);
            sqlite3_stmt lastInsertedIndexCommand = null;

            var resultCount = -1;

            try {
                var result = command.Step();
                if (result == SQLiteResult.ERROR)
                {
                    throw new CouchbaseLiteException(command.Connection.ErrorMessage(), StatusCode.DbError);
                }
                // Get the new row's id.
                // TODO.ZJG: This query should ultimately be replaced with a call to sqlite3_last_insert_rowid.
                lastInsertedIndexCommand = Connection.Prepare("select changes()");
                result = lastInsertedIndexCommand.Step();
                if (result != SQLiteResult.ERROR)
                {
                    throw new CouchbaseLiteException(lastInsertedIndexCommand.Connection.ErrorMessage(), StatusCode.DbError);
                }
                resultCount = Convert.ToInt32(lastInsertedIndexCommand[0]);
                if (resultCount == -1)
                {
                    throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError);
                }
            } catch (Exception ex) {
                Log.E(Tag, "Error updating table " + table, ex);
            } finally {
                command.Dispose();
                if (lastInsertedIndexCommand != null)
                {
                    lastInsertedIndexCommand.Dispose();
                }
            }
            return(resultCount);
        }
Esempio n. 18
0
 private void materialRaisedButton1_Click(object sender, EventArgs e)
 {
     if (!rbAdmin.Checked && !rbStudent.Checked)
     {
         MessageBox.Show("Select Account Type!");
     }
     else if (txtUser.Text == "")
     {
         MessageBox.Show("Please Enter Username!");
     }
     else if (txtEmail.Text == "")
     {
         MessageBox.Show("Please Enter Email!");
     }
     else if (txtPassword.Text == "")
     {
         MessageBox.Show("Please Enter Password!");
     }
     else
     {
         if (lblID.Visible == true)
         {
             ContentValues values = new ContentValues();
             values.Add("Account_Type", rbAdmin.Checked ? "Admin" : "User");
             values.Add("Us", txtUser.Text);
             values.Add("Pass", txtPassword.Text);
             values.Add("Em", txtEmail.Text);
             database.Update("Signin", values, " ID = " + lblID.Text);
         }
         else
         {
             ContentValues values = new ContentValues();
             values.Add("Account_Type", rbAdmin.Checked ? "Admin" : "User");
             values.Add("Us", txtUser.Text);
             values.Add("Pass", txtPassword.Text);
             values.Add("Em", txtEmail.Text);
             database.Insert("Signin", values);
         }
     }
 }
Esempio n. 19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: EngagementReachInteractiveContent(CampaignId campaignId, android.content.ContentValues values) throws org.json.JSONException
        internal EngagementReachInteractiveContent(CampaignId campaignId, ContentValues values) : base(campaignId, values)
        {
            /* Base fields */

            /* Behavior */
            string deliveryTime = values.getAsString(DELIVERY_TIME);

            if (deliveryTime.Equals("s"))
            {
                mBehavior = Behavior.SESSION;
            }
            else
            {
                mBehavior = Behavior.ANYTIME;
            }

            /* Notification type */
            mSystemNotification = "s".Equals(values.getAsString(NOTIFICATION_TYPE));

            /* Is notification closeable? */
            mNotiticationCloseable = parseBoolean(values, NOTIFICATION_CLOSEABLE);

            /* Has notification icon? */
            mNotificationIcon = parseBoolean(values, NOTIFICATION_ICON);

            /* Sound and vibration */
            mNotificationSound   = parseBoolean(values, NOTIFICATION_SOUND);
            mNotificationVibrate = parseBoolean(values, NOTIFICATION_VIBRATION);

            /* Parse texts */
            mNotificationTitle   = values.getAsString(NOTIFICATION_TITLE);
            mNotificationMessage = values.getAsString(NOTIFICATION_MESSAGE);

            /* Big text */
            mNotificationBigText = values.getAsString(NOTIFICATION_BIG_TEXT);

            /* Big picture */
            mNotificationBigPicture = values.getAsString(NOTIFICATION_BIG_PICTURE);
        }
        /// <summary>
        /// The find.
        /// </summary>
        /// <param name="par">
        /// The par.
        /// </param>
        /// <returns>
        /// The <see cref="T:KeyValuePair{List{String},List{Int32}}"/>.
        /// </returns>
        public override sealed KeyValuePair<List<string>, List<int>>? Find(ContentValues par)
        {
            var convoluted = (ComplexChain)par.Get(Enum.GetName(typeof(Formalism), Formalism.Sequence));
            var windowLen = (int)par.Get(Enum.GetName(typeof(Parameter), Parameter.Window));
            var alphabet = (FrequencyDictionary)par.Get(Enum.GetName(typeof(Formalism), Formalism.Alphabet));
            var level = (double)par.Get(Enum.GetName(typeof(Parameter), Parameter.CurrentThreshold));

            int scanStep = 1;
            int disp = 0;

            var it = new StartIterator(convoluted, windowLen, scanStep);

            while (it.HasNext())
            {
                it.Next();
                fullEntry.Add(it, disp);
            }

            CalculateStd(convoluted, windowLen);

            return DiscardCompositeWords(alphabet, level);
        }
        private static void CreateInsertItems(long[] ids, int offset, int len, int b)
        {
            if (offset + len > ids.Length)
            {
                len = ids.Length - offset;
            }

            if (_valuesCache == null || _valuesCache.Length != len)
            {
                _valuesCache = new ContentValues[len];
            }

            for (int i = 0; i < len; i++)
            {
                if (_valuesCache[i] == null)
                {
                    _valuesCache[i] = new ContentValues();
                }
                _valuesCache[i].Put(Playlists.Members.PlayOrder, b + offset + i);
                _valuesCache[i].Put(Playlists.Members.AudioId, ids[offset + 1]);
            }
        }
Esempio n. 22
0
        public override Android.Net.Uri Insert(Android.Net.Uri uri, ContentValues values)
        {
            Android.Util.Log.Debug("Test", "Insert");
            //---add a new book---
            _s_DB = new VegetableDatabase(this.Context);
            var _database = _s_DB.WritableDatabase;

            _database.BeginTransaction();
            long rowID = _database.Insert(DATABASE_TABLE, "", values);

            //---if added successfully---
            if (rowID > 0)
            {
                var _uri = ContentUris.WithAppendedId(CONTENT_URI, rowID);
                Context.ContentResolver.NotifyChange(_uri, null);
                _database.SetTransactionSuccessful();
                _database.EndTransaction();
                return(_uri);
            }
            throw new SQLException("Failed to insert row into " + uri);
            //throw new NotImplementedException(); //Java.Lang.UnsupportedOperationException();
        }
Esempio n. 23
0
        void InitAddEvent()
        {
            var addSampleEvent = FindViewById <Button> (Resource.Id.addSampleEvent);

            addSampleEvent.Click += (sender, e) => {
                // Create Event code
                ContentValues eventValues = new ContentValues();
                eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId);
                eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test Event from M4A");
                eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is an event created from Mono for Android");
                eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(2011, 12, 15, 10, 0));
                eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(2011, 12, 15, 11, 0));

                // GitHub issue #9 : Event start and end times need timezone support.
                // https://github.com/xamarin/monodroid-samples/issues/9
                eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
                eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");

                var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues);
                Console.WriteLine("Uri for new event: {0}", uri);
            };
        }
Esempio n. 24
0
        void SetCalendarWeek()
        {
            ContentValues values = new ContentValues();

            values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1);
            values.Put(CalendarContract.Events.InterfaceConsts.Dtstart, (long)(workshop[0].StartDate.Date - new DateTime(1970, 1, 1)).TotalMilliseconds);
            values.Put(CalendarContract.Events.InterfaceConsts.Dtend, (long)(workshop[0].EndDate.Date - new DateTime(1970, 1, 1)).TotalMilliseconds);
            values.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
            values.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");
            values.Put(CalendarContract.Events.InterfaceConsts.Title, workshop[0].topic);
            values.Put(CalendarContract.Events.InterfaceConsts.Description, workshop[0].description);
            values.Put(CalendarContract.Events.InterfaceConsts.EventLocation, workshop[0].campus);
            var calendar = this.Activity.ContentResolver.Insert(CalendarContract.Events.ContentUri, values);
            var eventID  = long.Parse(calendar.LastPathSegment);

            ContentValues reminderValues = new ContentValues();

            reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 10080);
            reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID);
            reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, 1);
            var reminder = this.Activity.ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues);
        }
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The update command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="whereClause">Where clause.</param>
        /// <param name="whereArgs">Where arguments.</param>
        sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs)
        {
            var builder = new StringBuilder("UPDATE ");

            builder.Append(table);
            builder.Append(" SET ");

            // Append our content column names and create our SQL parameters.
            var valueSet       = values.ValueSet();
            var valueSetLength = valueSet.Count();

            var whereArgsLength = (whereArgs != null ? whereArgs.Length : 0);

            var index = 0;

            foreach (var column in valueSet)
            {
                if (index++ > 0)
                {
                    builder.Append(",");
                }
                builder.AppendFormat("{0} = @", column.Key);
            }

            if (!String.IsNullOrWhiteSpace(whereClause))
            {
                builder.Append(" WHERE ");
                builder.Append(whereClause);
            }

            var sql     = builder.ToString();
            var command = Connection.Prepare(sql);

            for (var i = 1; i <= whereArgs.Length; i++)
            {
                command.Bind(i, whereArgs[i - 1]);
            }
            return(command);
        }
Esempio n. 26
0
        public void WriteCorrectAnswers(List <QuestionModel> questions, int idLevel, int maxLevel)
        {
            SQLiteDatabase _objSQLiteDatabase = _sqliteUtil.WritableDatabase;

            foreach (var record in questions)
            {
                ContentValues cv = new ContentValues();
                cv.Put("IS_ANSWERED", record.IsAnswered ? 1 : 0);
                _objSQLiteDatabase.Update("QUESTIONS", cv, $"ID={record.IdQuestion}", null);
            }
            //unlock next level
            if (maxLevel < idLevel + 1)
            {
                //cannot increment MAX
            }
            else
            {
                ContentValues cv = new ContentValues();
                cv.Put("IS_LOCKED", 0);
                _objSQLiteDatabase.Update("LEVELS", cv, $"ID={idLevel+1}", null);
            }
        }
Esempio n. 27
0
        //Update Existing contact
        public void UpdatePersona(Persona personainfo)
        {
            if (personainfo == null)
            {
                return;
            }

            //Obtain writable database
            SQLiteDatabase db = this.WritableDatabase;

            //Prepare content values
            ContentValues vals = new ContentValues();

            vals.Put("identificacion", personainfo.identificacion);
            vals.Put("nombre", personainfo.nombre);
            vals.Put("apellidos", personainfo.apellidos);
            vals.Put("direccion", personainfo.direccion);
            vals.Put("correo", personainfo.correo);
            vals.Put("telefono", personainfo.telefono);
            vals.Put("fechaNac", personainfo.fechaNac.ToString());
            vals.Put("sexo", personainfo.sexo);
            vals.Put("estadoCivil", personainfo.estadoCivil);
            vals.Put("tipoSangre", personainfo.tipoSangre);
            vals.Put("detalle", personainfo.detalle);

            ICursor cursor = db.Query("Persona",
                                      new String[] { "id", "identificacion", "nombre", "apellidos", "direccion", "correo", "telefono", "fechaNac", "sexo", "estadoCivil", "tipoSangre", "detalle" }, "id=?", new string[] { personainfo.id.ToString() }, null, null, null, null);

            if (cursor != null)
            {
                if (cursor.MoveToFirst())
                {
                    // update the row
                    db.Update("Persona", vals, "id=?", new String[] { cursor.GetString(0) });
                }

                cursor.Close();
            }
        }
Esempio n. 28
0
        public override void OnReceive(Context context, Intent intent)
        {
            Intent resultIntent;
            int    id = Convert.ToInt32(intent.GetLongExtra("_id", 0));

            databasehelper = new Databasehelper(context);

            Db = databasehelper.WritableDatabase;

            resultIntent = new Intent(context, typeof(WriteActivity));
            resultIntent.PutExtra("_id", id.ToString());



            ContentValues cv = new ContentValues();

            cv.Put(Databasehelper.COLUMN_NOTIFY, 0);
            Db.Update(Databasehelper.TEXTTABLE, cv, "_id= ?", new string[] { id.ToString() });
            Db.ExecSQL("VACUUM");
            Android.App.PendingIntent resultPendingIntent = Android.App.PendingIntent.GetActivity(context, id, resultIntent,
                                                                                                  Android.App.PendingIntentFlags.UpdateCurrent);
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context, "ID")
                .SetSmallIcon(Android.Resource.Drawable.IcButtonSpeakNow)
                .SetContentTitle("Вам напоминание!")
                .SetContentText(intent.GetStringExtra("message"))
                .SetPriority((int)Android.App.NotificationPriority.Default)
                .SetContentIntent(resultPendingIntent)
                .SetAutoCancel(true)
            ;
            Android.App.NotificationManager manager = (Android.App.NotificationManager)context.GetSystemService(Context.NotificationService);

            Android.App.Notification notification = builder.Build();


            Multitools.createChannelIfNeeded(manager);
            manager.Notify(id, notification);
        }
Esempio n. 29
0
        public Task <string> CreateAlarmAsync(string title, string description, DateTime timeInit, DateTime timeEnd, int alarmMinutes)
        {
            TaskCompletionSource <string> tcs = new TaskCompletionSource <string>();

            GetSystemCalendar();
            if (defaultCalendarId == 0)
            {
                tcs.SetResult(string.Empty);
                return(tcs.Task);
            }

            ContentValues eventValues = new ContentValues();

            eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, defaultCalendarId);
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, title);
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, description);
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(timeInit));
            eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(timeEnd));
            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, System.TimeZone.CurrentTimeZone.StandardName);
            eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, System.TimeZone.CurrentTimeZone.StandardName);
            var uri = Application.Context.ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues);

            if (!long.TryParse(uri.LastPathSegment, out long eventID))
            {
                tcs.SetResult(string.Empty);
            }
            else
            {
                ContentValues reminderValues = new ContentValues();
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, alarmMinutes);
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID);
                reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, (int)RemindersMethod.Alarm);
                uri = Application.Context.ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues);
                tcs.SetResult(eventID.ToString());
            }

            return(tcs.Task);
        }
Esempio n. 30
0
        public void NewBeaconSignal(BeaconSignal beacon, string apointUid, DateTime time)
        {
            if (!Helper.TableExist(BeaconTableName))
            {
                Helper.CreateNewTable(BeaconTableName, Headers);
            }

            var cv = new ContentValues();

            cv.Put(MacAddressKey, beacon.Mac);
            cv.Put(RssiKey, beacon.Rssi);
            cv.Put(APointKey, apointUid);
            cv.Put(DateTimeKey, Tools.FormateDateTimeToTime(time));
            cv.Put(UuidKey, beacon.UUID);

            try
            {
                long rowIndex = Helper.WritableDatabase.Insert(BeaconTableName, null, cv);
            }
            catch (Exception exp)
            {
            }
        }
Esempio n. 31
0
        public void Update(Settings setting)
        {
            // New value for one column
            ContentValues values = new ContentValues();

            values.Put(FeedEntry.COLUMN_NAME_NAME, setting.Name.ToString());
            values.Put(FeedEntry.COLUMN_NAME_VAL_1, setting.Val_1);
            values.Put(FeedEntry.COLUMN_NAME_VAL_2, setting.Val_2);
            values.Put(FeedEntry.COLUMN_NAME_VAL_3, setting.Val_3);
            values.Put(FeedEntry.COLUMN_NAME_VAL_4, setting.Val_4);
            values.Put(FeedEntry.COLUMN_NAME_VAL_5, setting.Val_5);

            // Which row to update, based on the title
            String selection = FeedEntry.Id + " = ?";

            String[] selectionArgs = { setting.Id.ToString() };

            int count = db.Update(
                FeedEntry.TABLE_NAME,
                values,
                selection,
                selectionArgs);
        }
Esempio n. 32
0
        //Add New Auto
        public void AddNewAuto(Vehicle autoinfo)
        {
            SQLiteDatabase db   = this.WritableDatabase;
            ContentValues  vals = new ContentValues();

            vals.Put("Year", autoinfo.Year);
            vals.Put("Make", autoinfo.Make);
            vals.Put("Model", autoinfo.Model);
            vals.Put("Color", autoinfo.Color);
            vals.Put("Description", autoinfo.Description);
            vals.Put("PercentagePaint", autoinfo.PercentagePaint);
            vals.Put("PercentageBody", autoinfo.PercentageBody);
            vals.Put("PercentageGlass", autoinfo.PercentageGlass);
            vals.Put("PercentageTrim", autoinfo.PercentageTrim);
            vals.Put("PercentageUpholstery", autoinfo.PercentageUpholstery);
            vals.Put("PercentageMechanical", autoinfo.PercentageMechanical);
            vals.Put("PercentageElectrical", autoinfo.PercentageElectrical);
            vals.Put("PercentageFrame", autoinfo.PercentageFrame);
            vals.Put("PercentageTires", autoinfo.PercentageTires);
            vals.Put("PercentageOverall", autoinfo.PercentageOverall);

            db.Insert("Vehicle", null, vals);
        }
Esempio n. 33
0
            public void Test(string storagename, string volpath)
            {
                DocumentFile srcdoc = GetExistingDocumentFile(storagename, volpath);

                ShowUriInfos(srcdoc.Uri, Activity.ContentResolver);

                ContentResolver resolver = Activity.ContentResolver;


                ContentValues values = new ContentValues();

                values.Put("document_id", "14F1-0B07:tmp1/tmp2/test2.txt");
                values.Put("mime_type", "text/plain");
                values.Put("_display_name", "test2.txt");
                values.Put("last_modified", 1553853408000);
                values.Put("flags", 326);
                values.Put("_size", 20);
                //int res = resolver.Update(srcdoc.Uri, values, null, null);  // Exception: Update not supported

                values = new ContentValues();
                values.Put("abc", "xyz");
                //resolver.Insert(srcdoc.Uri, values); // Exception: Insert not supported
            }
        public void OnClickAddTask(View view)
        {
            string input = this.FindViewById <EditText>(Resource.Id.editTextTaskDescription).Text;

            if (string.IsNullOrEmpty(input))
            {
                return;
            }

            ContentValues contentValues = new ContentValues();

            contentValues.Put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, input);
            contentValues.Put(TaskContract.TaskEntry.COLUMN_PRIORITY, this.priority);

            Android.Net.Uri uri = this.ContentResolver.Insert(TaskContract.TaskEntry.CONTENT_URI, contentValues);

            if (uri != null)
            {
                Toast.MakeText(this.BaseContext, uri.ToString(), ToastLength.Long).Show();
            }

            Finish();
        }
        public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!StringEx.IsNullOrWhiteSpace(nullColumnHack))
            {
                var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(TAG));
                Log.E(TAG, "Unsupported use of nullColumnHack", e);
                throw e;
            }

            var t = Factory.StartNew(() =>
            {
                var lastInsertedId = -1L;
                var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);

                try
                {
                    LastErrorCode = command.step();
                    command.Dispose();
                    if (LastErrorCode == SQLiteResult.ERROR)
                        throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError);

                    int changes = _writeConnection.changes();
                    if (changes > 0)
                    {
                        lastInsertedId = _writeConnection.last_insert_rowid();
                    }

                    if (lastInsertedId == -1L)
                    {
                        if(conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) {
                            Log.E(TAG, "Error inserting " + initialValues + " using " + command);
                            throw new CouchbaseLiteException("Error inserting " + initialValues + " using " + command, StatusCode.DbError);
                        }
                    } else
                    {
                        Log.V(TAG, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues);
                    }

                } 
                catch (Exception ex)
                {
                    Log.E(TAG, "Error inserting into table " + table, ex);
                    LastErrorCode = raw.sqlite3_errcode(_writeConnection);
                    throw;
                }
                return lastInsertedId;
            });

            var r = t.ConfigureAwait(false).GetAwaiter().GetResult();
            if (t.Exception != null)
                throw t.Exception;

            return r;
        }
        public long InsertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!String.IsNullOrWhiteSpace(nullColumnHack)) {
                var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag));
                Log.E(Tag, "Unsupported use of nullColumnHack", e);
                throw e;
            }

            var lastInsertedId = -1L;
            var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);

            try {
                int result;
                lock (dbLock) {
                    result = command.step ();
                }
                if (result == SQLiteResult.ERROR)
                    throw new CouchbaseLiteException(raw.sqlite3_errmsg(db), StatusCode.DbError);

                int changes;
                lock (dbLock) {
                    changes = db.changes ();
                }
                if (changes > 0) 
                {
                    lock (dbLock) {
                        lastInsertedId = db.last_insert_rowid();
                    }
                }

                if (lastInsertedId == -1L) {
                    Log.E(Tag, "Error inserting " + initialValues + " using " + command);
                    throw new CouchbaseLiteException("Error inserting " + initialValues + " using " + command, StatusCode.DbError);
                } else {
                    Log.V(Tag, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues);
                }

            } catch (Exception ex) {
                Log.E(Tag, "Error inserting into table " + table, ex);
                throw;
            } finally {
                lock (dbLock) {
                    command.Dispose();
                }
            }

            return lastInsertedId;
        }
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The update command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="whereClause">Where clause.</param>
        /// <param name="whereArgs">Where arguments.</param>
        sqlite3_stmt GetUpdateCommand (string table, ContentValues values, string whereClause, string[] whereArgs)
        {
            if (!IsOpen)
            {
                Open(Path);
            }
            var builder = new StringBuilder("UPDATE ");

            builder.Append(table);
            builder.Append(" SET ");

            // Append our content column names and create our SQL parameters.
            var valueSet = values.ValueSet();
//            var valueSetLength = valueSet.Count();
//
//            var whereArgsLength = (whereArgs != null ? whereArgs.Length : 0);

            var paramList = new List<object>();

            var index = 0;
            foreach(var column in valueSet)
            {
                if (index++ > 0) {
                    builder.Append(",");
                }
                builder.AppendFormat("{0} = ?", column.Key);
                paramList.Add(column.Value);
            }

            if (!String.IsNullOrWhiteSpace(whereClause)) {
                builder.Append(" WHERE ");
                builder.Append(whereClause);
            }

            if (whereArgs != null)
            {
                foreach(var arg in whereArgs)
                {
                    paramList.Add(arg);
                }
            }

            var sql = builder.ToString();
            sqlite3_stmt command;
            lock (dbLock) { 
                command = db.prepare (sql);
                command.bind (paramList.ToArray<object> ());
            }

            return command;
        }
        public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (_readOnly) {
                throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG,
                    "Attempting to write to a readonly database");
            }

            if (!StringEx.IsNullOrWhiteSpace(nullColumnHack)) {
                throw new InvalidOperationException("Don't use nullColumnHack");
            }

            Log.To.TaskScheduling.V(TAG, "Scheduling InsertWithOnConflict");
            var t = Factory.StartNew(() =>
            {
                Log.To.TaskScheduling.V(TAG, "Running InsertWithOnConflict");
                var lastInsertedId = -1L;
                var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);

                try {
                    LastErrorCode = command.step();
                    command.Dispose();
                    if (LastErrorCode == raw.SQLITE_ERROR) {
                        throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG,
                            raw.sqlite3_errmsg(_writeConnection));
                    }

                    int changes = _writeConnection.changes();
                    if (changes > 0)
                    {
                        lastInsertedId = _writeConnection.last_insert_rowid();
                    }

                    if (lastInsertedId == -1L) {
                        if(conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) {
                            throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG,
                                "Error inserting {0} using {1}", initialValues, command);
                        }
                    } else {
                        Log.To.Database.V(TAG, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues);
                    }

                } 
                catch(CouchbaseLiteException) {
                    LastErrorCode = raw.sqlite3_errcode(_writeConnection);
                    Log.To.Database.E(TAG, "Error inserting into table {0}, rethrowing...", table);
                    throw;
                } catch (Exception ex) {
                    LastErrorCode = raw.sqlite3_errcode(_writeConnection);
                    throw Misc.CreateExceptionAndLog(Log.To.Database, ex, StatusCode.DbError, TAG, 
                        "Error inserting into table {0}", table);
                }

                return lastInsertedId;
            });

            var r = t.ConfigureAwait(false).GetAwaiter().GetResult();
            if (t.Exception != null)
                throw t.Exception;

            return r;
        }
 /// <summary>
 /// The update parameters.
 /// </summary>
 /// <param name="par">
 /// The par.
 /// </param>
 /// <param name="winLen">
 /// The win len.
 /// </param>
 private void UpdateParams(ContentValues par, int winLen)
 {
     par.Put(Formalism.Sequence.ToString(), convoluted.ToString());
     par.Put(Formalism.Alphabet.ToString(), alphabet.ToString());
     par.Put(Parameter.Window, winLen);
 }
        /// <summary>
        /// The slot.
        /// </summary>
        public new void Slot()
        {
            var par = new ContentValues();
            par.Put(Formalism.Sequence, chain = new ComplexChain(inputs[0].Chain));
            par.Put(Formalism.Alphabet, alphabet = new FrequencyDictionary(chain));

            while (criterion.State(chain, alphabet))
            {
                UpdateParams(par, threshold.Next(criterion));
                var chainSplitter = new SimpleChainSplitter(extractor);
                chain = chainSplitter.Cut(par);
                alphabet = chainSplitter.FrequencyDictionary;
            }
        }
        public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs)
        {
            if (_readOnly) {
                throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG,
                    "Attempting to write to a readonly database");
            }

            Debug.Assert(!StringEx.IsNullOrWhiteSpace(table));
            Debug.Assert(values != null);

            Log.To.TaskScheduling.V(TAG, "Scheduling Update");
            var t = Factory.StartNew(() =>
            {
                Log.To.TaskScheduling.V(TAG, "Running Update");
                var resultCount = 0;
                var command = GetUpdateCommand(table, values, whereClause, whereArgs);
                try
                {
                    LastErrorCode = command.step();
                    if (LastErrorCode == raw.SQLITE_ERROR)
                        throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection),
                            StatusCode.DbError);
                }
                catch (ugly.sqlite3_exception ex)
                {
                    LastErrorCode = raw.sqlite3_errcode(_writeConnection);
                    var msg = raw.sqlite3_extended_errcode(_writeConnection);
                    Log.To.Database.E(TAG, String.Format("Error {0}: \"{1}\" while updating table {2}", ex.errcode, msg, table), ex);
                }

                resultCount = _writeConnection.changes();
                if (resultCount < 0)
                {
                    throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG,
                        "Error updating {0} with command '{1}'", values, command);
                }
                command.Dispose();
                return resultCount;
            }, CancellationToken.None);

            // NOTE.ZJG: Just a sketch here. Needs better error handling, etc.

            //doesn't look good
            var r = t.ConfigureAwait(false).GetAwaiter().GetResult();
            if (t.Exception != null)
                throw t.Exception;
            
            return r;
        }
 /// <summary>
 /// The update parameters.
 /// </summary>
 /// <param name="par">
 /// The par.
 /// </param>
 /// <param name="nextThreshold">
 /// The next threshold.
 /// </param>
 private void UpdateParams(ContentValues par, double nextThreshold)
 {
     par.Put(Formalism.Sequence, chain = new ComplexChain(inputs[0].Chain));
     par.Put(Parameter.Balance, balance);
     par.Put(Parameter.Window, windowLen);
     par.Put(Parameter.WindowDecrement, windowDec);
     par.Put(Parameter.CurrentThreshold, nextThreshold);
 }
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The insert command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param>
        sqlite3_stmt GetInsertCommand(String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!IsOpen) {
                throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG,
                    "GetInsertCommand called on closed database");
            }

            var builder = new StringBuilder("INSERT");

            if (conflictResolutionStrategy != ConflictResolutionStrategy.None)
            {
                builder.Append(" OR ");
                builder.Append(conflictResolutionStrategy);
            }

            builder.Append(" INTO ");
            builder.Append(table);
            builder.Append(" (");

            // Append our content column names and create our SQL parameters.
            var valueSet = values.ValueSet();
            var valueBuilder = new StringBuilder();
            var index = 0;

            var args = new object[valueSet.Count];

            foreach (var column in valueSet)
            {
                if (index > 0)
                {
                    builder.Append(",");
                    valueBuilder.Append(",");
                }

                builder.AppendFormat("{0}", column.Key);
                valueBuilder.Append("?");

                args[index] = column.Value;

                index++;
            }

            builder.Append(") VALUES (");
            builder.Append(valueBuilder);
            builder.Append(")");

            var sql = builder.ToString();
            sqlite3_stmt command = null;
            if (args != null) {
                Log.To.Database.V(TAG, "Preparing statement: '{0}' with values: {1}", sql, new SecureLogJsonString(args, LogMessageSensitivity.PotentiallyInsecure));
            } else {
                Log.To.Database.V(TAG, "Preparing statement: '{0}'", sql);
            }

            command = BuildCommand(_writeConnection, sql, args);

            return command;
        }
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The insert command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param>
        sqlite3_stmt GetInsertCommand (String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!IsOpen)
            {
                Open(Path);
            }
            var builder = new StringBuilder("INSERT");

            if (conflictResolutionStrategy != ConflictResolutionStrategy.None) {
                builder.Append(" OR ");
                builder.Append(conflictResolutionStrategy);
            }

            builder.Append(" INTO ");
            builder.Append(table);
            builder.Append(" (");

            // Append our content column names and create our SQL parameters.
            var valueSet = values.ValueSet();
            var valueBuilder = new StringBuilder();
            var index = 0;

            var args = new object[valueSet.Count];

            foreach(var column in valueSet)
            {
                if (index > 0) {
                    builder.Append(",");
                    valueBuilder.Append(",");
                }

                builder.AppendFormat( "{0}", column.Key);
                valueBuilder.Append("?");

                args[index] = column.Value;

                index++;
            }

            builder.Append(") VALUES (");
            builder.Append(valueBuilder);
            builder.Append(")");

            var sql = builder.ToString();
            sqlite3_stmt command;
            lock (dbLock) {
                command = db.prepare (sql);
                command.bind (args);
            }

            return command;
        }
 /// <summary>
 /// The cut.
 /// </summary>
 /// <param name="par">
 /// The par.
 /// </param>
 /// <returns>
 /// The <see cref="ComplexChain"/>.
 /// </returns>
 public abstract ComplexChain Cut(ContentValues par);
        public int Update (String table, ContentValues values, String whereClause, params String[] whereArgs)
        {
            Debug.Assert(!String.IsNullOrWhiteSpace(table));
            Debug.Assert(values != null);

            var resultCount = 0;
            lock (dbLock) {
                var command = GetUpdateCommand(table, values, whereClause, whereArgs);
                try {
                    var result = command.step();
                    if (result == SQLiteResult.ERROR)
                        throw new CouchbaseLiteException(raw.sqlite3_errmsg(db), StatusCode.DbError);

                    resultCount = db.changes();
                    if (resultCount < 0) 
                    {
                        Log.E(Tag, "Error updating " + values + " using " + command);
                        throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError);
                    }
                } catch (Exception ex) {
                    Log.E(Tag, "Error updating table " + table, ex);
                    throw;
                } finally {
                    command.Dispose();
                }
            }
            return resultCount;
        }
 /// <summary>Adds all values from the passed in ContentValues.</summary>
 /// <param name="other">the ContentValues from which to copy</param>
 public void PutAll(ContentValues other)
 {
     mValues.PutAll(other.mValues);
 }
 /// <summary>
 /// Finds a word based on current parameters.
 /// </summary>
 /// <param name="parameters">
 /// The current segmentation parameters.
 /// </param>
 /// <returns>
 /// The <see cref="T:KeyValuePair{List{string},List{int}}?"/>.
 /// </returns>
 public abstract KeyValuePair<List<string>, List<int>>? Find(ContentValues parameters);
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The update command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="whereClause">Where clause.</param>
        /// <param name="whereArgs">Where arguments.</param>
        sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs)
        {
            if (!IsOpen)
            {
                Open(Path);
            }
            var builder = new StringBuilder("UPDATE ");

            builder.Append(table);
            builder.Append(" SET ");

            // Append our content column names and create our SQL parameters.
            var valueSet = values.ValueSet();

            var paramList = new List<object>();

            var index = 0;
            foreach (var column in valueSet)
            {
                if (index++ > 0)
                {
                    builder.Append(",");
                }
                builder.AppendFormat("{0} = ?", column.Key);
                paramList.Add(column.Value);
            }

            if (!StringEx.IsNullOrWhiteSpace(whereClause))
            {
                builder.Append(" WHERE ");
                builder.Append(whereClause);
            }

            if (whereArgs != null)
            {
                paramList.AddRange(whereArgs);
            }

            var sql = builder.ToString();
            var command = BuildCommand(_writeConnection, sql, paramList.ToArray<object>());

            return command;
        }
 public long Insert(String table, String nullColumnHack, ContentValues values)
 {
     return InsertWithOnConflict(table, null, values, ConflictResolutionStrategy.None);
 }
	  /// <summary>
	  /// Parse a datapush. </summary>
	  /// <param name="campaignId"> already parsed campaign id. </param>
	  /// <param name="values"> campaign data. </param>
	  /// <param name="params"> special parameters to inject in the body of the datapush. </param>
	  /// <exception cref="JSONException"> if payload parsing error occurs. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: EngagementDataPush(CampaignId campaignId, android.content.ContentValues values, java.util.Map<String, String> params) throws org.json.JSONException
	  internal EngagementDataPush(CampaignId campaignId, ContentValues values, IDictionary<string, string> @params) : base(campaignId, values)
	  {
		this.@params = @params;
		replacePayloadParams();
	  }
        public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs)
        {
            Debug.Assert(!StringEx.IsNullOrWhiteSpace(table));
            Debug.Assert(values != null);

            var t = Factory.StartNew(() =>
            {
                var resultCount = 0;
                var command = GetUpdateCommand(table, values, whereClause, whereArgs);
                try
                {
                    LastErrorCode = command.step();
                    if (LastErrorCode == SQLiteResult.ERROR)
                        throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection),
                            StatusCode.DbError);
                }
                catch (ugly.sqlite3_exception ex)
                {
                    LastErrorCode = raw.sqlite3_errcode(_writeConnection);
                    var msg = raw.sqlite3_extended_errcode(_writeConnection);
                    Log.E(TAG, "Error {0}: \"{1}\" while updating table {2}\r\n{3}", ex.errcode, msg, table, ex);
                }

                resultCount = _writeConnection.changes();
                if (resultCount < 0)
                {
                    Log.E(TAG, "Error updating " + values + " using " + command);
                    throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError);
                }
                command.Dispose();
                return resultCount;
            }, CancellationToken.None);

            // NOTE.ZJG: Just a sketch here. Needs better error handling, etc.

            //doesn't look good
            var r = t.ConfigureAwait(false).GetAwaiter().GetResult();
            if (t.Exception != null)
                throw t.Exception;
            
            return r;
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: EngagementReachInteractiveContent(CampaignId campaignId, android.content.ContentValues values) throws org.json.JSONException
	  internal EngagementReachInteractiveContent(CampaignId campaignId, ContentValues values) : base(campaignId, values)
	  {
		/* Base fields */

		/* Behavior */
		string deliveryTime = values.getAsString(DELIVERY_TIME);
		if (deliveryTime.Equals("s"))
		{
		  mBehavior = Behavior.SESSION;
		}
		else
		{
		  mBehavior = Behavior.ANYTIME;
		}

		/* Notification type */
		mSystemNotification = "s".Equals(values.getAsString(NOTIFICATION_TYPE));

		/* Is notification closeable? */
		mNotiticationCloseable = parseBoolean(values, NOTIFICATION_CLOSEABLE);

		/* Has notification icon? */
		mNotificationIcon = parseBoolean(values, NOTIFICATION_ICON);

		/* Sound and vibration */
		mNotificationSound = parseBoolean(values, NOTIFICATION_SOUND);
		mNotificationVibrate = parseBoolean(values, NOTIFICATION_VIBRATION);

		/* Parse texts */
		mNotificationTitle = values.getAsString(NOTIFICATION_TITLE);
		mNotificationMessage = values.getAsString(NOTIFICATION_MESSAGE);

		/* Big text */
		mNotificationBigText = values.getAsString(NOTIFICATION_BIG_TEXT);

		/* Big picture */
		mNotificationBigPicture = values.getAsString(NOTIFICATION_BIG_PICTURE);
	  }
        /// <summary>
        /// Avoids the additional database trip that using SqliteCommandBuilder requires.
        /// </summary>
        /// <returns>The insert command.</returns>
        /// <param name="table">Table.</param>
        /// <param name="values">Values.</param>
        /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param>
        sqlite3_stmt GetInsertCommand(String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!IsOpen)
            {
                Open(Path);
            }
            var builder = new StringBuilder("INSERT");

            if (conflictResolutionStrategy != ConflictResolutionStrategy.None)
            {
                builder.Append(" OR ");
                builder.Append(conflictResolutionStrategy);
            }

            builder.Append(" INTO ");
            builder.Append(table);
            builder.Append(" (");

            // Append our content column names and create our SQL parameters.
            var valueSet = values.ValueSet();
            var valueBuilder = new StringBuilder();
            var index = 0;

            var args = new object[valueSet.Count];

            foreach (var column in valueSet)
            {
                if (index > 0)
                {
                    builder.Append(",");
                    valueBuilder.Append(",");
                }

                builder.AppendFormat("{0}", column.Key);
                valueBuilder.Append("?");

                args[index] = column.Value;

                index++;
            }

            builder.Append(") VALUES (");
            builder.Append(valueBuilder);
            builder.Append(")");

            var sql = builder.ToString();
            sqlite3_stmt command = null;
            if (args != null)
            {
                Log.D(TAG, "Preparing statement: '{0}' with values: {1}", sql, String.Join(", ", args.Select(o => o == null ? "null" : o.ToString()).ToArray()));
            }
            else
            {
                Log.D(TAG, "Preparing statement: '{0}'", sql);
            }

            command = BuildCommand(_writeConnection, sql, args);

            return command;
        }
 /// <summary>
 /// Creates a set of values copied from the given set
 /// </summary>
 /// <param name="from">The values to copy</param>
 public ContentValues(ContentValues from)
 {
     mValues = new Dictionary<string, object>(from.mValues);
 }
        public void TestUpgradeMD5()
        {
            var store = database.Storage as SqliteCouchStore;
            if (store == null) {
                Assert.Inconclusive("This test is only valid for a SQLite based store, since any others will be too new to see this issue");
            }

            using (var client = new HttpClient()) {
                var couchDbUri = String.Format("http://{0}:5984/", GetReplicationServer());

                try {
                    var request = new HttpRequestMessage(HttpMethod.Get, new Uri(couchDbUri));
                    client.SendAsync(request).Wait();
                } catch (Exception) {
                    Assert.Inconclusive("Apache CouchDB not running");
                }

                var dbName = "a" + Misc.CreateGUID();
                var putRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(couchDbUri + dbName));
                var response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);


                // The API prevents new insertions with MD5 hashes, so we need to insert this bypassing the API
                // to simulate a legacy document
                var engine = store.StorageEngine;
                var docName = "doc" + Convert.ToString(DateTime.UtcNow.ToMillisecondsSinceEpoch());
                var contentVals = new ContentValues();
                contentVals["docid"] = docName;
                engine.Insert("docs", null, contentVals);

                contentVals = new ContentValues();
                contentVals["doc_id"] = 1;
                contentVals["revid"] = "1-1153b140e4c8674e2e6425c94de860a0";
                contentVals["current"] = false;
                contentVals["deleted"] = false;
                contentVals["no_attachments"] = true;
                string json = "{\"foo\":false}";
                contentVals["json"] = Encoding.UTF8.GetBytes(json);
                engine.Insert("revs", null, contentVals);

                contentVals = new ContentValues();
                contentVals["doc_id"] = 1;
                contentVals["revid"] = "2-bb71ce0da1de19f848177525c4ae5a8b";
                contentVals["current"] = false;
                contentVals["deleted"] = false;
                contentVals["no_attachments"] = false;
                contentVals["parent"] = 1;
                json = "{\"foo\":false,\"_attachments\":{\"attachment\":{\"content_type\":\"image/png\",\"revpos\":2," +
                "\"digest\":\"md5-ks1IBwCXbuY7VWAO9CkEjA==\",\"length\":519173,\"stub\":true}}}";
                contentVals["json"] = Encoding.UTF8.GetBytes(json);
                engine.Insert("revs", null, contentVals);

                contentVals = new ContentValues();
                contentVals["doc_id"] = 1;
                contentVals["revid"] = "3-a020d6aae370ab5cbc136c477f4e5928";
                contentVals["current"] = true;
                contentVals["deleted"] = false;
                contentVals["no_attachments"] = false;
                contentVals["parent"] = 2;
                json = "{\"foo\":true,\"_attachments\":{\"attachment\":{\"content_type\":\"image/png\",\"revpos\":2," +
                "\"digest\":\"md5-ks1IBwCXbuY7VWAO9CkEjA==\",\"length\":519173,\"stub\":true}}}";
                contentVals["json"] = Encoding.UTF8.GetBytes(json);
                engine.Insert("revs", null, contentVals);

                var attachmentStream = (InputStream)GetAsset("attachment.png");
                var fileStream = File.OpenWrite(Path.Combine(database.AttachmentStorePath, "92CD480700976EE63B55600EF429048C.blob"));
                attachmentStream.Wrapped.CopyTo(fileStream);
                attachmentStream.Dispose();
                fileStream.Dispose();

                var baseEndpoint = String.Format("http://{0}:5984/{1}/{2}", GetReplicationServer(), dbName, docName);
                var endpoint = baseEndpoint;
                putRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(endpoint));
                putRequest.Content = new StringContent("{\"foo\":false}");
                putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);


                attachmentStream = (InputStream)GetAsset("attachment.png");
                var baos = new MemoryStream();
                attachmentStream.Wrapped.CopyTo(baos);
                attachmentStream.Dispose();
                endpoint = baseEndpoint + "/attachment?rev=1-1153b140e4c8674e2e6425c94de860a0";

                putRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(endpoint));
                putRequest.Content = new ByteArrayContent(baos.ToArray());
                putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                baos.Dispose();
                response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                endpoint = baseEndpoint + "?rev=2-bb71ce0da1de19f848177525c4ae5a8b";
                putRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(endpoint));
                putRequest.Content = new StringContent("{\"foo\":true,\"_attachments\":{\"attachment\":{\"content_type\":\"image/png\",\"revpos\":2,\"digest\":\"md5-ks1IBwCXbuY7VWAO9CkEjA==\",\"length\":519173,\"stub\":true}}}");
                putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                var pull = database.CreatePullReplication(new Uri(couchDbUri + dbName));
                pull.Continuous = true;
                pull.Start();

                endpoint = baseEndpoint + "?rev=3-a020d6aae370ab5cbc136c477f4e5928";
                putRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(endpoint));
                putRequest.Content = new StringContent("{\"foo\":false,\"_attachments\":{\"attachment\":{\"content_type\":\"image/png\",\"revpos\":2,\"digest\":\"md5-ks1IBwCXbuY7VWAO9CkEjA==\",\"length\":519173,\"stub\":true}}}");
                putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                Sleep(1000);
                while (pull.Status == ReplicationStatus.Active) {
                    Sleep(500);
                }

                var doc = database.GetExistingDocument(docName);
                Assert.AreEqual("4-a91f8875144c6162874371c07a08ea17", doc.CurrentRevisionId);
                var attachment = doc.CurrentRevision.Attachments.ElementAtOrDefault(0);
                Assert.IsNotNull(attachment);
                var attachmentsDict = doc.GetProperty("_attachments").AsDictionary<string, object>();
                var attachmentDict = attachmentsDict.Get("attachment").AsDictionary<string, object>();
                Assert.AreEqual("md5-ks1IBwCXbuY7VWAO9CkEjA==", attachmentDict["digest"]);

                var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, baseEndpoint + "/attachment?rev=4-a91f8875144c6162874371c07a08ea17");
                response = client.SendAsync(deleteRequest).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

                attachmentStream = (InputStream)GetAsset("attachment2.png");
                baos = new MemoryStream();
                attachmentStream.Wrapped.CopyTo(baos);
                attachmentStream.Dispose();
                endpoint = baseEndpoint + "/attachment?rev=5-4737cb66c6a7ef1b11e872cb6fa4d51a";

                putRequest = new HttpRequestMessage(HttpMethod.Put, endpoint);
                putRequest.Content = new ByteArrayContent(baos.ToArray());
                putRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                baos.Dispose();
                response = client.SendAsync(putRequest).Result;
                Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

                Sleep(1000);
                while (pull.Status == ReplicationStatus.Active) {
                    Sleep(500);
                }

                doc = database.GetExistingDocument(docName);
                Assert.AreEqual("6-e3a7423a9a9de094a0d12d7f3b44634c", doc.CurrentRevisionId);
                attachment = doc.CurrentRevision.Attachments.ElementAtOrDefault(0);
                Assert.IsNotNull(attachment);
                attachmentsDict = doc.GetProperty("_attachments").AsDictionary<string, object>();
                attachmentDict = attachmentsDict.Get("attachment").AsDictionary<string, object>();
                Assert.AreEqual("sha1-9ijdmMf0mK7c11WQPw7DBQcX5pE=", attachmentDict["digest"]);

                deleteRequest = new HttpRequestMessage(HttpMethod.Delete, couchDbUri + dbName);
                response = client.SendAsync(deleteRequest).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
	  /// <summary>
	  /// Parse a notification announcement. </summary>
	  /// <param name="campaignId"> already parsed campaign id. </param>
	  /// <param name="values"> campaign data. </param>
	  /// <param name="params"> special parameters to inject in the action URL of the announcement. </param>
	  /// <exception cref="JSONException"> if a parsing error occurs. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: EngagementNotifAnnouncement(CampaignId campaignId, android.content.ContentValues values, java.util.Map<String, String> params) throws org.json.JSONException
	  internal EngagementNotifAnnouncement(CampaignId campaignId, ContentValues values, IDictionary<string, string> @params) : base(campaignId, values, @params)
	  {
	  }