// unix group, not caching
        /// <summary>Gets users for a netgroup</summary>
        /// <param name="netgroup">return users for this netgroup</param>
        /// <returns>list of users for a given netgroup</returns>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual IList <string> GetUsersForNetgroup(string netgroup)
        {
            IList <string> users = new List <string>();
            // returns a string similar to this:
            // group               ( , user, ) ( domain, user1, host.com )
            string usersRaw = ExecShellGetUserForNetgroup(netgroup);

            // get rid of spaces, makes splitting much easier
            usersRaw = usersRaw.ReplaceAll(" +", string.Empty);
            // remove netgroup name at the beginning of the string
            usersRaw = usersRaw.ReplaceFirst(netgroup.ReplaceFirst("@", string.Empty) + "[()]+"
                                             , string.Empty);
            // split string into user infos
            string[] userInfos = usersRaw.Split("[()]+");
            foreach (string userInfo in userInfos)
            {
                // userInfo: xxx,user,yyy (xxx, yyy can be empty strings)
                // get rid of everything before first and after last comma
                string user = userInfo.ReplaceFirst("[^,]*,", string.Empty);
                user = user.ReplaceFirst(",.*$", string.Empty);
                // voila! got username!
                users.AddItem(user);
            }
            return(users);
        }
		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 static string CreateFolder(string listName, string folderName, SharePointContext spContext)
        {
            string relativeURL = string.Empty;

            using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
            {
                if (clientContext != null)
                {
                    List list = clientContext.Web.Lists.GetByTitle(listName);
                    clientContext.Load(clientContext.Web, w => w.ServerRelativeUrl);

                    ListItemCreationInformation info = new ListItemCreationInformation();
                    info.UnderlyingObjectType = FileSystemObjectType.Folder;
                    info.LeafName             = folderName.Trim();
                    ListItem newItem = list.AddItem(info);
                    newItem["Title"] = folderName;
                    newItem.Update();
                    clientContext.ExecuteQuery();

                    relativeURL = clientContext.Web.ServerRelativeUrl;
                }
            }

            return(relativeURL);
        }
