Sharepoint connection with a username and password - c#

i've searched during 2 days to resolve my problem but there is no way!
in fact, i'd like to connect to sharepoint using a user's account (there is no probleme when i use anonymous connexion).
i added a web reference of authentification and lists to use this code:
SPConnect.Authentication authSP = new SPConnect.Authentication();
SPLists.Lists spLists = new SPLists.Lists();
authSP.CookieContainer = new System.Net.CookieContainer();
authSP.AllowAutoRedirect = true;
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
if (loginSP.ErrorCode == SPConnect.LoginErrorCode.NoError)
{
spLists.CookieContainer = authSP.CookieContainer;
//object list = spLists.GetList("presentationAccueil");
SPSite oSiteCollection = SPContext.Current.Site;
SPList listeee = oSiteCollection.AllWebs["http://vmspprod:25401"].Lists["presentationAccueil"];
}
i get this erro NotInFormsAuthenticationMode when i execute
SPConnect.LoginResult loginSP = authSP.Login("administrateur", "pass");
is there any other method to use a user's login and password?
Thank you in advance for your answers.

You need to configure your SharePoint server to use Forms Authentication (that's what the exception is telling you).
You didn't say which version of SharePoint you are targeting (WSS 3.0, SP 2007, SP 2010). Here is a link to an MSDN page that shows you how to configure your server to use Forms Authentication: http://msdn.microsoft.com/en-us/library/bb975136(v=office.12).aspx
If you cannot modify the server, then you will need to change your code to use whatever authentication mechanism the server employs.
I hope this helps.

Related

SharePoint 2013: Why getting 500 error while creating clientContext?

I want to create a IIS webservice which has to write list items to SharePoint on Premise.
I want to use CSOM and try to create a ClientContext.
public string AddListItem()
string result = string.Empty;
string siteUrl = "https://serverUrl";
using (ClientContext context = new ClientContext(siteUrl))
{
context.Credentials = new NetworkCredential("User", "Password", "Domain");
List list = context.Web.Lists.GetByTitle("Test");
context.Load(list);
context.ExecuteQuery();
}
return result;
}
While executing, I get an error at context.ExecuteQuery();
System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error.'
In the Event Log, I see following error:
WebHost failed to process a request.
Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/41028758
Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/client.svc' cannot be activated due to an exception during compilation. The exception message is: Operation is not valid due to the current state of the object.. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.Administration.SPWebApplication.get_Context()
................................
In debugging, I also see after creating the ClientContext and before context.ExecuteQuery(); following error at some properties of ClientContext, e.g.:
ServerLibraryVersion = 'context.ServerLibraryVersion' threw an exception of type 'Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException'
Your code seems fine for on-prem SharePoint. I think You should check some settings on the farm that my be the cause of that.
Please check the services on farm server if the IIS Admin Service is on
also on SharePoint CA check the user profile service and the claims to windows token service (both should be on)
... sorry for the lang :)... usually I have access to SharePoint in PL language, but I tried to translate the most important stuff to ang.
Please also check if on IIS the app pools that You try to access are working correctly. I suppose yes, otherwise You would have a lot of other errors, but it's always better to check.
Use CSOM, what to use WCF is not clear:
ClientContextctx = newClientContext("http://gowtham.sharepoint.com");
List oList = ctx.Web.Lists.GetByTitle("Announcements");
ListItemCreationInformationitemCreateInfo = newListItemCreationInformation();
ListItemnewItem = oList.AddItem(itemCreateInfo);
newItem["Title"] = "Test Item!";
newItem["Body"] = "welcome to Gowtham Blog";
newItem.Update();
context.ExecuteQuery();
Try below code
using (ClientContext clientContext = new ClientContext(ServerURL))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(your_mail_ID, securePassword);
Web web = clientContext.Web;
var list = web.Lists.GetByTitle("your_list_name");
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
}
Check if the "SharePoint Web Servies Root" application pool was stopped or the "SharePoint Web Services" web application not start in IIS.
Go to IIS Application Pools, find the "SecurityTokenServiceApplicationPool" and click "Advanced Settings" from the action panel, then Scroll to "ProcessModel" section and change the Identity to your SharePoint Farm Account and do IISRESET.
And create a console application with the CSOM C# code to check if it works.
FWIW - I had exactly the same error - CSOM local mode to on-prem SP2016 with a 500 error requesting the list by title.
I had just applied a 10/2019 SharePoint update, but hadn't gone through Product Configuration Wizard and the prompts in Central Admin. Once I did that, CSOM requests worked again.

UWP create VPN connection

