Beispiel #1
0
        private static Tuple<string, DateTime> GetFileInformation(Web web, string serverRelativeUrl)
        {
            var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));

            web.Context.Load(file, p => p.ListItemAllFields);
            web.Context.ExecuteQueryRetry();

            // TODO: fails when using sites.read.all role on xoml file download (access denied, requires ACP permission level)
            ClientResult<Stream> stream = file.OpenBinaryStream();
            web.Context.ExecuteQueryRetry();

            string returnString = string.Empty;
            DateTime date = DateTime.MinValue;

            date = file.ListItemAllFields.LastModifiedDateTime();

            using (Stream memStream = new MemoryStream())
            {
                CopyStream(stream.Value, memStream);
                memStream.Position = 0;
                StreamReader reader = new StreamReader(memStream);
                returnString = reader.ReadToEnd();
            }

            return new Tuple<string, DateTime>(returnString, date);
        }
        public override EventResult <EnterpriseResourceCollection> Execute()
        {
            EventResult <EnterpriseResourceCollection> result = new EventResult <EnterpriseResourceCollection>();

            Param.Util.LoadEnterpriseResources();

            int enterpriseResourceCount = Param.Util.ProjContext.EnterpriseResources.Count;

            Console.WriteLine("resource count is " + enterpriseResourceCount.ToString());
            for (int cnt = enterpriseResourceCount - 1; cnt > -1; cnt--)
            {
                EnterpriseResource resource = Param.Util.ProjContext.EnterpriseResources[cnt];
                if (ContainsResource(resource.Name, Param.Form.MaxResource))
                {
                    Console.WriteLine("resource name is " + resource.Name);
                    //resource.DeleteObject();
                    //resource.ForceCheckIn();
                    ClientResult <bool> ret = Param.Util.ProjContext.EnterpriseResources.Remove(resource);
                    //DeleteResource();
                    if (!ret.Value)
                    {
                        Console.WriteLine("resource name " + resource.Name + " is not deleted..");
                    }

                    if (cnt == 0 || cnt % 20 == 0)
                    {
                        Param.Util.UpdateEnterpriseResource();
                    }
                }
            }
            Param.Util.UpdateEnterpriseResource();
            result.Result = Param.Util.ProjContext.EnterpriseResources;
            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// Used to fetch user profile property from SPO.
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        static string GetSingleProfileProperty(string UserName, string PropertyName)
        {
            try
            {
                var peopleManager = new PeopleManager(_clientContext);

                ClientResult <string> profileProperty = peopleManager.GetUserProfilePropertyFor(UserName, PropertyName);
                _clientContext.ExecuteQuery();

                //this is the web service way of retrieving the same thing as client API. Note: valye of propertyname is not case sensitive when using web service, but does seem to be with client API
                //UPSvc.PropertyData propertyData = userProfileService.GetUserPropertyByAccountName(UserName, PropertyName);

                if (profileProperty.Value.Length > 0)
                {
                    return(profileProperty.Value);
                }
                else
                {
                    LogMessage("Cannot find a value for property " + PropertyName + " for user " + UserName, LogLevel.Information);
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                LogMessage("User Error: Exception trying to get profile property " + PropertyName + " for user " + UserName + "\n" + ex.Message, LogLevel.Error);
                return(string.Empty);
            }
        }
Beispiel #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cc">ClientContext object of an arbitrary site collection accessible by the defined enumeration username and password</param>
        /// <param name="keywordQueryValue">Query to execute</param>
        /// <param name="sites">List of found site collections</param>
        /// <param name="keywordQuery">KeywordQuery instance that will perform the actual queries</param>
        /// <param name="startRow">Row as of which we want to see the results</param>
        /// <returns>Total result rows of the query</returns>
        private static int ProcessQuery(ClientRuntimeContext cc, string keywordQueryValue, List <string> sites, KeywordQuery keywordQuery, int startRow)
        {
            int totalRows = 0;

            keywordQuery.QueryText = keywordQueryValue;
            keywordQuery.RowLimit  = 500;
            keywordQuery.StartRow  = startRow;
            keywordQuery.SelectProperties.Add("SPSiteUrl");
            keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending);
            SearchExecutor searchExec = new SearchExecutor(cc);
            ClientResult <ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery);

            cc.ExecuteQueryRetry();

            if (results != null)
            {
                if (results.Value[0].RowCount > 0)
                {
                    totalRows = results.Value[0].TotalRows;

                    foreach (var row in results.Value[0].ResultRows)
                    {
                        if (row["SPSiteUrl"] != null)
                        {
                            sites.Add(row["SPSiteUrl"].ToString());
                        }
                    }
                }
            }

            return(totalRows);
        }
