get the last modification date in a collection within sharepoint application - c#

I have an asp.net Web Api application which communicates with a sharepoint application via web services.
I add this method to create a list reference with using http request
public static SPService.Lists CreateSPServiceListsReference(HttpRequestMessage request, bool defaultEpic = true)
{
var login = EpicConfiguration.ExtractAuthenticationParameters(request);
var lists = new SPService.Lists(){
Credentials = new NetworkCredential(login.Username, login.Password, login.Domain),
Url = string.Format(SPServiceListFormat, (defaultEpic)?login.EpicWebUrl:login.RefWebUrl)
};
return lists;
}
The this the first time I have to communicate with a sharepoint app. I need to call a service which takes as a parameter the name of the list and returns the last modification date in this this list. I googled before asking this question but I didn't find a solution.
Any ideas?

You could utilize Lists.GetList Method of SharePoint Web Services to retrieve schema for the specified list and then extract Modified property which represents last modified date.
Example
using (var svc = new ListsService.Lists())
{
svc.Credentials = new NetworkCredential(userName, password, domain);
var list = svc.GetList("Pages");
var listXml = XElement.Parse(list.OuterXml);
var lastModified = listXml.Attribute("Modified").Value;
}

Related

Why does SPContext.Current return a null value?

I am new in SharePoint development and I am developing a custom SharePoint Farm Solution. I am currently having an issue with code which runs properly on the production and test environments but gives an error on the development and I don't know why. The source code looks identical in all environments. I was able to locate the error through debugging and I found that it gives an error on the following line:
SPWeb web = SPContext.Current.Web;
The code is about sending an email upon the completion of course evaluation function in my application. Here's the code:
MailConfiguration config = new MailConfiguration();
MailNotification content = config.GetMailNotification(userId, courseId);
SPWeb web = SPContext.Current.Web;
string subject = content.Subject;
string msgBody = content.Body;
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, content.To, subject, msgBody);
message = "Email sent successfully";
});
Could you please explain to me why this is happening? The SendEmail function is not working now due to this error.
Check the follows:
1.Check the alternate mapping access(AAMs). If not, configure it.
2.Check if have Site Collection at the root of the SharePoint website.
3.Use the method below to create a fake SPContext in a non-SharePoint context.
public static SPContext FakeSPContext(SPWeb web)
{
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(TextWriter.Null));
}
if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
{
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
return SPContext.Current;
}

Facebook Access Token keeps Expiring c#

I have a web application that runs a schedule job which pulls in the Facebook reviews from a page which I manage. Here is a snippet
public void Execute(IJobExecutionContext context)
{
//get api details from the web.config
var pageId = WebConfigurationManager.AppSettings["FacebookPageId"];
var token = WebConfigurationManager.AppSettings["FacebookAPIToken"];
if (!string.IsNullOrEmpty(token))
{
//create a facebook client object
var client = new FacebookClient(token);
//make a call to facebook to retrieve the json data
dynamic graphJson = client.Get(pageId + "?fields=ratings{review_text,reviewer,rating}").ToString();
//deserialize the json returned from facebook
ReviewDeserializeData reviews = JsonConvert.DeserializeObject<ReviewDeserializeData>(graphJson);
//loop through the deserialized data and pass each review to the import class
foreach (var rating in reviews.ratings.data)
{
var fbRating = new FacebookRating
{
RatingReviewerId = long.Parse(rating.reviewer.id),
StarRating = rating.rating,
ReviewerName = rating.reviewer.name,
ReviewText = rating.review_text
};
ImportFacebookRating.ImportTheFacebookRating(fbRating);
}
}
}
This works great until the Page Access Token expires. I have tried following many articles such as this one https://medium.com/#Jenananthan/how-to-create-non-expiry-facebook-page-token-6505c642d0b1#.24vb5pyiv but i have had no luck fixing the token expiring.
Does anyone know how i can achieve this or is there a way to programmatically generate a new token if the existing one has expired? at the moment i have it stored in the web.config as an app setting.
Thanks
I found the answer here and was able to generate a token that 'Never' Expires Long-lasting FB access-token for server to pull FB page info

Clear Credentials stored in Universal Windows App