Example #4
0
 /// <summary>Block is not found on the disk</summary>
 private void AddDifference(List <DirectoryScanner.ScanInfo> diffRecord, DirectoryScanner.Stats
                            statsRecord, long blockId, FsVolumeSpi vol)
 {
     statsRecord.missingBlockFile++;
     statsRecord.missingMetaFile++;
     diffRecord.AddItem(new DirectoryScanner.ScanInfo(blockId, null, null, vol));
 }
 public void CreateNewItem(String userName, int employeeNumber, String fullName, String firstName, String lastName, DateTime emplymentStart, DateTime employmentEnd, String department, String mobile, String address, String postcode, String postTown, String email)
 {
     try
     {
         ListItemCreationInformation newItemSepc = new ListItemCreationInformation();
         ListItem newItem = list.AddItem(newItemSepc);
         newItem["Title"] = userName;
         newItem["Employee_x0020_Number"]            = employeeNumber;
         newItem["Full_x0020_Name"]                  = fullName;
         newItem["First_x0020_Name"]                 = firstName;
         newItem["Last_x0020_Name"]                  = lastName;
         newItem["_x000a_Employment_x0020_start_x0"] = emplymentStart.Date;
         newItem["Employment_x0020_end_x0020_date"]  = employmentEnd.Date;
         newItem["Department"]      = department;
         newItem["Mobile"]          = mobile;
         newItem["Adress"]          = address;
         newItem["Postcode"]        = postcode;
         newItem["Post_x0020_town"] = postTown;
         newItem["Email"]           = email;
         newItem["Person"]          = fullName;
         newItem.Update();
         context.ExecuteQuery();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Example #6
0
        public string CreateFolder(ClientContext ctx, List list, string folderTitle, bool enableFolderCreation = false, string folderUrl = "")
        {
            ctx.Load(list, l => l.EnableFolderCreation);
            ctx.ExecuteQueryWithIncrementalRetry();

            if (!list.EnableFolderCreation && enableFolderCreation)
            {
                list.EnableFolderCreation = enableFolderCreation;
                list.Update();
                ctx.ExecuteQueryWithIncrementalRetry();
            }
            else if (!list.EnableFolderCreation)
            {
                throw new Exception("Can not create Folders on List because EnableFolderCreation Property is set to false");
            }

            var folderItem = list.AddItem(new ListItemCreationInformation()
            {
                FolderUrl            = folderUrl,
                LeafName             = folderTitle,
                UnderlyingObjectType = FileSystemObjectType.Folder,
            });

            folderItem.Update();
            ctx.Load(folderItem, folder => folder.Folder.ServerRelativeUrl);
            ctx.ExecuteQueryWithIncrementalRetry();

            return(UrlHelper.GetAbsoluteUrl(ctx.Url, folderItem.Folder.ServerRelativeUrl));
        }
Example #7
0
 //end for
 //end synchronized
 /// <summary>Block is found on the disk.</summary>
 /// <remarks>
 /// Block is found on the disk. In-memory block is missing or does not match
 /// the block on the disk
 /// </remarks>
 private void AddDifference(List <DirectoryScanner.ScanInfo> diffRecord, DirectoryScanner.Stats
                            statsRecord, DirectoryScanner.ScanInfo info)
 {
     statsRecord.missingMetaFile  += info.GetMetaFile() == null ? 1 : 0;
     statsRecord.missingBlockFile += info.GetBlockFile() == null ? 1 : 0;
     diffRecord.AddItem(info);
 }
Example #8
0
        /// <summary>
        /// Creates new options to the look and feel section
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="web"></param>
        private void AddNewThemeOptionToSite(ClientContext clientContext, Web web)
        {
            // Let's get instance to the composite look gallery
            List themesOverviewList = web.GetCatalog(124);

            clientContext.Load(themesOverviewList);
            clientContext.ExecuteQuery();
            // Is the item already in the list?
            if (!ContosoThemeEntryExists(clientContext, web, themesOverviewList))
            {
                // Let's create new theme entry. Notice that theme selection is not available from UI in personal sites, so this is just for consistency sake
                ListItemCreationInformation          itemInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem item     = themesOverviewList.AddItem(itemInfo);
                item["Name"]          = "Contoso";
                item["Title"]         = "Contoso";
                item["ThemeUrl"]      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spcolor");;
                item["FontSchemeUrl"] = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spfont");;
                item["ImageUrl"]      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contosobg.jpg");
                // Notice that we use oob master, but just as well you vould upload and use custom one
                item["MasterPageUrl"] = URLCombine(web.ServerRelativeUrl, "/_catalogs/masterpage/seattle.master");
                item["DisplayOrder"]  = 0;
                item.Update();
                clientContext.ExecuteQuery();
            }
        }
        static void Main(string[] args)
        {
            string userName = "******";

            Console.WriteLine("Enter the password");
            string       passWord = Console.ReadLine();
            SecureString pwd      = new SecureString();

            foreach (char c in passWord)
            {
                pwd.AppendChar(c);
            }


            string webUrl = "https://sandlerasher770.sharepoint.com/sites/JGate/";

            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new SharePointOnlineCredentials(userName, pwd);

                List fruitList = context.Web.Lists.GetByTitle("Fruits");

                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem newItem = fruitList.AddItem(itemCreateInfo);
                newItem["Title"] = "Mary";
                newItem.Update();

                context.ExecuteQuery();
                Console.WriteLine("List Item created ");
                Console.ReadLine();
            }
        }
        public bool AddListItem(string listTitle, Dictionary <string, string> fieldValues)
        {
            try
            {
                List <string> ignoreFields = new List <string>()
                {
                    "ID", "Attachments"
                };
                List targetList = Web.Lists.GetByTitle(listTitle);

                ListItemCreationInformation listItemCreateInfo = new ListItemCreationInformation();
                ListItem targetListItem = targetList.AddItem(listItemCreateInfo);
                foreach (var pair in fieldValues)
                {
                    Log.Info($"updating {pair.Key}");
                    targetListItem[pair.Key] = pair.Value;
                    targetListItem.Update();
                    ExecuteQuery();
                    Log.Info($"{pair.Key} updated with {pair.Value}");
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Example #11
0
        private static IList <KeyProviderCryptoExtension.EncryptedKeyVersion> ParseJSONEncKeyVersion
            (string keyName, IList valueList)
        {
            IList <KeyProviderCryptoExtension.EncryptedKeyVersion> ekvs = new List <KeyProviderCryptoExtension.EncryptedKeyVersion
                                                                                    >();

            if (!valueList.IsEmpty())
            {
                foreach (object values in valueList)
                {
                    IDictionary valueMap    = (IDictionary)values;
                    string      versionName = CheckNotNull((string)valueMap[KMSRESTConstants.VersionNameField
                                                           ], KMSRESTConstants.VersionNameField);
                    byte[] iv = Base64.DecodeBase64(CheckNotNull((string)valueMap[KMSRESTConstants.IvField
                                                                 ], KMSRESTConstants.IvField));
                    IDictionary encValueMap = CheckNotNull((IDictionary)valueMap[KMSRESTConstants.EncryptedKeyVersionField
                                                           ], KMSRESTConstants.EncryptedKeyVersionField);
                    string encVersionName = CheckNotNull((string)encValueMap[KMSRESTConstants.VersionNameField
                                                         ], KMSRESTConstants.VersionNameField);
                    byte[] encKeyMaterial = Base64.DecodeBase64(CheckNotNull((string)encValueMap[KMSRESTConstants
                                                                                                 .MaterialField], KMSRESTConstants.MaterialField));
                    ekvs.AddItem(new KMSClientProvider.KMSEncryptedKeyVersion(keyName, versionName, iv
                                                                              , encVersionName, encKeyMaterial));
                }
            }
            return(ekvs);
        }
Example #12
0
        static void CreateQuotFolders(ClientContext cc, List newLib, Web _web)
        {
            List <string> folders = new List <string> {
                "1 RFQ",
                "2 Communication",
                "3 Drawings and technical specifications",
                "4 RFQ Project (LQG 1_1)",
                "5 Purchase material and external operations",
                "6 Calculations",
                "7 Quotation (LQG 1_2)",
                "8 Customer decision (Order or No order)",
                "9 Handover to project or production (LQG 2)",
                "98 Work in Progress",
                "99 Archive"
            };

            foreach (string folder in folders)
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

                itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                itemCreateInfo.LeafName             = folder;

                Microsoft.SharePoint.Client.ListItem newItem = newLib.AddItem(itemCreateInfo);
                newItem["Title"] = folder;
                newItem.Update();
                cc.ExecuteQuery();
            }
        }
 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);
 }
        public static string[] GetCNs(X509Certificate cert)
        {
            List <string>   cnList           = new List <string>();
            string          subjectPrincipal = cert.GetSubjectX500Principal().ToString();
            StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+");

            while (st.HasMoreTokens())
            {
                string tok = st.NextToken().Trim();
                if (tok.Length > 3)
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase(Sharpen.Runtime.Substring(tok, 0, 3), "CN="))
                    {
                        cnList.AddItem(Sharpen.Runtime.Substring(tok, 3));
                    }
                }
            }
            if (!cnList.IsEmpty())
            {
                string[] cns = new string[cnList.Count];
                Sharpen.Collections.ToArray(cnList, cns);
                return(cns);
            }
            else
            {
                return(null);
            }
        }
