static void Ping(List pings)
 {
     var ping = pings.AddItem(new ListItemCreationInformation());
     ping["Title"] = DateTime.Now.ToUniversalTime();
     ping.Update();
     pings.Context.ExecuteQuery();
 }
		public virtual void TestNonRecursiveFiltering()
		{
			ObjectInserter odi = db.NewObjectInserter();
			ObjectId aSth = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString(
				"a.sth"));
			ObjectId aTxt = odi.Insert(Constants.OBJ_BLOB, Sharpen.Runtime.GetBytesForString(
				"a.txt"));
			DirCache dc = db.ReadDirCache();
			DirCacheBuilder builder = dc.Builder();
			DirCacheEntry aSthEntry = new DirCacheEntry("a.sth");
			aSthEntry.FileMode = FileMode.REGULAR_FILE;
			aSthEntry.SetObjectId(aSth);
			DirCacheEntry aTxtEntry = new DirCacheEntry("a.txt");
			aTxtEntry.FileMode = FileMode.REGULAR_FILE;
			aTxtEntry.SetObjectId(aTxt);
			builder.Add(aSthEntry);
			builder.Add(aTxtEntry);
			builder.Finish();
			ObjectId treeId = dc.WriteTree(odi);
			odi.Flush();
			TreeWalk tw = new TreeWalk(db);
			tw.Filter = PathSuffixFilter.Create(".txt");
			tw.AddTree(treeId);
			IList<string> paths = new List<string>();
			while (tw.Next())
			{
				paths.AddItem(tw.PathString);
			}
			IList<string> expected = new List<string>();
			expected.AddItem("a.txt");
			NUnit.Framework.Assert.AreEqual(expected, paths);
		}
        public void AddDeaultData(ClientContext context, List list)
        {
            for (int i = 1; i <= 5; i++)
            {
                // Add a list item
                var itemInfo = new ListItemCreationInformation
                {
                    LeafName = string.Format("List Item {0}", i)
                };
                var item = list.AddItem(itemInfo);
                item["My_x0020_Number1"] = 100 + i;
                item["My_x0020_Number2"] = i;
                item.Update();
            }

            context.ExecuteQuery();
        }