Beispiel #5
0
        /// <summary>
        /// Saves a remote file to a local folder
        /// </summary>
        /// <param name="web">The Web to process</param>
        /// <param name="serverRelativeUrl">The server relative url to the file</param>
        /// <param name="localPath">The local folder</param>
        /// <param name="localFileName">The local filename. If null the filename of the file on the server will be used</param>
        public static void SaveFileToLocal(this Web web, string serverRelativeUrl, string localPath, string localFileName = null)
        {
            var clientContext = web.Context as ClientContext;
            var file = web.GetFileByServerRelativeUrl(serverRelativeUrl);

            clientContext.Load(file);
            clientContext.ExecuteQueryRetry();

            ClientResult<Stream> stream = file.OpenBinaryStream();
            clientContext.ExecuteQueryRetry();

            string fileOut;
            if (!string.IsNullOrEmpty(localFileName))
            {
                fileOut = Path.Combine(localPath, localFileName);
            }
            else
            {
                fileOut = Path.Combine(localPath, file.Name);
            }

            using (Stream fileStream = new FileStream(fileOut, FileMode.Create))
            {
                CopyStream(stream.Value, fileStream);
            }
        }
        public static bool CheckFileUploadedToSharePOint(string libraryName, string folderName, string FileName)
        {
            bool isFileExists = true;

            using (ClientContext context = GetContextObject())
            {
                ClientResult <Stream> stream = null;
                Web web = context.Web;
                context.Load(web, website => website.ServerRelativeUrl);
                context.ExecuteQuery();

                var docLibs = context.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 101));
                context.ExecuteQuery();

                try
                {
                    string strServerRelativeURL = string.Concat(web.ServerRelativeUrl + "/" + libraryName + "/" + folderName, "/", FileName);

                    Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL);
                    context.Load(oFile);
                    stream = oFile.OpenBinaryStream();
                    context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("File Not Found"))
                    {
                        isFileExists = false;
                    }
                }
            }
            return(isFileExists);
        }