Example #15
0
        public int InsertItem <T>(T entity)
        {
            Type entityType = typeof(T);

            try
            {
                string listName = EntityHelper.GetInternalNameFromEntityType(entityType);
                using (var clientContext = GetClientContext())
                {
                    Web            web            = clientContext.Web;
                    ListCollection listCollection = web.Lists;
                    clientContext.Load(listCollection);
                    clientContext.ExecuteQuery();
                    List list = listCollection.FirstOrDefault(q => q.Title == listName);
                    if (list == null)
                    {
                        throw new ListNotFoundException();
                    }

                    ListItem newItem = list.AddItem(new ListItemCreationInformation());
                    AssignPropertiesToListItem(entity, newItem);

                    newItem.Update();
                    clientContext.ExecuteQuery();
                    return(newItem.Id);
                }
            }
            catch (Exception ex)
            {
                _log.Error($"Cannot insert data from entity of type '{entityType.Name}'", ex);
                throw;
            }
        }
 public static void SaveAttchments(FileStream fsAttachment, string NewTitle)
 {
     using (ClientContext ctx = new ClientContext(_serverURL))
     {
         SecureString passWord = new SecureString();
         foreach (char c in _userPasswordAdmin)
         {
             passWord.AppendChar(c);
         }
         ctx.Credentials = new SharePointOnlineCredentials(_userNameAdmin, passWord);
         List oList = ctx.Web.Lists.GetByTitle("BotTestAttachments");
         ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
         ListItem oListItem = oList.AddItem(itemCreateInfo);
         oListItem["Title"] = NewTitle;
         oListItem.Update();
         ctx.ExecuteQuery();
         ListItem item = oList.GetItemById(oListItem.Id);
         AttachmentCreationInformation attInfo = new AttachmentCreationInformation();
         attInfo.FileName      = fsAttachment.Name;
         attInfo.ContentStream = fsAttachment;
         item.AttachmentFiles.Add(attInfo);
         item.Update();
         ctx.ExecuteQuery();
     }
 }