I'm using Windows.Web.Http.HttpClient in Universal Windows platform (UWP). The URL needs domain credentials (NTLM) so windows opens a self defined popup for username and password. App needs a functionality to logout but I couldn;'t find a working code which can clear credentials stored by UWP.
I have tried to clear credentials from Windows.Security.Credentials.PasswordVault using following code but it didn't work:
var cred = new Windows.Security.Credentials.PasswordVault();
var pwds = cred.RetrieveAll();
foreach(var pwd in pwds)
{
pwd.RetrievePassword();
cred.Remove(pwd);
}
I'm also clearing cookies as below:
var filter = new HttpBaseProtocolFilter();
var cookieManager = filter.CookieManager;
HttpCookieCollection cookies = cookieManager.GetCookies(uri);
foreach (HttpCookie u in cookies)
{
cookieManager.DeleteCookie(u);
}
Any suggestions please?
This isn't available in Windows 10, but will be in the Anniversary Update:
var filter = new HttpBaseProtocolFilter();
filter.ClearAuthenticationCache();
You can see more on the MSDN page and if you have an Insider Preview build / SDK later than 14295 you should be able to test it.
Please look at:
https://learn.microsoft.com/en-us/windows/uwp/security/credential-locker#deleting-user-credentials
There function for deleting the credentials is described.
It seems that the method public IReadOnlyList<PasswordCredential> RetrieveAll() that you are using returns a read-only collection. Therefor its values can't be deleted.
Try to access the credentials e.g. with public PasswordCredential Retrieve(String resource, String userName). The return type which is not read-only, should enable you to use the delete methods.
If you want to delete all credentials for a specific resource name, this workaround works even in older Windows 10 versions:
private void RemoveAllCredentials(PasswordVault passwordVault)
{
//Get all credentials.
List<PasswordCredential> passwordCredentials = new List<PasswordCredential>();
var credentials = passwordVault.RetrieveAll();
foreach (PasswordCredential credential in credentials)
{
if (credential.Resource.Equals("ResourceName"))
{
passwordCredentials.Add(
passwordVault.Retrieve(credential.Resource, credential.UserName));
}
}
foreach (PasswordCredential entry in passwordCredentials)
{
passwordVault.Remove(entry);
}
}

Accessing list from Sharepoint Webservice with Sharepoint Online 2013

I am trying to access a list from sharepoint via the web services.
I have tried lots of different web reference URLS for my web service.
The list is found at :
example.com/sites/dms/_layouts/15/start.aspx#/Lists/Documents/AllItems.aspx
the Web service URL I am using now is
https://example.com/sites/dms/_vti_bin/lists.asmx
Obviously example.com is not the real URL.
when I run the code
service.GetList("Documents");
I get the error:
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
0x82000006
My full code (many things are just for testing purposes):
public void UpdateList()
{
MKLists.Lists service = GetService();
string targetSite = "https://mywebpage.com/sites/dms";
using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))
{
if (ctx != null)
{
ctx.Load(ctx.Web); // Query for Web
ctx.ExecuteQuery(); // Execute
string test = (ctx.Web.Title);
}
}
CookieCollection authCookie = ClaimClientContext.GetAuthenticatedCookies(targetSite, 925, 525);
service.CookieContainer = new CookieContainer();
service.CookieContainer.Add(authCookie);
XmlNode tester = service.GetList("Documents");
}
private MKLists.Lists GetService()
{
MKLists.Lists myService = new MKLists.Lists();
myService.Credentials = System.Net.CredentialCache.DefaultCredentials;
return myService;
}
change this line:
MKLists.Lists service = GetService();
with
MKLists.Lists service = new MKLists.Lists();
i hope this helps.
Edit
according to your comment in the answer here is the update #Michael
try changing your targetsite url to
string targetSite = "https://mywebpage.com/sites/dms/_vti_bin/Lists.asmx";
hope this time it helps
IT turns out it was to do with the subsites.. and this line solved it:
service.Url = "https://mywebpage.com/sites/dms/_vti_bin/lists.asmx";
I've found some users with the same issue.
They said that these links below solved that issue. Could you try it?
http://blogs.msdn.com/b/sharepointdev/archive/2011/05/12/connecting-to-sharepoint-online-web-services.aspx
http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx

ASP.NET Send Cookies to client Browser

I'm integrating a single sign on over 2 ASP.Net applications. For that matter i have a web service that is called by the main app. when a user logs in. this web service authenticates the user in my second application and brings back the authentication cookies i need to deliver to the client browser so he can navigate freely and logged in both applications.
I was planning to use HttpContext.Current.Response.Cookies.Add(cookie) in order to deliver the new cookies but this seems not to work as no cookies are added what so ever...
Any ideas on what might be going wrong?
here is my code:
var service = new localhost.UserManagement();
service.CookieContainer = new CookieContainer();
if (service.AuthenticateUser("test#user.pt", "test"))
{
var collection = service.CookieContainer.GetCookies(new Uri("http://localhost"));
foreach (Cookie item in collection)
{
HttpContext.Current.Response.Cookies.Add(CookieConverter(item));
}
HttpContext.Current.Response.Flush();
return true;
}
return false;
Note: CookieConverter(item) is used to convert Cookie object i receive to HttpCookie
Thanks
private HttpCookie CookieConverter(Cookie cookie)
{
var result = new HttpCookie(cookie.Name);
result.Value = cookie.Value;
result.Domain = cookie.Domain;
result.Expires = cookie.Expires;
result.Path = cookie.Path;
result.Secure = cookie.Secure;
result.HttpOnly = cookie.HttpOnly;
return result;
}
You should check:
collection is empty? Could you set braeakpoint and check collection?
where is this code located? (.aspx page, web service, http handler?)
try to create minimalistic "Cookie setter" that just add simple cookie in any way

Categories