Beispiel #7
0
        /// <summary>
        /// Places service call to search user based on the search term.
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="searchTerm">Search term</param>
        /// <returns>Set of users returned by people picker service based on the search term</returns>
        internal static IList <PeoplePickerUser> SearchUsers(ClientContext clientContext, string searchTerm)
        {
            List <PeoplePickerUser> userResult = null;
            string results = string.Empty;
            int    peoplePickerMaxRecords;

            try
            {
                ClientPeoplePickerQueryParameters queryParams = new ClientPeoplePickerQueryParameters();
                queryParams.AllowMultipleEntities    = Convert.ToBoolean(ServiceConstantStrings.PeoplePickerAllowMultipleEntities, CultureInfo.InvariantCulture);
                queryParams.MaximumEntitySuggestions = Convert.ToInt32(ServiceConstantStrings.PeoplePickerMaximumEntitySuggestions, CultureInfo.InvariantCulture);
                queryParams.PrincipalSource          = PrincipalSource.All;
                queryParams.PrincipalType            = PrincipalType.User | PrincipalType.SecurityGroup;
                queryParams.QueryString = searchTerm;
                peoplePickerMaxRecords  = Convert.ToInt32(ServiceConstantStrings.PeoplePickerMaxRecords, CultureInfo.InvariantCulture);

                ClientResult <string> clientResult = ClientPeoplePickerWebServiceInterface.ClientPeoplePickerSearchUser(clientContext, queryParams);
                clientContext.ExecuteQuery();
                results    = clientResult.Value;
                userResult = JsonConvert.DeserializeObject <List <PeoplePickerUser> >(results).Where(result => (string.Equals(result.EntityType, ConstantStrings.PeoplePickerEntityTypeUser, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(result.Description)) || (!string.Equals(result.EntityType, ConstantStrings.PeoplePickerEntityTypeUser, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(result.EntityData.Email))).Take(peoplePickerMaxRecords).ToList();
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(userResult);
        }
Beispiel #8
0
 /// <summary>
 /// This method will check whether user exists in a sharepoint site or not
 /// </summary>
 /// <param name="externalSharingRequest"></param>
 /// <returns></returns>
 public bool CheckUserPresentInMatterCenter(ClientContext clientContext, string email)
 {
     try
     {
         //If the current email is part of current organization, no need to check for validity of the user email
         if (email.Trim().ToLower().IndexOf(generalSettings.Tenant.Trim().ToLower()) > 0)
         {
             return(true);
         }
         string userAlias = email;
         ClientPeoplePickerQueryParameters queryParams = new ClientPeoplePickerQueryParameters();
         queryParams.AllowMultipleEntities    = false;
         queryParams.MaximumEntitySuggestions = 500;
         queryParams.PrincipalSource          = PrincipalSource.All;
         queryParams.PrincipalType            = PrincipalType.User | PrincipalType.SecurityGroup;
         queryParams.QueryString = userAlias;
         ClientResult <string> clientResult = ClientPeoplePickerWebServiceInterface.ClientPeoplePickerSearchUser(clientContext, queryParams);
         clientContext.ExecuteQuery();
         string results = clientResult.Value;
         int    peoplePickerMaxRecords       = 30;
         IList <PeoplePickerUser> foundUsers = Newtonsoft.Json.JsonConvert.DeserializeObject <List <PeoplePickerUser> >(results).Where(result => (string.Equals(result.EntityType, ServiceConstants.PEOPLE_PICKER_ENTITY_TYPE_USER,
                                                                                                                                                                StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(result.Description)) || (!string.Equals(result.EntityType,
                                                                                                                                                                                                                                                                          ServiceConstants.PEOPLE_PICKER_ENTITY_TYPE_USER, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(result.EntityData.Email))).Take(peoplePickerMaxRecords).ToList();
         return(foundUsers.Count > 0);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Beispiel #9
0
        /// <summary>
        /// Downloads the image and converts it to base64 strings
        /// </summary>
        /// <param name="ClientContext">client context.</param>
        /// <param name="imagePath">Includes the image path.</param>
        public static string GetImageInBase64Format(ClientContext clientContext, string imagePath)
        {
            string result = string.Empty;

            try
            {
                if (null != clientContext)
                {
                    Microsoft.SharePoint.Client.File userImage       = clientContext.Web.GetFileByServerRelativeUrl(imagePath);
                    ClientResult <Stream>            userImageStream = userImage.OpenBinaryStream();
                    clientContext.Load(userImage);
                    clientContext.ExecuteQuery();
                    if (userImage.Exists)
                    {
                        using (var newStream = new MemoryStream())
                        {
                            userImageStream.Value.CopyTo(newStream);
                            byte[] bytes = newStream.ToArray();
                            result = ConstantStrings.base64ImageFormat + Convert.ToBase64String(bytes);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ConstantStrings.LogTableName);
            }
            return(result);
        }
        public ClientResult <Guid> Add(AlertCreationInformation alertCreationInformation)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (alertCreationInformation == null)
                {
                    throw ClientUtility.CreateArgumentNullException("alertCreationInformation");
                }
                if (alertCreationInformation != null && alertCreationInformation.User == null)
                {
                    throw ClientUtility.CreateArgumentNullException("alertCreationInformation.User");
                }
            }
            ClientAction clientAction = new ClientActionInvokeMethod(this, "Add", new object[]
            {
                alertCreationInformation
            });

            context.AddQuery(clientAction);
            ClientResult <Guid> clientResult = new ClientResult <Guid>();

            context.AddQueryIdAndResultObject(clientAction.Id, clientResult);
            return(clientResult);
        }
Beispiel #11
0
        public async Task <ActionResult> GetPhoto(string url)
        {
            try
            {
                using (var clientContext = await AuthenticationHelper.GetDemoSiteClientContextAsync())
                {
                    Match  match       = (new Regex(@"(?<=\.)(\w*)")).Match(url);
                    string contentType = string.Format("image/{0}", match.Captures[match.Captures.Count - 1].Value);

                    Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(url);
                    clientContext.Load(file);
                    clientContext.ExecuteQuery();

                    ClientResult <Stream> clientResult = file.OpenBinaryStream();
                    clientContext.ExecuteQuery();

                    using (Stream stream = clientResult.Value)
                    {
                        byte[] data = new byte[stream.Length];
                        stream.Read(data, 0, data.Length);
                        return(File(data, contentType));
                    }
                }
            }
            catch
            { }

            throw new HttpException(404, "File not found");
        }
        public void ImportTerms(string termGroup, string termSet, IEnumerable <TermData> terms)
        {
            var set = getTermSet(termGroup, termSet);

            var termNames = loadAllTermNamesInSet(set);

            foreach (var term in terms)
            {
                Console.Write("Importing term '{0}' ... ", term.Term);

                ClientResult <string> normalized = Term.NormalizeName(_ctx, term.Term);
                _ctx.ExecuteQuery();
                string normalizedTermName = normalized.Value;

                if (termNames.Contains(normalizedTermName.ToLower()))
                {
                    Console.WriteLine("SKIPPING Done");
                    continue;
                }

                Console.Write("CREATING ");
                importTerm(set, term);
                termNames.Add(normalizedTermName.ToLower());   // cache so we don't have to re-load

                Console.WriteLine("Done");
            }
        }
        /// <summary>
        /// Returns the document stream for the given file name in specified library.
        /// </summary>
        /// <param name="filename">The document to find and stream.</param>
        /// <param name="libraryName">The folder name of the document location.</param>
        /// <returns> A stream containing the contents of the document. </returns>
        public async Task <byte[]> GetDocument(string filename, string libraryName)
        {
            _logger.LogInformation($"[{nameof(GetDocument)}] - Attempting to connect to SharePoint location.");

            string fileRelativeUrl = $"{_spConfig.RelativeSiteURL}/{libraryName}/{filename}";

            try
            {
                var file = _clientContext.Web.GetFileByServerRelativeUrl(fileRelativeUrl);
                _clientContext.Load(file);
                if (file is null)
                {
                    _logger.LogError($"[{nameof(GetDocument)}] - File not found: {fileRelativeUrl}");
                    return(HandleFileNotFoundExceptionWithTestPdf(new DocumentNotFoundException($"[{nameof(GetDocument)}] - File not found: {fileRelativeUrl}")));
                }

                ClientResult <Stream> stream = file.OpenBinaryStream();
                await _clientContext.ExecuteQueryAsync();

                if (stream.Value is null)
                {
                    _logger.LogError($"[{nameof(GetDocument)}] - File not stream from location: {fileRelativeUrl}");
                    return(HandleFileNotFoundExceptionWithTestPdf(new DocumentNotFoundException($"[{nameof(GetDocument)}] - File not found: {fileRelativeUrl}")));
                }

                _logger.LogInformation($"[{nameof(GetDocument)}] - File stream location: {fileRelativeUrl} completed.");
                return(stream.Value.ToByteArray());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"[{nameof(GetDocument)}] - The contract pdf file is not accessible. File: {fileRelativeUrl}");
                return(HandleFileNotFoundExceptionWithTestPdf(new DocumentNotAccessibleException("The contract pdf file is not accessible.", ex)));
            }
        }
Beispiel #14
0
        private void SaveFileToLocal(Web web, string serverRelativeUrl, string localPath, string localFileName = null, Func <string, bool> fileExistsCallBack = null)
        {
#if SP2013 || SP2016
            var file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
#else
            var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
#endif

            var clientContext = web.Context as ClientContext;
            clientContext.Load(file);
            clientContext.ExecuteQueryRetry();

            ClientResult <Stream> stream = file.OpenBinaryStream();
            clientContext.ExecuteQueryRetry();

            var fileOut = System.IO.Path.Combine(localPath, !string.IsNullOrEmpty(localFileName) ? localFileName : file.Name);

            if (!System.IO.File.Exists(fileOut) || (fileExistsCallBack != null && fileExistsCallBack(fileOut)))
            {
                using (Stream fileStream = new FileStream(fileOut, FileMode.Create))
                {
                    CopyStream(stream.Value, fileStream);
                }
            }
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            var siteurl  = "https://abc.sharepoint.com/sites/sbdev";
            var pwd      = "xxxxxxx";
            var username = "******";

            var           authManager = new AuthenticationManager();
            ClientContext context     = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteurl, username, pwd);

            // timezone
            var spTimeZone = context.Web.RegionalSettings.TimeZone;

            //context.Load(spTimeZone);
            //context.ExecuteQuery();

            //Console.WriteLine(spTimeZone.Description);


            var orginaldate = DateTime.ParseExact("14/10/2020 13:14:11", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);


            //Console.WriteLine(orginaldate);

            ClientResult <DateTime> cr = spTimeZone.UTCToLocalTime(orginaldate);

            context.ExecuteQuery();
            Console.WriteLine(cr.Value);

            Console.ReadKey();
        }
Beispiel #16
0
        protected override void OnStart(string[] args)
        {
            //if (string.IsNullOrWhiteSpace(GlobalConfig.MonitorWebUrl))
            //{
            string       url = GlobalConfig.MonitorWebUrl.TrimEnd('/') + "/OpenApi/GetConfig/";
            ClientResult r   = ApiHelper.Get(url, new
            {
            });

            if (r.success == false)
            {
                string msg = "请求" + url + "失败,请检查配置中“统一监控平台站点url”配置项";
                Core.LogHelper.Error(msg, null);
                throw new Exception(msg);
            }

            var    appconfiginfo = ApiHelper.Data(r);
            string connectstring = appconfiginfo.PlatformManageConnectString;

            Core.CoreGlobalConfig.PlatformManageConnectString = StringDESHelper.DecryptDES(connectstring, "dyd88888888");
            //}

            //Core.CoreGlobalConfig.PlatformManageConnectString = "server=192.168.17.201;Initial Catalog=dyd_bs_monitor_platform_manage;User ID=sa;Password=Xx~!@#;";
            task = new CollectVersionUpdateBackgroundTask();
            task.Start();
            System.Threading.Thread.Sleep(1000);
            task2 = new CollectUpdateBackgroundTask();
            task2.Start();
            Core.LogHelper.Log("当前服务启动完成");
        }
    //Lots more properties

    public ClientResult ToClientResult()
    {
        var clientResult = new ClientResult();

        SetupClientResult(clientResult);
        return(clientResult);
    }
        private static DateTime GetServerTime(string siteUrl, out HttpStatusCode statusCode)
        {
            DateTime dt = DateTime.MinValue;

            statusCode = HttpStatusCode.OK;

            using (ClientContext context = new ClientContext(siteUrl))
            {
                try
                {
                    Web web = context.Web;
                    context.Load(web, l => l.RegionalSettings);
                    ClientResult <System.DateTime> cr = web.RegionalSettings.TimeZone.UTCToLocalTime(DateTime.Now.ToUniversalTime());
                    context.ExecuteQuery();

                    dt = cr.Value;
                }
                catch (WebException ex)
                {
                    var webResponse = ex.Response as HttpWebResponse;
                    LogToFile("Web Response Exception", "Status Code: " + webResponse.StatusCode.ToString() + " Exception: " + ex.Message);
                    string strFolderLocation = ConfigurationManager.AppSettings["FolderLocation"];
                    System.IO.File.WriteAllText(string.Format("{0}\\LastOperationResult.txt", strFolderLocation), webResponse.StatusCode.ToString());
                }
                catch (Exception ex)
                { LogToFile("Exception", "Exception: " + ex.Message); }
            }

            return(dt);
        }
        /// <summary>
        /// returns the document stream using corresponding relative document path
        /// </summary>
        public static Stream GetStream(string id, string ext)
        {
            LLMainErr Model      = new LLMainErr();
            Stream    fileStream = null;
            string    fileName   = "";

            try
            {
                using (ClientContext ctx = GetContext())
                {
                    List olist             = ctx.Web.Lists.GetByTitle(ListName);
                    bool relativePathExist = urlDictProp.TryGetValue(Uri.EscapeDataString(id) + "." + ext, out string relativePath); //urlDictProp[id.ToString()];
                    if (relativePathExist)
                    {
                        Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByServerRelativeUrl(relativePath);
                        ctx.Load(file);
                        ClientResult <Stream> streamX = file.OpenBinaryStream();
                        ctx.Load(file);
                        ctx.ExecuteQuery();
                        fileStream = streamX.Value;
                        fileStream.Seek(0, SeekOrigin.Begin);
                        fileName = file.Name;
                    }
                    else
                    {
                        fileStream = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Model.Error = ex.Message;
            }
            return(fileStream);
        }
Beispiel #20
0
        public static Stream GetFile(string itemPath, ClientContext context)
        {
            try
            {
                /*
                 * Logic explained in example below:-
                 * itemPath = "http://sp201601/sites/academy/SiteAssets/logo/logo.png"
                 * the web url i.e. siteurl = "http://sp201601/sites/academy"
                 * the relative url i.e. siterelativeurl= "/sites/academy"
                 *
                 */
                Web web = context.Web;
                context.Load(web, w => w.Url, w => w.ServerRelativeUrl);
                context.ExecuteQuery();
                string siteurl         = web.Url;
                string siterelativeurl = web.ServerRelativeUrl;

                string url1 = siteurl.Substring(0, siteurl.LastIndexOf(siterelativeurl));

                itemPath = itemPath.Substring(url1.Length);

                Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(itemPath);
                context.Load(oFile);
                ClientResult <Stream> stream = oFile.OpenBinaryStream();
                context.ExecuteQuery();
                return(stream.Value);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #21
0
        public ClientResult Count <T>()
        {
            var res = new ClientResult();

            res.Type = "count";
            return(res);
        }
Beispiel #22
0
        public async Task <byte[]> LoadFile(string path)
        {
            using (ClientContext ctx = new ClientContext(_siteUrl))
            {
                ctx.Credentials = new SharePointOnlineCredentials(_login, _password);

                Web web  = ctx.Web;
                var file = web.GetFileByServerRelativeUrl(path);

                if (file != null)
                {
                    ClientResult <Stream> data = file.OpenBinaryStream();
                    ctx.Load(file);
                    await ctx.ExecuteQueryAsync();

                    using (MemoryStream mStream = new MemoryStream())
                    {
                        if (data != null)
                        {
                            data.Value.CopyTo(mStream);
                            return(mStream.ToArray());
                        }
                    }
                }

                return(null);
            }
        }
Beispiel #23
0
        public async Task LoadFilesData(List <FileModel> filesModels)
        {
            using (ClientContext ctx = new ClientContext(_siteUrl))
            {
                ctx.Credentials = new SharePointOnlineCredentials(_login, _password);

                Web web = ctx.Web;

                foreach (var fileModel in filesModels)
                {
                    var fileData = web.GetFileByServerRelativeUrl(fileModel.FileStorageIdentifier);
                    if (fileData != null)
                    {
                        ClientResult <Stream> data = fileData.OpenBinaryStream();
                        ctx.Load(fileData);
                        await ctx.ExecuteQueryAsync();

                        using (MemoryStream mStream = new MemoryStream())
                        {
                            if (data != null)
                            {
                                data.Value.CopyTo(mStream);
                                fileModel.FileData = mStream.ToArray();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Query SharePoint Search and fetch information about each file (URL and name).
        /// </summary>
        /// <param name="client">Existing SharePoint ClientContext</param>
        /// <param name="folderUrl">Full server folder URL</param>
        /// <returns>List of files information</returns>
        static async Task <IEnumerable <SPFileInfo> > GetFilesFromFolderAsync(ClientContext client, string folderUrl)
        {
            KeywordQuery query = new KeywordQuery(client)
            {
                QueryText = $"IsContainer=false Path:\"{folderUrl}\"",
                RowLimit  = 500
            };
            SearchExecutor searchExecutor = new SearchExecutor(client);
            ClientResult <ResultTableCollection> results = searchExecutor.ExecuteQuery(query);
            await client.ExecuteQueryAsync();

            var relevantResults = results.Value.Where(x => x.TableType == "RelevantResults").FirstOrDefault();

            if (relevantResults == null)
            {
                return(Array.Empty <SPFileInfo>());
            }

            var files = new List <SPFileInfo>();

            foreach (IDictionary <string, object> item in relevantResults.ResultRows)
            {
                var fileKey  = item.Where(x => x.Key == "Path").FirstOrDefault();
                Uri filePath = new Uri(fileKey.Value.ToString());

                files.Add(new SPFileInfo()
                {
                    ServerRelativeUrl = filePath.PathAndQuery,
                    FileName          = filePath.PathAndQuery.Substring(filePath.PathAndQuery.LastIndexOf("/") + 1)
                });
            }

            return(files);
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            var siteurl  = "https://abc.sharepoint.com/sites/sbdev";
            var pwd      = "xxxxxx";
            var username = "******";

            var           authManager = new AuthenticationManager();
            ClientContext context     = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteurl, username, pwd);

            // timezone
            var      spTimeZone  = context.Web.RegionalSettings.TimeZone;
            List     mylist      = context.Web.Lists.GetByTitle("kkkk");
            ListItem targetitems = mylist.GetItemById(17);

            context.Load(spTimeZone);
            context.Load(targetitems);
            context.ExecuteQuery();

            Console.WriteLine(spTimeZone.Description);
            Console.WriteLine(targetitems["mStartDate"] is null);

            var orginaldate = Convert.ToDateTime(targetitems["mStartDate"]);

            string strStartdate = orginaldate.ToLocalTime().ToString();

            Console.WriteLine(strStartdate);

            ClientResult <DateTime> cr = spTimeZone.UTCToLocalTime(orginaldate);

            context.ExecuteQuery();
            Console.WriteLine(cr.Value);

            Console.ReadKey();
        }
Beispiel #26
0
        private static void ReadExcelData(ClientContext clientContextobj, string FileName)
        {
            const string lstDocName = "Documents";

            try
            {
                DataTable datatable = new DataTable("TempExcelDataTable");
                List      list      = clientContextobj.Web.Lists.GetByTitle(lstDocName);
                clientContextobj.Load(list.RootFolder);
                clientContextobj.ExecuteQuery();
                string  fileServerRelativeUrl = list.RootFolder.ServerRelativeUrl + "/" + "xlsheet.xlsx";
                SP.File fileobj = clientContextobj.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl);
                ClientResult <System.IO.Stream> clientresult = fileobj.OpenBinaryStream();
                clientContextobj.Load(fileobj);
                clientContextobj.ExecuteQuery();
                using (System.IO.MemoryStream mstream = new System.IO.MemoryStream())
                {
                    if (clientresult != null)
                    {
                        clientresult.Value.CopyTo(mstream);
                        using (SpreadsheetDocument document = SpreadsheetDocument.Open(mstream, false))
                        {
                            WorkbookPart        WBPart   = document.WorkbookPart;
                            IEnumerable <Sheet> sheets   = document.WorkbookPart.Workbook.GetFirstChild <DocumentFormat.OpenXml.Spreadsheet.Sheets>().Elements <Sheet>();
                            string        relationshipId = sheets.First().Id.Value;
                            WorksheetPart WBPart1        = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
                            DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = WBPart1.Worksheet;
                            SheetData         sheetdata = worksheet.GetFirstChild <SheetData>();
                            IEnumerable <Row> rows      = sheetdata.Descendants <Row>();
                            foreach (Cell cellvalue in rows.ElementAt(0))
                            {
                                string str = GetCellValue(document, cellvalue);
                                datatable.Columns.Add(str);
                            }
                            foreach (Row row in rows)
                            {
                                if (row != null)
                                {
                                    DataRow datarow = datatable.NewRow();
                                    for (int i = 0; i < row.Descendants <Cell>().Count(); i++)
                                    {
                                        datarow[i] = GetCellValue(document, row.Descendants <Cell>().ElementAt(i));
                                    }
                                    datatable.Rows.Add(datarow);
                                }
                            }
                            datatable.Rows.RemoveAt(0);
                        }
                    }
                }
                ReadData(datatable);
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
Beispiel #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                /* Save the Context Token and Host Web URL in hidden fields
                 * These will be needed to create client contexts in subsequent calls */
                hdnContextToken.Value = TokenHelper.GetContextTokenFromRequest(Page.Request);
                hdnHostWeb.Value      = Page.Request["SPHostUrl"];

                List <AssignmentPost> posts = new List <AssignmentPost>();

                /* Create a collection of posts that mention the current user
                 * and are tagged with #Assignment. These posts are candidates
                 * to be turned into tasks for the current user */

                using (ClientContext ctx = TokenHelper.GetClientContextWithContextToken(hdnHostWeb.Value, hdnContextToken.Value, Request.Url.Authority))
                {
                    try
                    {
                        //Get current user
                        ctx.Load(ctx.Web, w => w.CurrentUser);
                        ctx.ExecuteQuery();

                        //Get posts that mention the current user
                        SocialFeedManager feedManager = new SocialFeedManager(ctx);
                        ctx.Load(feedManager);

                        SocialFeedOptions feedOptions = new SocialFeedOptions();
                        feedOptions.MaxThreadCount = 50;
                        feedOptions.SortOrder      = SocialFeedSortOrder.ByCreatedTime;
                        ClientResult <SocialFeed> feedData = feedManager.GetMentions(false, feedOptions);
                        ctx.ExecuteQuery();

                        //Build a collection of posts tagged with #Assignment
                        foreach (SocialThread thread in feedData.Value.Threads)
                        {
                            if (thread.PostReference.Post.Text.Contains("#Assignment"))
                            {
                                AssignmentPost post = new AssignmentPost();
                                post.CreatedDate = thread.RootPost.CreatedTime;
                                post.Body        = thread.PostReference.Post.Text
                                                   .Replace("#Assignment", string.Empty)
                                                   .Replace("@" + ctx.Web.CurrentUser.Title, string.Empty);
                                post.Requester = thread.Actors[thread.PostReference.Post.AuthorIndex].Name;
                                posts.Add(post);
                            }
                        }

                        //Bind these posts for display
                        assignmentPosts.DataSource = posts;
                        assignmentPosts.DataBind();
                    }
                    catch (Exception x)
                    {
                        messages.Text = x.Message;
                    }
                }
            }
        }
        public static void GetUnlabeledDocsFromSearch(ICollector <UnlabeledDocument> queueData, TraceWriter log)
        {
            Stopwatch sw = new Stopwatch();

            //var ac = new AuthenticationContext(Constants.AuthorityUri, false);
            var cert = Utils.GetCertificate(Constants.AADAppCertificateThumbprint);

            ClientAssertionCertificate cac = new ClientAssertionCertificate(Constants.AADAppClientId, cert);

            var authResult = ac.AcquireTokenAsync(Constants.ResourceUri, cac).Result;

            using (ClientContext cc = new ClientContext(Constants.TenantRootUrl))
            {
                cc.ExecutingWebRequest += (s, e) =>
                {
                    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authResult.AccessToken;
                };

                ClientResult <ResultTableCollection> results = new ClientResult <ResultTableCollection>();
                KeywordQuery keywordQuery = new KeywordQuery(cc);

                int startRow = 0;
                var defaultRetentionLabel = Environment.GetEnvironmentVariable("defaultRetentionLabel");

                sw.Start();
                do
                {
                    keywordQuery.StartRow       = startRow;
                    keywordQuery.QueryText      = Constants.KeywordQueryForComplianceTag;
                    keywordQuery.RowLimit       = 500;
                    keywordQuery.TrimDuplicates = false;

                    SearchExecutor searchExec = new SearchExecutor(cc);
                    results = searchExec.ExecuteQuery(keywordQuery);
                    cc.ExecuteQuery();

                    if (results != null)
                    {
                        if (results.Value[0].RowCount > 0)
                        {
                            foreach (var row in results.Value[0].ResultRows)
                            {
                                var path              = row["Path"].ToString();
                                var byteEncodedPath   = HttpUtility.UrlEncode(row["Path"].ToString());
                                var byteEncodedWebUrl = HttpUtility.UrlEncode(row["SPWebUrl"].ToString());

                                log.Info("Unlabeled document at: " + path);

                                queueData.Add(new UnlabeledDocument(byteEncodedWebUrl, byteEncodedPath, Constants.DefaultRetentionLabel));
                            }
                        }
                    }

                    startRow += results.Value[0].RowCount;
                } while (results.Value[0].TotalRowsIncludingDuplicates > startRow);
                sw.Stop();
                telemetry.TrackMetric("CSOM-GetUnlabeledDocs", sw.ElapsedMilliseconds);
            }
        }
        private MemoryStream convertToMemoryStream(ClientResult <Stream> documentStream)
        {
            MemoryStream documentMemoryStream = new MemoryStream();

            documentStream.Value.CopyTo(documentMemoryStream);
            documentMemoryStream.Position = 0;
            return(documentMemoryStream);
        }
Beispiel #30
0
        public ClientResult SaveBatch <T>(List <T> items, Dictionary <string, string> def, Dictionary <string, short> order)
        {
            var res = new ClientResult();

            res.Type = "save";
            res.Data = GetData <T>(items, def, order);
            return(res);
        }
Beispiel #31
0
        private static void ResponseResult(HttpContext context)
        {
            var aList = DataItem.GetList(9);

            var aResult = new ClientResult();
            aResult.DataList = aList;

            var aResultString = JsonConvert.SerializeObject(aResult);

            context.Response.Write(aResultString);
        }
Beispiel #32
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/x-json";
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            //context.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");

            var aEmail = context.Request.Form["email"];
            var aPassword = context.Request.Form["password"];

            //ResponseResult(context);

            var aList = DataItem.GetList(9);

            var aResult = new ClientResult();
            aResult.DataList = aList;
            aResult.Email = aEmail;
            aResult.Password = aPassword;

            var aResultString = JsonConvert.SerializeObject(aResult);

            context.Response.Write(aResultString);
        }
 private MemoryStream convertToMemoryStream(ClientResult<Stream> documentStream)
 {
     MemoryStream documentMemoryStream = new MemoryStream();
     documentStream.Value.CopyTo(documentMemoryStream);
     documentMemoryStream.Position = 0;
     return documentMemoryStream;
 }
        /// <summary>
        /// This method generates dynamic html based on the list item collection.
        /// </summary>
        /// <param name="clientcontext"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static string GenerateDiscussionHTML(ClientResult<ResultTableCollection> items, string errMsg)
        {
            string mostPopularHTML = string.Empty;
            StringBuilder oSb = new StringBuilder();
            try
            {
                int count = 0;

                foreach (var resultRow in items.Value[0].ResultRows)
                {
                    if (count < Convert.ToInt32(displayCount))
                    {
                        bool allowOnly = (!string.IsNullOrEmpty(Convert.ToString(resultRow["Created"])) && !Convert.ToString(resultRow["FileExtension"]).Contains("aspx") && !string.IsNullOrEmpty(Convert.ToString(resultRow["ContentTypeId"])));

                        if (allowOnly)
                        {
                            DateTime dt = (DateTime)resultRow["Created"];
                            string formattedDate = string.Format("{0:dd MMM yyyy}", dt);
                            oSb.Append("<div class='docinfo'>");
                            oSb.Append("<div class='forum-txt'>");
                            oSb.Append("<a href='" + resultRow["Path"] + "'>");
                            oSb.Append("<p class='skyblue'>" + resultRow["Title"] + "</p>");
                            oSb.Append("</a>");
                            oSb.Append("</div>");
                            oSb.Append("<div class='userinfo-forum'>");
                            oSb.Append("<div class='usrinfo-box'>");
                            oSb.Append("<a href='#' class=''>");
                            oSb.Append("<span class='blue user-txt-detail'>" + resultRow["Author"].ToString() + "</span>");
                            oSb.Append("</a>");
                            oSb.Append("<div class='icon-time-user'>");
                            oSb.Append("<span class='glyphicon glyphicon-time' aria-hidden='true'><span class='icon-txt'>" + formattedDate + "</span></span>");
                            oSb.Append("<span class='glyphicon glyphicon-comment' aria-hidden='true'><span class='icon-txt'> " + resultRow["ReplyCount"] + " Comments</span></span>");
                            oSb.Append("</div>");
                            oSb.Append("</div>");
                            oSb.Append("</div>");
                            oSb.Append("</div>");
                        }
                        else
                        {
                            count--;
                        }
                    }
                    count++;
                }

                if (oSb.Length > 0)
                {

                    // Check If Global_MostPopularDiscussion cache exists

                        CacheHelper.SaveTocache("Global_MostPopularDiscussion",oSb.ToString(),DateTime.Now.AddSeconds(60.00));

                    mostPopularHTML = oSb.ToString();
                }
            }
            catch (Exception ex)
            {
                mostPopularHTML = errMsg;
                Logger.WriteLog(Logger.Category.Unexpected, string.Format("{0}-{1}", "CommonHelper", "GenerateDiscussionHTML"), ex.StackTrace);
            }
            return mostPopularHTML;
        }
        /// <summary>
        /// This method generates dynamic html based on the list item collection.
        /// </summary>
        /// <param name="clientcontext"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static string GenerateFAQHTML(ClientResult<ResultTableCollection> items, string errMsg)
        {
            string mostPopularHTML = string.Empty;
            StringBuilder oSb = new StringBuilder();
            try
            {
                int count = 0;
                int i = 1;
                foreach (var resultRow in items.Value[0].ResultRows)
                {
                    if (count < Convert.ToInt32(displayCount))
                    {
                        bool allowOnly = (!string.IsNullOrEmpty(Convert.ToString(resultRow["LastModifiedTime"])) && !string.IsNullOrEmpty(Convert.ToString(resultRow["ContentTypeId"])));

                        if (allowOnly)
                        {
                            DateTime dt = (DateTime)resultRow["LastModifiedTime"];
                            string formattedDate = string.Format("{0:dd MMM yyyy}", dt);
                            oSb.Append("<div class='panel panel-default faq-acordian'>");
                            oSb.Append("<div class='panel-heading'>");
                            oSb.Append("<a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion' href='#collapsePop" + i + "'>");
                            oSb.Append("<h4 class='panel-title'>");
                            oSb.Append("<i class='acc-con'>");
                            oSb.Append("<span class='glyphicon glyphicon-chevron-down'></span></i>");
                            oSb.Append("<p class='accHeadtxt'><span class='skyblue'>" + formattedDate + " </span>" + resultRow["Title"] + "</p>");
                            oSb.Append("</h4>");
                            oSb.Append("</a>");
                            oSb.Append("</div>");
                            oSb.Append("<div id='collapsePop" + i + "' class='panel-collapse collapse in'>");
                            oSb.Append("<div class='panel-body acc-content'>");
                            oSb.Append("<p>" + resultRow["Answer"] + "</p>");
                            oSb.Append("</div>");
                            oSb.Append("</div>");
                            oSb.Append("</div>");
                            i++;
                        }
                        else
                        {
                            count--;
                        }
                    }
                    count++;
                }
                mostPopularHTML = oSb.ToString();
            }
            catch (Exception ex)
            {
                mostPopularHTML = errMsg;
                Logger.WriteLog(Logger.Category.Unexpected, string.Format("{0}-{1}", "CommonHelper", "GenerateFAQHTML"), ex.StackTrace);
            }
            return mostPopularHTML;
        }
 private string FormatResults(ClientResult<ResultTableCollection> results)
 {
     string responseHtml = "<h3>Results</h3>";
     responseHtml += "<table>";
     responseHtml += "<tr><th>Title</th><th>Site URL</th><th>Description</th><th>Template</th></tr>";
     if (results.Value[0].RowCount > 0)
     {
         foreach (var row in results.Value[0].ResultRows)
         {
             responseHtml += "<tr>";
             responseHtml += string.Format("<td>{0}</td>", row["Title"] != null ? row["Title"].ToString() : "");
             responseHtml += string.Format("<td>{0}</td>", row["SPSiteUrl"] != null ? row["SPSiteUrl"].ToString() : "");
             responseHtml += string.Format("<td>{0}</td>", row["Description"] != null ? row["Description"].ToString() : "");
             responseHtml += string.Format("<td>{0}</td>", row["WebTemplate"] != null ? row["WebTemplate"].ToString() : "");
             responseHtml += "</tr>";
         }
     }
     responseHtml += "</table>";
     return responseHtml;
 }