Example #17
0
        private void button1_Click(object sender, EventArgs e)
        {
            string       userName       = "******";
            string       password       = "******";
            SecureString securePassword = new SecureString();

            foreach (char ch in password.ToCharArray())
            {
                securePassword.AppendChar(ch);
            }

            SharePointOnlineCredentials crendentials = new SharePointOnlineCredentials(userName, securePassword);



            using (ClientContext ctx = new ClientContext("https://spmmra.sharepoint.com/sites/MyCompany/HR/"))
            {
                ctx.Credentials = crendentials;
                Web myWeb = ctx.Web;
                ctx.Load(myWeb, wde => wde.Title);
                List lst = myWeb.Lists.GetByTitle("HRPolicyDocuments");
                ListItemCreationInformation itmCreastionInfo = new ListItemCreationInformation();
                ListItem newItem = lst.AddItem(itmCreastionInfo);
                newItem["Title"] = "My Title First and I am on the top of the moon";
                newItem.Update();
                ctx.ExecuteQuery();
                MessageBox.Show(myWeb.Title);
            }
        }
Example #18
0
        private ListItem CopyListItem(string siteURL, string listTitle, string folder, ListItem parentListItem)
        {
            using (ClientContext context = InitializeContext(siteURL))
            {
                Web  spWeb = context.Web;
                List list  = spWeb.Lists.GetByTitle(listTitle);
                context.Load(list.Fields);
                context.Load(list.RootFolder);
                context.ExecuteQuery();
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

                if (!string.IsNullOrEmpty(folder))
                {
                    itemCreateInfo.FolderUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, folder);
                }

                ListItem newItem = list.AddItem(itemCreateInfo);

                foreach (Field field in list.Fields)
                {
                    if (!field.Hidden && !field.ReadOnlyField && !string.IsNullOrEmpty(field.InternalName) && string.Compare(field.InternalName, Constants.SOProperties.ID, true) != 0 && string.Compare(field.InternalName, "Attachments", true) != 0 && parentListItem.FieldValues.ContainsKey(field.InternalName) && parentListItem[field.InternalName] != null)
                    {
                        newItem[field.InternalName] = parentListItem[field.InternalName];
                    }
                }

                newItem.Update();
                context.ExecuteQuery();
                return(newItem);
            }
        }
Example #19
0
        internal Replication ReplicationWithDatabase(Database database, Uri url, bool push, bool create, bool start)
        {
            foreach (var replication in replications)
            {
                if (replication.LocalDatabase == database &&
                    replication.RemoteUrl.Equals(url) &&
                    replication.IsPull == !push)
                {
                    return(replication);
                }
            }
            if (!create)
            {
                return(null);
            }

            var replicator = push
                ? (Replication) new Pusher(database, url, true, new TaskFactory(new SingleTaskThreadpoolScheduler()))
                : (Replication) new Puller(database, url, true, new TaskFactory(new SingleTaskThreadpoolScheduler()));

            replications.AddItem(replicator);
            if (start)
            {
                replicator.Start();
            }
            return(replicator);
        }