Example #4
0
 /// <summary>
 /// Adds list item in specified list.
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="list">Name of the list</param>
 /// <param name="columns">List of column names</param>
 /// <param name="values">Values for corresponding columns</param>
 /// <returns>String stating success flag</returns>
 public static bool AddItem(ClientContext clientContext, List list, IList<string> columns, IList<object> values)
 {
     bool result = false;
     if (null != clientContext && null != list && null != columns && null != values && columns.Count == values.Count)
     {
         // Add the Matter URL in list
         ListItemCreationInformation listItemCreateInfo = new ListItemCreationInformation();
         ListItem newListItem = list.AddItem(listItemCreateInfo);
         int position = 0;
         foreach (string column in columns)
         {
             newListItem[column] = values[position++];
         }
         ///// Update the list
         newListItem.Update();
         clientContext.ExecuteQuery();
         result = true;
     }
     return result;
 }
        internal override void ProcessInbox(RevisionList inbox)
        {
            if (Status == ReplicationStatus.Offline) {
                Log.V(TAG, "Offline, so skipping inbox process");
                return;
            }

            if(_requests.Count > ManagerOptions.Default.MaxOpenHttpConnections) {
                Task.Delay(1000).ContinueWith(t => ProcessInbox(inbox), CancellationToken.None, TaskContinuationOptions.None, WorkExecutor.Scheduler);
                return;
            }

            SafeAddToChangesCount(inbox.Count);
            // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
            // <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
            var diffs = new Dictionary<String, IList<String>>();
            foreach (var rev in inbox) {
                var docID = rev.GetDocId();
                var revs = diffs.Get(docID);
                if (revs == null) {
                    revs = new List<String>();
                    diffs[docID] = revs;
                }
                revs.AddItem(rev.GetRevId());
                AddPending(rev);
            }

            // Call _revs_diff on the target db:
            Log.D(TAG, "posting to /_revs_diff: {0}", String.Join(Environment.NewLine, new[] { Manager.GetObjectMapper().WriteValueAsString(diffs) }));

            SendAsyncRequest(HttpMethod.Post, "/_revs_diff", diffs, (response, e) =>
            {
                try {
                    var results = response.AsDictionary<string, object>();

                    Log.D(TAG, "/_revs_diff response: {0}\r\n{1}", response, results);

                    if (e != null) {
                        LastError = e;
                        RevisionFailed();
                    } else {
                        if (results.Count != 0)  {
                            // Go through the list of local changes again, selecting the ones the destination server
                            // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
                            var docsToSend = new List<object> ();
                            var revsToSend = new RevisionList();
                            foreach (var rev in inbox) {
                                // Is this revision in the server's 'missing' list?
                                IDictionary<string, object> properties = null;
                                var revResults = results.Get(rev.GetDocId()).AsDictionary<string, object>(); 
                                if (revResults == null) {
                                    SafeIncrementCompletedChangesCount();
                                    continue;
                                }

                                var revs = revResults.Get("missing").AsList<string>();
                                if (revs == null || !revs.Any( id => id.Equals(rev.GetRevId(), StringComparison.OrdinalIgnoreCase))) {
                                    RemovePending(rev);
                                    SafeIncrementCompletedChangesCount();
                                    continue;
                                }

                                // Get the revision's properties:
                                var contentOptions = DocumentContentOptions.IncludeAttachments;
                                if (!_dontSendMultipart && RevisionBodyTransformationFunction == null)
                                {
                                    contentOptions |= DocumentContentOptions.BigAttachmentsFollow;
                                }


                                RevisionInternal loadedRev;
                                try {
                                    loadedRev = LocalDatabase.LoadRevisionBody (rev);
                                    properties = new Dictionary<string, object>(rev.GetProperties());
                                } catch (CouchbaseLiteException e1) {
                                    Log.W(TAG, string.Format("{0} Couldn't get local contents of {1}", rev, this), e1);
                                    RevisionFailed();
                                    continue;
                                }

                                var populatedRev = TransformRevision(loadedRev);
                                IList<string> possibleAncestors = null;
                                if (revResults.ContainsKey("possible_ancestors")) {
                                    possibleAncestors = revResults["possible_ancestors"].AsList<string>();
                                }

                                properties = new Dictionary<string, object>(populatedRev.GetProperties());
                                var history = LocalDatabase.GetRevisionHistory(populatedRev, possibleAncestors);
                                properties["_revisions"] = Database.MakeRevisionHistoryDict(history);
                                populatedRev.SetProperties(properties);

                                // Strip any attachments already known to the target db:
                                if (properties.ContainsKey("_attachments")) {
                                    // Look for the latest common ancestor and stuf out older attachments:
                                    var minRevPos = FindCommonAncestor(populatedRev, possibleAncestors);
                                    Status status = new Status();
                                    if(!LocalDatabase.ExpandAttachments(populatedRev, minRevPos + 1, !_dontSendMultipart, false, status)) {
                                        Log.W(TAG, "Error expanding attachments!");
                                        RevisionFailed();
                                        continue;
                                    }

                                    properties = populatedRev.GetProperties();
                                    if (!_dontSendMultipart && UploadMultipartRevision(populatedRev)) {
                                        continue;
                                    }
                                }

                                if (properties == null || !properties.ContainsKey("_id")) {
                                    throw new InvalidOperationException("properties must contain a document _id");
                                }

                                // Add the _revisions list:
                                revsToSend.Add(rev);

                                //now add it to the docs to send
                                docsToSend.AddItem (properties);
                            }

                            UploadBulkDocs(docsToSend, revsToSend);
                        } else {
                            foreach (var revisionInternal in inbox) {
                                RemovePending(revisionInternal);
                            }

                            SafeAddToCompletedChangesCount(inbox.Count);
                        }
                    }
                } catch (Exception ex) {
                    Log.E(TAG, "Unhandled exception in Pusher.ProcessInbox", ex);
                }
            });
        }
        private static void MigrateContent_List(ClientContext clientContext, List listToBeReplaced, List newList)
        {
            try
            {
                ListItemCollection sourceListItems = listToBeReplaced.GetItems(CamlQuery.CreateAllItemsQuery());
                FieldCollection sourceListFields = listToBeReplaced.Fields;

                clientContext.Load(sourceListItems, sListItems => sListItems.IncludeWithDefaultProperties(li => li.AttachmentFiles));
                clientContext.Load(sourceListFields);
                clientContext.ExecuteQuery();

                var sourceItemEnumerator = sourceListItems.GetEnumerator();
                while (sourceItemEnumerator.MoveNext())
                {
                    var sourceItem = sourceItemEnumerator.Current;
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem targetItem = newList.AddItem(itemCreateInfo);
                    object sourceModifiedDate = null;
                    object sourceModifiledBy = null;

                    foreach (Field sourceListField in sourceListFields)
                    {
                        try
                        {
                            //[START]Copy all except Attachments,ReadOnlyField,ContentType
                            if (!sourceListField.ReadOnlyField && sourceListField.InternalName != "Attachments" && sourceListField.InternalName != "ContentType" && null != sourceItem[sourceListField.InternalName])
                            {
                                //[START] Calendar and Event List
                                if (listToBeReplaced.BaseTemplate.ToString().Equals("106"))
                                {
                                    if (sourceListField.InternalName.Equals("EndDate"))
                                    {
                                        continue;
                                    }
                                    else if (sourceListField.InternalName.Equals("EventDate"))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem["EndDate"] = sourceItem["EndDate"];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                    else if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                }
                                //[END] Calendar and Event List
                                else
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                        //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                                        targetItem = newList.GetItemById(targetItem.Id);
                                        clientContext.Load(targetItem);
                                        clientContext.ExecuteQuery();
                                        //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                                    }
                                }
                            }
                            //[END]Copy all except Attachments, ReadOnlyField, ContentType

                            //Created, Author Field
                            if (sourceItem.FieldValues.Keys.Contains(sourceListField.InternalName))
                            {
                                //Created By
                                if (sourceListField.InternalName.Equals("Author"))
                                {
                                    //newList.Fields.GetByInternalNameOrTitle("Author").ReadOnlyField = false;
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                    }
                                }
                                //Created Date
                                if (sourceListField.InternalName.Equals("Created"))
                                {
                                    //newList.Fields.GetByInternalNameOrTitle("Created").ReadOnlyField = false;
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName];
                                        targetItem.Update();
                                        clientContext.ExecuteQuery();
                                    }
                                }

                                //Modified Date
                                if (sourceListField.InternalName.Equals("Modified"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        sourceModifiedDate = sourceItem["Modified"];
                                    }
                                }
                                //Modified By
                                if (sourceListField.InternalName.Equals("Editor"))
                                {
                                    if (ContainsField(newList, sourceListField.InternalName))
                                    {
                                        sourceModifiledBy = sourceItem["Editor"];
                                    }
                                }
                            }
                            //Created, Author Field
                        }
                        catch (Exception ex)
                        {
                            ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Items", ex.GetType().ToString(), "Not initialized: " + sourceListField.Title);
                            Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List]  Copy Items, Exception Message: " + ex.Message + ", Exception Comment: Not initialized: " + sourceListField.Title);

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("[EXCEPTION] [MigrateContent_List]  Copy Items, Exception Message: " + ex.Message + ", ExceptionComments: Not initialized: " + sourceListField.Title);
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                    }

                    #region Copy Attachments

                    //Copy attachments
                   foreach (Attachment fileName in sourceItem.AttachmentFiles)
                    {
                        try
                        {
                            Microsoft.SharePoint.Client.File oAttachment = clientContext.Web.GetFileByServerRelativeUrl(fileName.ServerRelativeUrl);
                            clientContext.Load(oAttachment);
                            clientContext.ExecuteQuery();

                            FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, oAttachment.ServerRelativeUrl);
                            AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation();

                            Byte[] buffer = new Byte[oAttachment.Length];
                            int bytesRead = fInfo.Stream.Read(buffer, 0, buffer.Length);

                            MemoryStream stream = new MemoryStream(buffer);
                            attachFileInfo.ContentStream = stream;
                            attachFileInfo.FileName = oAttachment.Name;
                            targetItem.AttachmentFiles.Add(attachFileInfo);
                            targetItem.Update();
                            clientContext.ExecuteQuery();
                            stream.Dispose();

                            //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                            targetItem = newList.GetItemById(targetItem.Id);
                            clientContext.Load(targetItem);
                            clientContext.ExecuteQuery();
                            //[END] [Load "Target Items" After Update, to avoid Version Conflict]
                        }
                        catch (Exception ex)
                        {
                            if (!ex.Message.Equals("Version conflict.", StringComparison.CurrentCultureIgnoreCase))
                            {
                                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Attachments", ex.GetType().ToString(), "");
                                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message);

                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message);
                                Console.ForegroundColor = ConsoleColor.Gray;
                            }
                        }
                    }
                    #endregion

                   //[START] [Load "Target Items" After Update, to avoid Version Conflict]
                   targetItem = newList.GetItemById(targetItem.Id);
                   clientContext.Load(targetItem);
                   clientContext.ExecuteQuery();
                   //[END] [Load "Target Items" After Update, to avoid Version Conflict]

                   targetItem["Modified"] = sourceModifiedDate;
                   targetItem["Editor"] = sourceModifiledBy;
                   targetItem.Update();
                   clientContext.ExecuteQuery();

                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List", ex.GetType().ToString(), "");
                Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
        private static void AddNewListItem(CsvRecord record, List spList, ClientContext clientContext)
        {
            //Instantiate dictionary to temporarily store field values
            Dictionary<string, object> itemFieldValues = new Dictionary<string, object>();
            //Use reflection to iterate through the record's properties
            PropertyInfo[] properties = typeof(CsvRecord).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                //Get property value
                object propValue = property.GetValue(record, null);
                //Only set field if the property has a value
                if (!String.IsNullOrEmpty(propValue.ToString()))
                {
                    //Get site column that matches the property name
                    //ASSUMPTION: Your property names match the internal names of the corresponding site columns
                    Field matchingField = spList.Fields.GetByInternalNameOrTitle(property.Name);
                    clientContext.Load(matchingField);
                    clientContext.ExecuteQuery();

                    //Switch on the field type
                    switch (matchingField.FieldTypeKind)
                    {
                        case FieldType.User:
                            FieldUserValue userFieldValue = GetUserFieldValue(propValue.ToString(), clientContext);
                            if (userFieldValue != null)
                                itemFieldValues.Add(matchingField.InternalName, userFieldValue);
                            else
                                throw new Exception("User field value could not be added: " + propValue.ToString());
                            break;
                        case FieldType.Lookup:
                            FieldLookupValue lookupFieldValue = GetLookupFieldValue(propValue.ToString(),
                                ConfigurationManager.AppSettings["LookupListName"].ToString(),
                                clientContext);
                            if (lookupFieldValue != null)
                                itemFieldValues.Add(matchingField.InternalName, lookupFieldValue);
                            else
                                throw new Exception("Lookup field value could not be added: " + propValue.ToString());
                            break;
                        case FieldType.Invalid:
                            switch (matchingField.TypeAsString)
                            {
                                case "TaxonomyFieldType":
                                    TaxonomyFieldValue taxFieldValue = GetTaxonomyFieldValue(propValue.ToString(), matchingField, clientContext);
                                    if (taxFieldValue != null)
                                        itemFieldValues.Add(matchingField.InternalName, taxFieldValue);
                                    else
                                        throw new Exception("Taxonomy field value could not be added: " + propValue.ToString());
                                    break;
                                default:
                                    //Code for publishing site columns not implemented
                                    continue;
                            }
                            break;
                        default:
                            itemFieldValues.Add(matchingField.InternalName, propValue);
                            break;
                    }
                }
            }

            //Add new item to list
            ListItemCreationInformation creationInfo = new ListItemCreationInformation();
            ListItem oListItem = spList.AddItem(creationInfo);

            foreach (KeyValuePair<string, object> itemFieldValue in itemFieldValues)
            {
                //Set each field value
                oListItem[itemFieldValue.Key] = itemFieldValue.Value;
            }
            //Persist changes
            oListItem.Update();
            clientContext.ExecuteQuery();
        }