Currently I'm trying to figure out, how to add a VPN profile and connect to it from my universal app. I can connect to existing VPN connections with the Windows.Networking.Vpn namespace. I can also add a profile, but can not find a way to set all the required information (PSK for example). There is no documentation about this namespace in the MS docs. I also saw that there are two different profile namespaces available: VpnNativeProfile and VpnPlugInProfile. What is the difference between them? Currently I'm not at home, so I can't provide my current code, but it would be very helpful if someone can give me some hints. Is there a documentation available somewhere else?
Edit 1//
Here is my sample Code
Creating a profile
VpnManagementAgent mgr = new VpnManagementAgent();
VpnNativeProfile profile = new VpnNativeProfile()
{
AlwaysOn = false,
NativeProtocolType = VpnNativeProtocolType.L2tp,
ProfileName = "MyConnection",
RememberCredentials = true,
RequireVpnClientAppUI = true,
RoutingPolicyType = VpnRoutingPolicyType.SplitRouting,
TunnelAuthenticationMethod = VpnAuthenticationMethod.PresharedKey,
UserAuthenticationMethod = VpnAuthenticationMethod.Mschapv2,
};
profile.Servers.Add("vpn.example.com");
VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
Connecting to the VPN
PasswordCredential credentials = new PasswordCredential
{
UserName = "username",
Password = "password",
};
VpnManagementErrorStatus connectStatus = await mgr.ConnectProfileWithPasswordCredentialAsync(profile, credentials);
This works, but i don't know where or how to set the PSK.
VPN Native Profile : This refers to a Windows Inbox / Built-In VPN profile and can be used for L2TP, PPTP or IKEv2 based VPN
VPN Plugin Profile : Refers to a Windows 10 UWP based VPN Plugin. This is a VPN app written using the Windows.networking.VPN namespace.
I also took a peek at the code and can see that there seems to be a very obvious miss where there isnt really a way to set the PSK via the code. The only real workaround would be to set it in the Settings UI for now.
I will go ahead and report to the VPN team for Windows about this being missing.
Documentation Link : https://learn.microsoft.com/en-us/uwp/api/windows.networking.vpn

Sharepoint Client Object Model edit Author and Editor fields

I'm trying to put the current user logged in my MVC 5 application (with windows authentication) into the Author and Editor fields of a new ListItem.
I didn't succeed to just pass the user credentials to the SharePoint Client context, so I tried to edit these two fields instead using SharePoint Client Object Model
using SP = Microsoft.SharePoint.Client;
...
SP.User SPuser = context.Web.EnsureUser(Request.LogonUserIdentity.Name);
//SP.User SPuser = context.Web.EnsureUser("mydomain\\someuser"); //same result as above
context.Load(SPuser);
context.ExecuteQuery();
SP.FieldUserValue userValue = new SP.FieldUserValue();
userValue.LookupId = SPuser.Id;
SP.ListItem documentLi = documentFile.ListItemAllFields;
...
//We don't want the application pool identity here, but the current user
documentLi["Author"] = userValue;
documentLi["Editor"] = userValue;
documentLi.Update();
context.ExecuteQuery();
It works fine in localhost, but nothing happens when I try it on the server : these two fields keeps the application pool identity.
What did I miss ?
I found what was the problem : in localhost the application pool identity is my user which has full control on the sharepoint list unlike the application pool identity in IIS (it just had contribute permission), it worked fine once I promoted it with full control as well.

Download using WebClient - IIS Basic Authentication

I am using this to download html content from a site published on IIS:
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultCredentials;
string html = client.DownloadString("http://site.com");
}
But when the IIS is set to Basic Authentication this doesn't works. The user already type user and password on the IIS dialog box.
There is a way to make this work without pass a user and password again?
I suspect that basic authentication is going to need the password, so I suspect you'll need a new System.Net.NetworkCredential("your-username","your-password"). The default credential would work with integrated auth, but not (AFAIK) basic. So in answer to:
There is a way to make this work without pass a user and password again?
No, I don't think so.
Searching more, I found this:
HttpApplication context = (HttpApplication)HttpContext.Current.ApplicationInstance;
string authHeader = context.Request.Headers["Authorization"];
string userNameAndPassword = Encoding.Default.GetString(
Convert.FromBase64String(authHeader.Substring(6)));
string[] parts = userNameAndPassword.Split(':');
Response.Write(userNameAndPassword);
We can get user and password when the IIS is set do basic authentication!
I use the following code for the NTLM authentication with default credentials
webClient.Proxy = WebRequest.GetSystemWebProxy();
webClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
One day I researched the problem and found this working. However, with .Net 4.0 my Visual Studio says GetSystemWebProxy is currently deprecated.

TFS API using c#

I have find all collection from TFS all are fine. but i am not Understand why get username and password in windows security essential dialog to save TFS username and Password and URL . Please share to me .
This is one main problem in client machine.
Sample code
Uri configurationServerUri = new Uri("http://your-server:8080/tfs");
TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
ITeamProjectCollectionService tpcService = configurationServer.GetService<ITeamProjectCollectionService>();
foreach (TeamProjectCollection tpc in tpcService.GetCollections())
{
List.add(tpc .name);
}
windows screen
Try to use TfsConfigurationServer Constructor (Uri, ICredentials) instead of TfsConfigurationServer Constructor (Uri), then you can specify the credentials that are used to authenticate the user to the server, as #Lasse V. Karlsen mentioned in comment.

Categories