Example #20
0
        static void Main(string[] args)
        {
            using (ClientContext clientContext = new ClientContext("urldosite")) {
                clientContext.Credentials = new NetworkCredential("user", "passwordex");


                Web site = clientContext.Web;

                Console.WriteLine("Digite o nome da lista");

                List lista = site.Lists.GetByTitle(Console.ReadLine());

                clientContext.Load(lista);

                clientContext.ExecuteQuery();

                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

                ListItem newItem = lista.AddItem(itemCreateInfo);

                newItem["Title"] = "Novo Item";

                newItem.Update();
            }
        }
        public void RemoveEventReceiversFromHostWeb(ClientContext clientContext)
        {
            List myList = clientContext.Web.Lists.GetByTitle(LIST_TITLE);

            clientContext.Load(myList, p => p.EventReceivers);
            clientContext.ExecuteQuery();

            var rer = myList.EventReceivers.Where(
                e => e.ReceiverName == RECEIVER_NAME).FirstOrDefault();

            try
            {
                System.Diagnostics.Trace.WriteLine("Removing ItemAdded receiver at "
                                                   + rer.ReceiverUrl);

                //This will fail when deploying via F5, but works
                //when deployed to production
                rer.DeleteObject();
                clientContext.ExecuteQuery();
            }
            catch (Exception oops)
            {
                System.Diagnostics.Trace.WriteLine(oops.Message);
            }

            //Now the RER is removed, add a new item to the list
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem newItem = myList.AddItem(itemCreateInfo);

            newItem["Title"]       = "App deleted";
            newItem["Description"] = "Deleted on " + System.DateTime.Now.ToLongTimeString();
            newItem.Update();

            clientContext.ExecuteQuery();
        }
Example #22
0
        public RedirectResult NewItem(string managerName, string details, DateTime dueDate)
        {
            ClientContext clientContext = new ClientContext(SiteUrl);

            var user = clientContext.Web.EnsureUser(User.Identity.Name);

            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId = user.Id;

            var manager = clientContext.Web.EnsureUser(managerName);

            clientContext.Load(manager);
            clientContext.ExecuteQuery();
            FieldUserValue managerValue = new FieldUserValue();

            managerValue.LookupId = manager.Id;

            List spList = clientContext.Web.Lists.GetByTitle(ListName);
            var  info   = new ListItemCreationInformation();
            var  item   = spList.AddItem(info);

            item[FieldDetails] = details;
            item[FieldDueDate] = dueDate;
            item[FieldAuthor]  = userValue;
            item[FieldManager] = managerValue;
            item.Update();
            clientContext.ExecuteQuery();

            return(Redirect("Items"));
        }