Example #8
0
 public virtual void Test005_PutGetStringList()
 {
     Config c = new Config();
     List<string> values = new List<string>();
     values.AddItem("value1");
     values.AddItem("value2");
     c.SetStringList("my", null, "somename", values);
     object[] expArr = Sharpen.Collections.ToArray(values);
     string[] actArr = c.GetStringList("my", null, "somename");
     NUnit.Framework.Assert.IsTrue(Arrays.Equals(expArr, actArr));
     string expText = "[my]\n\tsomename = value1\n\tsomename = value2\n";
     NUnit.Framework.Assert.AreEqual(expText, c.ToText());
 }
        public IList<String> GetPossibleAncestorRevisionIDs(RevisionInternal rev, int limit, ref Boolean hasAttachment)
        {
            var matchingRevs = new List<String>();
            var generation = rev.GetGeneration();
            if (generation <= 1)
            {
                return null;
            }

            var docNumericID = GetDocNumericID(rev.GetDocId());
            if (docNumericID <= 0)
            {
                return null;
            }

            var sqlLimit = limit > 0 ? limit : -1;

            // SQL uses -1, not 0, to denote 'no limit'
            var sql = @"SELECT revid, sequence FROM revs WHERE doc_id=? and revid < ? and deleted=0 and json not null"
                  + " ORDER BY sequence DESC LIMIT ?";
            var args = new [] { Convert.ToString(docNumericID), generation + "-", sqlLimit.ToString() };
            Cursor cursor = null;
            try
            {
                cursor = StorageEngine.RawQuery(sql, args);
                cursor.MoveToNext();

                if (!cursor.IsAfterLast())
                {
                    if (matchingRevs.Count == 0)
                    {
                        hasAttachment = SequenceHasAttachments(cursor.GetLong(1));
                    }
                    matchingRevs.AddItem(cursor.GetString(0));
                }
            }
            catch (SQLException e)
            {
                Log.E(Database.Tag, "Error getting all revisions of document", e);
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }
            return matchingRevs;
        }
Example #10
0
		public Header(IDictionary<string, IList<string>> map) : this()
		{
			// initialize fields
			foreach (KeyValuePair<string, IList<string>> next in map.EntrySet())
			{
				string key = next.Key;
				IList<string> value = next.Value;
				List<string> linkedList = new List<string>();
				foreach (string element in value)
				{
					linkedList.AddItem(element);
					props.AddItem(key);
					props.AddItem(element);
				}
				keyTable.Put(key, linkedList);
			}
		}
        private void CreateSampleReport(ClientContext clientContext, List list)
        {
            Trace.WriteLine("Creating sample report template");
            var template = new
            {
                engine = "jsrender",
                content = System.IO.File.ReadAllText(Path.Combine(AssemblyDirectory, "SampleReport", "SampleReport.html")),
                helpers = System.IO.File.ReadAllText(Path.Combine(AssemblyDirectory, "SampleReport", "SampleHelpers.js")),
                script = new
                {
                    content = System.IO.File.ReadAllText(Path.Combine(AssemblyDirectory, "SampleReport", "SampleScript.js")),
                }
            };

            ListItem listItem = list.AddItem(new ListItemCreationInformation());
            listItem["Title"] = "Sample report";
            listItem["Template"] = JsonConvert.SerializeObject(template);
            listItem["Description"] = "This is sample report. You can print it using [Render jsreport] button from detail form. To edit it use [Open editor] button on edit form";
            listItem.Update();
            clientContext.ExecuteQuery();
            Trace.WriteLine("Sample report template created");
        }