Example #23
0
        public void ImportTaskRow(List list, List <ShTaskListDataItem> dataRows, ListItem parentItem = null)
        {
            foreach (var item in dataRows)
            {
                if (item.Fields.Count > 0)
                {
                    var newItemInfo = new ListItemCreationInformation();
                    var newItem     = list.AddItem(newItemInfo);

                    foreach (var fieldValue in item.Fields)
                    {
                        newItem.ParseAndSetFieldValue(fieldValue.Name, fieldValue.Value);
                    }
                    if (parentItem != null && parentItem.Id > 0)
                    {
                        newItem["ParentID"] = parentItem.Id;
                    }
                    newItem.Update();
                    Context.Load(newItem);
                    Context.ExecuteQuery();

                    if (item.Rows.Count > 0)
                    {
                        ImportTaskRow(list, item.Rows, newItem);
                    }
                }
            }
        }
        public CalendarItemModel AddCalendarItem(string siteUrl, string listName, CalendarItemModel calItem)
        {
            string realm     = ConfigurationManager.AppSettings["ida:Audience"];
            string appId     = ConfigurationManager.AppSettings["ida:ClientId"];
            string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];

            OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
            using (ClientContext context = authManager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
            {
                try
                {
                    List oList = context.Web.Lists.GetByTitle(listName);
                    ListItemCreationInformation oItemCreateInfo = new ListItemCreationInformation();
                    ListItem oItem = oList.AddItem(oItemCreateInfo);
                    oItem["Description"] = calItem.Description;
                    oItem["Location"]    = calItem.Location;
                    oItem["EventDate"]   = calItem.EventDate;
                    oItem["EndDate"]     = calItem.EndDate;
                    oItem["Author"]      = calItem.Author;
                    oItem["Editor"]      = calItem.Editor;
                    oItem.Update();
                    context.ExecuteQuery();
                    return(calItem);
                }
                catch (Exception)
                {
                    return(null);

                    throw;
                }
            }
        }
        public ActionResult Alta(Alumno alumno)
        {
            using (var context = new ClientContext("https://letias.sharepoint.com"))
            {
                var pwd = new SecureString();
                foreach (var c in "Cursill0".ToCharArray())
                {
                    pwd.AppendChar(c);
                }

                context.Credentials = new SharePointOnlineCredentials("‎[email protected]", pwd);

                List list = context.Web.Lists.GetByTitle("Alumnos");
                context.Load(list);
                var creacion = new ListItemCreationInformation();
                var item     = list.AddItem(creacion);
                item["Title"]    = alumno.Nombre;
                item["Apellido"] = alumno.Apellido;
                item["Edad"]     = alumno.Edad;
                item["Nota"]     = alumno.Nota;

                item.Update();

                context.ExecuteQuery();
            }
            String redireccion = String.Format("/?SPHostUrl={0}&SPLanguage={1}&SPClientTag{2}&" +
                                               "SPProductNumber={3}", Session["SPHostUrl"],
                                               Session["SPLanguage"], Session["SPClientTag"],
                                               Session["SPProductNumber"]);

            return(RedirectToAction("Index", "Home"));
        }
        /// <summary>Add new entries to the PendingUncached list.</summary>
        /// <param name="neededUncached">The number of replicas that need to be uncached.</param>
        /// <param name="cachedBlock">The block which needs to be uncached.</param>
        /// <param name="cached">A list of DataNodes currently caching the block.</param>
        /// <param name="pendingUncached">
        /// A list of DataNodes that will soon uncache the
        /// block.
        /// </param>
        private void AddNewPendingUncached(int neededUncached, CachedBlock cachedBlock, IList
                                           <DatanodeDescriptor> cached, IList <DatanodeDescriptor> pendingUncached)
        {
            // Figure out which replicas can be uncached.
            List <DatanodeDescriptor> possibilities = new List <DatanodeDescriptor>();

            foreach (DatanodeDescriptor datanode in cached)
            {
                if (!pendingUncached.Contains(datanode))
                {
                    possibilities.AddItem(datanode);
                }
            }
            while (neededUncached > 0)
            {
                if (possibilities.IsEmpty())
                {
                    Log.Warn("Logic error: we're trying to uncache more replicas than " + "actually exist for "
                             + cachedBlock);
                    return;
                }
                DatanodeDescriptor datanode_1 = possibilities.Remove(random.Next(possibilities.Count
                                                                                 ));
                pendingUncached.AddItem(datanode_1);
                bool added = datanode_1.GetPendingUncached().AddItem(cachedBlock);
                System.Diagnostics.Debug.Assert(added);
                neededUncached--;
            }
        }
 static void Ping(List pings)
 {
     var ping = pings.AddItem(new ListItemCreationInformation());
     ping["Title"] = DateTime.Now.ToUniversalTime();
     ping.Update();
     pings.Context.ExecuteQuery();
 }
Example #28
0
        private Folder CreateSubFolderInternalWithoutRecursion(ClientContext context, List list, Folder parentFolder, string folderName)
        {
            string folderPath = string.Concat(parentFolder.ServerRelativeUrl, '/' + folderName);

            Folder curFolder;

            try
            {
                //check is folder exists
                curFolder = parentFolder.Folders.GetByUrl(parentFolder.ServerRelativeUrl);
                context.Load(curFolder);
                context.ExecuteQuery();
            }
            catch
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                itemCreateInfo.LeafName             = folderName;
                itemCreateInfo.FolderUrl            = parentFolder.ServerRelativeUrl;
                itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                ListItem newItem = list.AddItem(itemCreateInfo);
                newItem[Constants.InternalProperties.Title] = folderName;
                newItem.Update();
                context.ExecuteQuery();

                //get current folder
                curFolder = parentFolder.Folders.GetByUrl(folderPath);
                context.Load(curFolder);
                context.ExecuteQuery();
            }
            return(curFolder);
        }