Example #12
0
 private IList<ID3v2ChapterTOCFrameData> ExtractChapterTOCFrameData(string id)
 {
     ID3v2FrameSet frameSet = frameSets.Get(id);
     if (frameSet != null)
     {
         IList<ID3v2ChapterTOCFrameData> chapterData = new List<ID3v2ChapterTOCFrameData>();
         IList<ID3v2Frame> frames = frameSet.GetFrames();
         foreach (ID3v2Frame frame in frames)
         {
             ID3v2ChapterTOCFrameData frameData;
             try
             {
                 frameData = new ID3v2ChapterTOCFrameData(UseFrameUnsynchronisation(), frame.GetData
                     ());
                 chapterData.AddItem(frameData);
             }
             catch (InvalidDataException)
             {
             }
         }
         // do nothing
         return chapterData;
     }
     return null;
 }
        private ListItem EnsureListItem(List list, ListItemDefinition listItemModel)
        {
            var context = list.Context;

            // TODO, lazy to query
            var items = list.GetItems(CamlQuery.CreateAllItemsQuery());

            context.Load(items);
            context.ExecuteQuery();

            // BIG TODO, don't tell me, I know that
            var currentItem = items.FirstOrDefault(i => i["Title"] != null &&
                    (i["Title"].ToString() == listItemModel.Title));

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentItem,
                ObjectType = typeof(ListItem),
                ObjectDefinition = listItemModel,
                ModelHost = list
            });

            if (currentItem == null)
            {
                var newItem = list.AddItem(new ListItemCreationInformation());

                newItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                newItem.Update();

                context.ExecuteQuery();

                return newItem;
            }
            else
            {
                currentItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = currentItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                currentItem.Update();

                context.ExecuteQuery();

                return currentItem;
            }
        }
 /// <summary>
 /// Check for the list item named Matter Center Briefcase already exists, if not then only create new folder
 /// </summary>
 /// <param name="clientContext">SP client context</param>
 /// <param name="list">Name of the list</param>
 /// <param name="usersMySite">My Site URL of the user</param>
 internal static void CreateBriefcaseIfNotExists(ClientContext clientContext, List list, string usersMySite)
 {
     CamlQuery briefcaseQuery = new CamlQuery();
     briefcaseQuery.ViewXml = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.BriefcaseFolderQuery, ServiceConstantStrings.LegalBriefcaseFolder);
     ListItemCollection briefcases = list.GetItems(briefcaseQuery);
     clientContext.Load(briefcases, listItems => listItems.Include(item => item.DisplayName));
     clientContext.ExecuteQuery();
     ListItem listItem = briefcases.Where(item => item.DisplayName == ServiceConstantStrings.LegalBriefcaseFolder).FirstOrDefault();
     if (null == listItem)      // Check for Matter Center Briefcase folder exists, if not then create
     {
         ListItemCreationInformation newItem = new ListItemCreationInformation();
         newItem.FolderUrl = string.Concat(usersMySite, ServiceConstantStrings.OneDriveDocumentLibraryTitle);
         newItem.LeafName = ServiceConstantStrings.LegalBriefcaseFolder;
         newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
         listItem = list.AddItem(newItem);
         listItem.Update();
         clientContext.Load(listItem, field => field.DisplayName);
         clientContext.ExecuteQuery();
     }
 }
Example #15
0
        private void PopulateListWithTestData()
        {
            _clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite");

            Web site = _clientContext.Web;
            _list = site.Lists.GetByTitle("Death Star Inventory 2");

            for (int j = 0; j < 20; j++)
            {
                for (int i = 0; i < 100; i++)
                {
                    var newItemInfo = new ListItemCreationInformation() { LeafName = string.Format("TIE Fighter #{0}", i + (j * 100)) };
                    ListItem newItem = _list.AddItem(newItemInfo);
                    _clientContext.Load(newItem);
                    newItem["Item_x0020_Type"] = "TIE Fighter";
                    newItem["Fire_x0020_Power"] = 1;
                    newItem.Update();
                }
                _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);
            }

            for (int j = 0; j < 10; j++)
            {
                for (int i = 0; i < 100; i++)
                {
                    var newItemInfo = new ListItemCreationInformation() { LeafName = string.Format("Turbo Laser Battery #{0}", i + (j * 100)) };
                    ListItem newItem = _list.AddItem(newItemInfo);
                    _clientContext.Load(newItem);
                    newItem["Item_x0020_Type"] = "Turbo Laser";
                    newItem["Fire_x0020_Power"] = 4;
                    newItem.Update();
                }
                _clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback);
            }
        }
Example #16
0
        private void import_excel_to_sharepoint_list(Object stateInfo)
        {
            try {
                string[] ui_selections = stateInfo.ToString().Split(';');

                _clientContext.Load(_site);
                _list = _site.Lists.GetByTitle(ui_selections[0]);
                _clientContext.ExecuteQuery();
                Folder root_folder = _list.RootFolder;
                _clientContext.Load(root_folder);
                _clientContext.ExecuteQuery();
                string root_folder_url = root_folder.ServerRelativeUrl;

                string commandStr = "select * from [" + ui_selections[1] + "]";
                OleDbDataAdapter command = new OleDbDataAdapter(commandStr, get_conn_string());
                DataTable data = new DataTable();
                command.Fill(data);
                this.Invoke(
                    _update_counter,
                    new object[] { _count + " / " + data.Rows.Count }
                );

                // prepar for the loop
                DataTable table = new DataTable();
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

                if (_folder_tree == null) {
                    _folder_tree = new Tree();
                    _folder_tree.URL = String.Format("{0}",root_folder_url);
                    _folder_tree.Name = "ROOT";
                    _folder_tree.Children = new List<Tree>();
                }
                int record_number = 0;
                _count = int.Parse(numericUpDown1.Value.ToString());
                foreach (DataRow row in data.Rows) {
                    if (!_is_running) return;
                    record_number++;
                    if (record_number <= _count) continue;
                    // check if need to created Folders for imported items
                    string new_folder_relative_url = "";
                    Tree new_folder = null;
                    Tree parent_folder = _folder_tree;
                    _message = _folder_tree.URL;
                    foreach (DataGridViewRow mapping_row in dgMapping.Rows) {
                        // if the Folder Level column is not null, then, put item into this folder
                        // the folder level will depends on the sequence of the folder columns apprea in the Mapping GridView. TODO: maybe improved in the future.
                        if (mapping_row.Cells[3].Value != null) {
                            string folder_name = format_folder_name(row[mapping_row.Cells[0].Value.ToString()].ToString());
                            _message += "\n  folder:" + folder_name;
                            new_folder = create_folder_if_not_exists(parent_folder, folder_name);
                            new_folder_relative_url += folder_name + "/";
                            parent_folder = new_folder;
                        }
                    }
                    if (new_folder != null) {
                        itemCreateInfo.FolderUrl = new_folder.URL;
                        _message += "\nnew_folder: " + new_folder.URL;
                    }

                    Microsoft.SharePoint.Client.ListItem listItem = _list.AddItem(itemCreateInfo);
                    // Item Value
                    foreach (DataGridViewRow mapping_row in dgMapping.Rows) {
                        if (mapping_row.Cells[1].Value != null) {
                            if (mapping_row.Cells[2].Value != null) {
                                if (string.IsNullOrEmpty(table.TableName)) {
                                    table.TableName = mapping_row.Cells[2].Value.ToString();
                                } else {
                                    if (table.TableName != mapping_row.Cells[2].Value.ToString()) {
                                        listItem[table.TableName] = this.ToHtmlTable(table);
                                        table.TableName = null;
                                        table.Clear();
                                        table.Columns.Clear();
                                        table.TableName = mapping_row.Cells[2].Value.ToString();
                                    }
                                }
                                DataColumn tcol = new DataColumn(mapping_row.Cells[0].Value.ToString());
                                table.Columns.Add(tcol);
                                if (row[mapping_row.Cells[0].Value.ToString()] != null) {	// The column must have value, or, it will be ignored.
                                    if (!string.IsNullOrEmpty(row[mapping_row.Cells[0].Value.ToString()].ToString())) {
                                        string[] col_values = row[mapping_row.Cells[0].Value.ToString()].ToString().Split(_separator);
                                        if (table.Rows.Count == 0) {
                                            for (int i = 0; i < col_values.Length; i++) {
                                                table.Rows.Add(new object[] { col_values[i] });
                                            }
                                        } else {
                                            int i = 0;
                                            for (i = 0; i < Math.Min(col_values.Length, table.Rows.Count); i++) {
                                                table.Rows[i][tcol] = col_values[i];
                                            }
                                            if (col_values.Length > table.Rows.Count) {
                                                for (int j = i; j < col_values.Length; j++) {
                                                    DataRow new_row = table.Rows.Add();
                                                    new_row[tcol] = col_values[j];
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                string value = row[mapping_row.Cells[0].Value.ToString()].ToString();
                                if (!string.IsNullOrEmpty(value)) {
                                    // Check the Date-Time format, for some date column will have time in it, we must remove the time first before we can put it into SharePoint.
                                    Regex reg = new Regex(@" [0-9]+:[0-9]+[AP]M$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                                    if (reg.IsMatch(value)) {
                                        value = reg.Replace(value, "");
                                    }
                                    listItem[mapping_row.Cells[1].Value.ToString()] = value;
                                }
                            }
                        }
                    }
                    if (table.Columns.Count > 0) {
                        listItem[table.TableName] = this.ToHtmlTable(table);
                        table.TableName = null;
                        table.Clear();
                        table.Columns.Clear();
                    }
                    listItem.Update();
                    _count++;
                    this.Invoke(
                        _update_counter,
                        new object[] { _count + " / " + data.Rows.Count }
                    );
                    if (_count % 20 == 0) {
                        _clientContext.ExecuteQuery(); // TODO: Is there any other way to improve this?
                    }
                }
                _clientContext.ExecuteQuery(); // for the last item
            }
            catch (Exception ex) {
                MessageBox.Show(_message+"\n"+ex.ToString()+"\n"+ex.Source+"\n"+ex.StackTrace);
            }
        }
Example #17
0
        private void CreateCustomPropertiesInList(List list)
        {
            IList<string> _listItemsToAdd = new List<string>();
            _listItemsToAdd.Add(SiteClassificationKeys.AudienceReachKey);
            _listItemsToAdd.Add(SiteClassificationKeys.BusinessImpactKey);

           foreach(var _itemToAdd in _listItemsToAdd)
           {
               ListItemCreationInformation _item = new ListItemCreationInformation();
               ListItem _record = list.AddItem(_item);
               _record[SiteClassificationFields.FLD_KEY_INTERNAL_NAME] = _itemToAdd;
               _record.Update();
           }
        }
        private void Create(List list, string[] foldernames, int teller, string url, string newFolderName)
        {
            ListItemCreationInformation newItem = new ListItemCreationInformation();

            newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
            newItem.FolderUrl = url;
            string folderName = foldernames[teller].Trim();
            if (folderName != foldernames[teller] || folderName == string.Empty)
            {
                string errorInformation = string.Format("Path [{0}] is not valid", newFolderName);
                throw new Exception(string.Format("Error in creating form [{0}].Exeption({1})", newFolderName, errorInformation));
            }
            newItem.LeafName = foldernames[teller];
            ListItem item = list.AddItem(newItem);
            item["Title"] = foldernames[teller];
            item.Update();
        }
		internal WalkFetchConnection(WalkTransport t, WalkRemoteObjectDatabase w)
		{
			NGit.Transport.Transport wt = (NGit.Transport.Transport)t;
			local = wt.local;
			objCheck = wt.IsCheckFetchedObjects() ? new ObjectChecker() : null;
			inserter = local.NewObjectInserter();
			reader = local.NewObjectReader();
			remotes = new AList<WalkRemoteObjectDatabase>();
			remotes.AddItem(w);
			unfetchedPacks = new List<WalkFetchConnection.RemotePack>();
			packsConsidered = new HashSet<string>();
			noPacksYet = new List<WalkRemoteObjectDatabase>();
			noPacksYet.AddItem(w);
			noAlternatesYet = new List<WalkRemoteObjectDatabase>();
			noAlternatesYet.AddItem(w);
			fetchErrors = new Dictionary<ObjectId, IList<Exception>>();
			packLocks = new AList<PackLock>(4);
			revWalk = new RevWalk(reader);
			revWalk.SetRetainBody(false);
			treeWalk = new TreeWalk(reader);
			COMPLETE = revWalk.NewFlag("COMPLETE");
			IN_WORK_QUEUE = revWalk.NewFlag("IN_WORK_QUEUE");
			LOCALLY_SEEN = revWalk.NewFlag("LOCALLY_SEEN");
			localCommitQueue = new DateRevQueue();
			workQueue = new List<ObjectId>();
		}
Example #20
0
        internal override void ProcessInbox(RevisionList inbox)
        {
            // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
            // <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
            var diffs = new Dictionary<String, IList<String>>();
            foreach (var rev in inbox)
            {
                var docID = rev.GetDocId();
                var revs = diffs.Get(docID);
                if (revs == null)
                {
                    revs = new List<String>();
                    diffs[docID] = revs;
                }
                revs.AddItem(rev.GetRevId());
                AddPending(rev);
            }

            // Call _revs_diff on the target db:
            Log.D(Tag, "processInbox() calling asyncTaskStarted()");
            Log.D(Tag, "posting to /_revs_diff: {0}", String.Join(Environment.NewLine, Manager.GetObjectMapper().WriteValueAsString(diffs)));

            AsyncTaskStarted();
            SendAsyncRequest(HttpMethod.Post, "/_revs_diff", diffs, (response, e) =>
            {
                try {
                    var results = response.AsDictionary<string, object>();

                    Log.D(Tag, "/_revs_diff response: {0}\r\n{1}", response, results);

                    if (e != null) 
                    {
                        SetLastError(e);
                        RevisionFailed();
                    } else {
                        if (results.Count != 0) 
                        {
                            // Go through the list of local changes again, selecting the ones the destination server
                            // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
                            var docsToSend = new List<object> ();
                            var revsToSend = new RevisionList();
                            foreach (var rev in inbox)
                            {
                                // Is this revision in the server's 'missing' list?
                                IDictionary<string, object> properties = null;
                                var revResults = results.Get(rev.GetDocId()).AsDictionary<string, object>();

                                if (revResults == null)
                                {
                                    continue;
                                }

                                var revs = ((JArray)revResults.Get("missing")).Values<String>().ToList();
                                if (revs == null || !revs.Contains(rev.GetRevId()))
                                {
                                    RemovePending(rev);
                                    continue;
                                }

                                // Get the revision's properties:
                                var contentOptions = DocumentContentOptions.IncludeAttachments;

                                if (!dontSendMultipart && revisionBodyTransformationFunction == null)
                                {
                                    contentOptions &= DocumentContentOptions.BigAttachmentsFollow;
                                }


                                RevisionInternal loadedRev;
                                try {
                                    loadedRev = LocalDatabase.LoadRevisionBody (rev, contentOptions);
                                    properties = new Dictionary<string, object>(rev.GetProperties());
                                } catch (CouchbaseLiteException e1) {
                                    Log.W(Tag, string.Format("{0} Couldn't get local contents of {1}", rev, this), e1);
                                    RevisionFailed();
                                    continue;
                                }

                                var populatedRev = TransformRevision(loadedRev);

                                IList<string> possibleAncestors = null;
                                if (revResults.ContainsKey("possible_ancestors"))
                                {
                                    possibleAncestors = revResults["possible_ancestors"].AsList<string>();
                                }

                                properties = new Dictionary<string, object>(populatedRev.GetProperties());
                                var revisions = LocalDatabase.GetRevisionHistoryDictStartingFromAnyAncestor(populatedRev, possibleAncestors);
                                properties["_revisions"] = revisions;
                                populatedRev.SetProperties(properties);

                                // Strip any attachments already known to the target db:
                                if (properties.ContainsKey("_attachments")) 
                                {
                                    // Look for the latest common ancestor and stuf out older attachments:
                                    var minRevPos = FindCommonAncestor(populatedRev, possibleAncestors);

                                    Database.StubOutAttachmentsInRevBeforeRevPos(populatedRev, minRevPos + 1, false);

                                    properties = populatedRev.GetProperties();

                                    if (!dontSendMultipart && UploadMultipartRevision(populatedRev)) 
                                    {
                                        continue;
                                    }
                                }

                                if (properties == null || !properties.ContainsKey("_id"))
                                {
                                    throw new InvalidOperationException("properties must contain a document _id");
                                }
                                // Add the _revisions list:
                                revsToSend.Add(rev);

                                //now add it to the docs to send
                                docsToSend.AddItem (properties);
                            }

                            UploadBulkDocs(docsToSend, revsToSend);
                        } 
                        else 
                        {
                            foreach (var revisionInternal in inbox)
                            {
                                RemovePending(revisionInternal);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.E(Tag, "Unhandled exception in Pusher.ProcessInbox", ex);
                }
                finally
                {
                    Log.D(Tag, "processInbox() calling AsyncTaskFinished()");
                    AsyncTaskFinished(1);
                }
            });
        }
Example #21
0
        /// <summary>
        /// Convert push remote refs update specification from
        /// <see cref="RefSpec">RefSpec</see>
        /// form
        /// to
        /// <see cref="RemoteRefUpdate">RemoteRefUpdate</see>
        /// . Conversion expands wildcards by matching
        /// source part to local refs. expectedOldObjectId in RemoteRefUpdate is
        /// always set as null. Tracking branch is configured if RefSpec destination
        /// matches source of any fetch ref spec for this transport remote
        /// configuration.
        /// </summary>
        /// <param name="db">local database.</param>
        /// <param name="specs">collection of RefSpec to convert.</param>
        /// <param name="fetchSpecs">
        /// fetch specifications used for finding localtracking refs. May
        /// be null or empty collection.
        /// </param>
        /// <returns>
        /// collection of set up
        /// <see cref="RemoteRefUpdate">RemoteRefUpdate</see>
        /// .
        /// </returns>
        /// <exception cref="System.IO.IOException">
        /// when problem occurred during conversion or specification set
        /// up: most probably, missing objects or refs.
        /// </exception>
        public static ICollection<RemoteRefUpdate> FindRemoteRefUpdatesFor(Repository db, 
			ICollection<RefSpec> specs, ICollection<RefSpec> fetchSpecs)
        {
            if (fetchSpecs == null)
            {
                fetchSpecs = Sharpen.Collections.EmptyList<RefSpec>();
            }
            IList<RemoteRefUpdate> result = new List<RemoteRefUpdate>();
            ICollection<RefSpec> procRefs = ExpandPushWildcardsFor(db, specs);
            foreach (RefSpec spec in procRefs)
            {
                string srcSpec = spec.GetSource();
                Ref srcRef = db.GetRef(srcSpec);
                if (srcRef != null)
                {
                    srcSpec = srcRef.GetName();
                }
                string destSpec = spec.GetDestination();
                if (destSpec == null)
                {
                    // No destination (no-colon in ref-spec), DWIMery assumes src
                    //
                    destSpec = srcSpec;
                }
                if (srcRef != null && !destSpec.StartsWith(Constants.R_REFS))
                {
                    // Assume the same kind of ref at the destination, e.g.
                    // "refs/heads/foo:master", DWIMery assumes master is also
                    // under "refs/heads/".
                    //
                    string n = srcRef.GetName();
                    int kindEnd = n.IndexOf('/', Constants.R_REFS.Length);
                    destSpec = Sharpen.Runtime.Substring(n, 0, kindEnd + 1) + destSpec;
                }
                bool forceUpdate = spec.IsForceUpdate();
                string localName = FindTrackingRefName(destSpec, fetchSpecs);
                RemoteRefUpdate rru = new RemoteRefUpdate(db, srcSpec, destSpec, forceUpdate, localName
                    , null);
                result.AddItem(rru);
            }
            return result;
        }
 public static string AccessTokenForEmailAndSite(string email, Uri site)
 {
     try
     {
         IList<string> key = new List<string>();
         key.AddItem(email);
         key.AddItem(site.ToString().ToLower());
         Log.D(Database.Tag, "FacebookAuthorizer looking up key: " + key + " from list of access tokens");
         return accessTokens.Get(key);
     }
     catch (Exception e)
     {
         Log.E(Database.Tag, "Error looking up access token", e);
     }
     return null;
 }
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal IDictionary<String, Object> GetAllDocs(QueryOptions options)
        {
            var result = new Dictionary<String, Object>();
            var rows = new AList<QueryRow>();
            if (options == null)
                options = new QueryOptions();

            var includeDeletedDocs = (options.GetAllDocsMode() == AllDocsMode.IncludeDeleted);
            var updateSeq = 0L;
            if (options.IsUpdateSeq())
            {
                updateSeq = GetLastSequenceNumber();
            }

            // TODO: needs to be atomic with the following SELECT
            var sql = new StringBuilder("SELECT revs.doc_id, docid, revid, sequence");
            if (options.IsIncludeDocs())
            {
                sql.Append(", json");
            }
            if (includeDeletedDocs)
            {
                sql.Append(", deleted");
            }
            sql.Append(" FROM revs, docs WHERE");

            if (options.GetKeys() != null)
            {
                if (options.GetKeys().Count() == 0)
                {
                    return result;
                }
                var commaSeperatedIds = JoinQuotedObjects(options.GetKeys());
                sql.Append(String.Format(" revs.doc_id IN (SELECT doc_id FROM docs WHERE docid IN ({0})) AND", commaSeperatedIds));
            }
            sql.Append(" docs.doc_id = revs.doc_id AND current=1");

            if (!includeDeletedDocs)
            {
                sql.Append(" AND deleted=0");
            }

            var args = new AList<String>();
            var minKey = options.GetStartKey();
            var maxKey = options.GetEndKey();
            var inclusiveMin = true;
            var inclusiveMax = options.IsInclusiveEnd();

            if (options.IsDescending())
            {
                minKey = maxKey;
                maxKey = options.GetStartKey();
                inclusiveMin = inclusiveMax;
                inclusiveMax = true;
            }
            if (minKey != null)
            {
                Debug.Assert((minKey is String));
                sql.Append((inclusiveMin ? " AND docid >= ?" : " AND docid > ?"));
                args.AddItem((string)minKey);
            }
            if (maxKey != null)
            {
                Debug.Assert((maxKey is string));
                sql.Append((inclusiveMax ? " AND docid <= ?" : " AND docid < ?"));
                args.AddItem((string)maxKey);
            }
            sql.Append(
                String.Format(" ORDER BY docid {0}, {1} revid DESC LIMIT ? OFFSET ?", 
                    options.IsDescending() ? "DESC" : "ASC", 
                    includeDeletedDocs ? "deleted ASC," : String.Empty
                )
            );
            args.AddItem(options.GetLimit().ToString());
            args.AddItem(options.GetSkip().ToString());

            Cursor cursor = null;
            var docs = new Dictionary<String, QueryRow>();
            try
            {
                cursor = StorageEngine.RawQuery(
                    sql.ToString(),
                    CommandBehavior.SequentialAccess,
                    args.ToArray()
                );

//                cursor.MoveToNext();

                var keepGoing = cursor.MoveToNext();
                while (keepGoing)
                {
                    var docNumericID = cursor.GetLong(0);

                    var includeDocs = options.IsIncludeDocs();

                    var docId = cursor.GetString(1);
                    var revId = cursor.GetString(2);
                    var sequenceNumber = cursor.GetLong(3);
                    byte[] json = null;
                    if (includeDocs)
                    {
                        json = cursor.GetBlob(4);
                    }
                    var deleted = includeDeletedDocs && cursor.GetInt(GetDeletedColumnIndex(options)) > 0;

                    IDictionary<String, Object> docContents = null;

                    if (includeDocs)
                    {
                        docContents = DocumentPropertiesFromJSON(json, docId, revId, deleted, sequenceNumber, options.GetContentOptions());
                    }
                    // Iterate over following rows with the same doc_id -- these are conflicts.
                    // Skip them, but collect their revIDs if the 'conflicts' option is set:
                    var conflicts = new List<string>();
                    while (((keepGoing = cursor.MoveToNext())) && cursor.GetLong(0) == docNumericID)
                    {
                       if (options.GetAllDocsMode() == AllDocsMode.ShowConflicts || options.GetAllDocsMode() == AllDocsMode.OnlyConflicts)
                       {
                           if (conflicts.IsEmpty())
                           {
                               conflicts.AddItem(revId);
                           }
                           conflicts.AddItem(cursor.GetString(2));
                       }
                    }
                    if (options.GetAllDocsMode() == AllDocsMode.OnlyConflicts && conflicts.IsEmpty())
                    {
                       continue;
                    }
                    var value = new Dictionary<string, object>();
                    value["rev"] = revId;
                    value["_conflicts"] = conflicts;
                    if (includeDeletedDocs)
                    {
                        value["deleted"] = deleted;
                    }
                    var change = new QueryRow(docId, sequenceNumber, docId, value, docContents);
                    change.Database = this;

                    if (options.GetKeys() != null)
                    {
                        docs[docId] = change;
                    }
                    else
                    {
                        rows.AddItem(change);
                    }
                }
                if (options.GetKeys() != null)
                {
                    foreach (var docIdObject in options.GetKeys())
                    {
                        if (docIdObject is string)
                        {
                            var docId = (string)docIdObject;
                            var change = docs.Get(docId);
                            if (change == null)
                            {
                                var value = new Dictionary<string, object>();
                                var docNumericID = GetDocNumericID(docId);
                                if (docNumericID > 0)
                                {
                                    bool deleted;
                                    var outIsDeleted = new AList<bool>();
                                    var outIsConflict = new AList<bool>();
                                    var revId = WinningRevIDOfDoc(docNumericID, outIsDeleted, outIsConflict);
                                    if (outIsDeleted.Count > 0)
                                    {
                                        deleted = true;
                                    }
                                    if (revId != null)
                                    {
                                        value["rev"] = revId;
                                        value["deleted"] = true; // FIXME: SHould this be set the value of `deleted`?
                                    }
                                }
                                change = new QueryRow((value != null ? docId : null), 0, docId, value, null);
                                change.Database = this;
                            }
                            rows.AddItem(change);
                        }
                    }
                }
            }
            catch (SQLException e)
            {
                Log.E(Tag, "Error getting all docs", e);
                throw new CouchbaseLiteException("Error getting all docs", e, new Status(StatusCode.InternalServerError));
            }
            finally
            {
                if (cursor != null)
                    cursor.Close();
            }
            result["rows"] = rows;
            result["total_rows"] = rows.Count;
            result.Put("offset", options.GetSkip());
            if (updateSeq != 0)
            {
                result["update_seq"] = updateSeq;
            }
            return result;
        }
Example #24
0
        internal static IDictionary<string, object> MakeRevisionHistoryDict(IList<RevisionInternal> history)
        {
            if (history == null)
                return null;

            // Try to extract descending numeric prefixes:
            var suffixes = new List<string>();
            var start = -1;
            var lastRevNo = -1;

            foreach (var rev in history) {
                var parsed = RevisionInternal.ParseRevId(rev.GetRevId());
                int revNo = parsed.Item1;
                string suffix = parsed.Item2;
                if (revNo > 0 && suffix.Length > 0) {
                    if (start < 0) {
                        start = revNo;
                    }
                    else {
                        if (revNo != lastRevNo - 1) {
                            start = -1;
                            break;
                        }
                    }
                    lastRevNo = revNo;
                    suffixes.AddItem(suffix);
                }
                else {
                    start = -1;
                    break;
                }
            }

            var result = new Dictionary<String, Object>();
            if (start == -1) {
                // we failed to build sequence, just stuff all the revs in list
                suffixes = new List<string>();
                foreach (RevisionInternal rev_1 in history) {
                    suffixes.AddItem(rev_1.GetRevId());
                }
            }
            else {
                result["start"] = start;
            }

            result["ids"] = suffixes;
            return result;
        }
Example #25
0
 public static void AddDemoDataToSupportCasesList(ClientContext ctx, List list, string title,
                                                string status, string csr, string customerID)
 {
     ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
     ListItem newItem = list.AddItem(itemCreateInfo);
     newItem["Title"] = title;
     newItem["FTCAM_Status"] = status;
     newItem["FTCAM_CSR"] = csr;
     newItem["FTCAM_CustomerID"] = customerID;
     newItem.Update();
     ctx.ExecuteQuery();
 }
        public void AddItem_NotNullValue_ShouldContainItem()
        {
            // Setup
            var sut = new List<int>() { 1, 2, 3, 4, 5, 6, 7 }.AsEnumerable();
            var expectedItem = 8;

            // Exercise
            sut = sut.AddItem(expectedItem);
            var actual = sut.Last();

            //Verify
            Assert.Equal(expectedItem, actual);
        }
 public static string RegisterAccessToken(string accessToken, string email, string
      origin)
 {
     lock (typeof(FacebookAuthorizer))
     {
         IList<string> key = new List<string>();
         key.AddItem(email);
         key.AddItem(origin);
         if (accessTokens == null)
         {
             accessTokens = new Dictionary<IList<string>, string>();
         }
         Log.D(Database.Tag, "FacebookAuthorizer registering key: " + key);
         accessTokens[key] = accessToken;
         return email;
     }
 }
        private ListItem EnsureListItem(List list, Folder folder, ListItemDefinition listItemModel)
        {
            var context = list.Context;
            var currentItem = FindListItem(list, folder, listItemModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentItem,
                ObjectType = typeof(ListItem),
                ObjectDefinition = listItemModel,
                ModelHost = list
            });

            if (currentItem == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list item");

                var newItem = list.AddItem(new ListItemCreationInformation
                {
                    FolderUrl = folder.ServerRelativeUrl,
                    UnderlyingObjectType = FileSystemObjectType.File,
                    LeafName = null
                });

                MapListItemProperties(newItem, listItemModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                newItem.Update();

                context.ExecuteQueryWithTrace();

                return newItem;
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list item");

                MapListItemProperties(currentItem, listItemModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = currentItem,
                    ObjectType = typeof(ListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                currentItem.Update();

                context.ExecuteQueryWithTrace();

                return currentItem;
            }
        }
Example #29
0
 internal static string JoinQuotedObjects(IEnumerable<Object> objects)
 {
     var strings = new List<String>();
     foreach (var obj in objects)
     {
         strings.AddItem(obj != null ? obj.ToString() : null);
     }
     return JoinQuoted(strings);
 }
Example #30
0
 private void AddDemoItem(List demoList, string title)
 {
     Microsoft.SharePoint.Client.ListItem item = demoList.AddItem(new ListItemCreationInformation());
     item["Title"] = title;
     item.Update();
 }