Example #29
0
        //public bool insertRecord(ClientContext _ctx, List oList, IndividualItem ind)
        public bool insertRecord(ClientContext _ctx, string LastName, IndividualItem ind)
        {
            try
            {
                List oList = _ctx.Web.Lists.GetByTitle(LastName);
                ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();
                ListItem oListItem = oList.AddItem(listCreationInformation);

                oListItem["Title"]     = ind.Title;
                oListItem["FirstName"] = ind.FirstName;
                oListItem["LastName"]  = ind.LastName;
                oListItem["Age"]       = ind.Age;
                oListItem["Gender"]    = ind.Gender;

                oListItem.Update();
                _ctx.ExecuteQuery();

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Example #30
0
        public static int SendSTaticDataToSharePoint()
        {
            #region Connexion to SharePoint
            string WebUrl         = "https://ilcomptroller.sharepoint.com/spotestsite/";
            string login          = "******";
            string password       = "******";
            var    securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
            #endregion
            #region Insert the data
            using (ClientContext CContext = new ClientContext(WebUrl))
            {
                CContext.Credentials = onlineCredentials;
                List announcementsList = CContext.Web.Lists.GetByTitle("SAMSTestList");
                ListItemCreationInformation          itemCreateInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem newItem        = announcementsList.AddItem(itemCreateInfo);

                newItem["Title"]            = "Ms.";
                newItem["First_x0020_Name"] = "R";
                newItem["Last_x0020_Name"]  = "S";
                newItem.Update();
                CContext.ExecuteQuery();
            }
            #endregion

            return(0);
        }
Example #31
0
        public static void CreateNewOrder(ClientContext ctx, Order order)
        {
            List     list = ctx.Web.GetListByTitle("Customer Orders");
            ListItem item = list.AddItem(new ListItemCreationInformation());

            item["SW_Customer"]    = order.Customer;
            item["SW_AmountMoney"] = order.Amount;
            item.Update();

            TermCollection termCollection = OrderListHelper.GetTaxonomyTermSet(ctx);
            List <KeyValuePair <Guid, String> > products_ordered = new List <KeyValuePair <Guid, string> >();

            foreach (var termItem in termCollection)
            {
                foreach (var productItem in order.Products)
                {
                    if (termItem.Name.ToString() == productItem)
                    {
                        products_ordered.Add(new KeyValuePair <Guid, string>(termItem.Id, termItem.Name.ToString()));
                    }
                }
            }
            item.SetTaxonomyFieldValues("{854C4414-A6AB-46B2-A18B-D8BD4C46E960}".ToGuid(), products_ordered);

            ctx.ExecuteQuery();
        }
Example #32
0
        public static List <FileInfo> GetAllRealatedApexFiles(DirectoryInfo apexDir, FileInfo rootApexClassName)
        {
            Stack <FileInfo> readFileNames = new Stack <FileInfo>();

            readFileNames.Push(rootApexClassName);

            List <FileInfo> apexFileFound = new List <FileInfo> {
                rootApexClassName
            };

            while (readFileNames.Count > 0)
            {
                // Need the Apex Class with out the .cls
                var apexClassName = readFileNames.Pop().Name.Replace(".cls", "");

                var apexFileList = GetFilesAsFileInfo(apexDir, "*.cls");
                foreach (var apexFile in apexFileList)
                {
                    var rootFile = File.ReadAllText(apexFile.FullName);

                    if (RelatedClassHelper.IsRelated(rootFile, apexClassName))
                    {
                        apexFileFound.AddItem(apexFile);

                        // Only push files we have not looked at.
                        if (apexFileFound.Contains((FileInfo)apexFile) == false)
                        {
                            readFileNames.Push(apexFile);
                        }
                    }
                }
            }

            return(apexFileFound);
        }
        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 #34
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 #35
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();
           }
        }
Example #36
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 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();
        }
Example #38
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());
 }
        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();
     }
 }
        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 #42
0
        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 #43
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();
 }
Example #44
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;
 }
        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;
            }
        }
        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 #47
0
        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;
            }
        }
		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 #50
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 #51
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 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);
        }
        /// <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;
        }
 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;
 }
Example #55
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 #56
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;
 }
 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;
     }
 }
Example #58
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 #59
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 #60
0
 private void AddDemoItem(List demoList, string title)
 {
     Microsoft.SharePoint.Client.ListItem item = demoList.AddItem(new ListItemCreationInformation());
     item["Title"] = title;
     item.Update();
 }