Trying to make OneDrive connector in Windows Form app - winforms

I am making a WinForm application using C#. When i try to connect OneDrive using SharePoint Client Object Model it gives me an error of "Value cannot be null".
Please guide me where i am making mistake. I need guidance on this.
private void GetClientContext()
{
using (ClientContext clientContext = new ClientContext("https://techiesworld-my.sharepoint.com/"))
{
SecureString passWord = new SecureString();
//passtxt.Text = passWord.ToString();
//foreach (char c in passtxt.Text.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(accountxt.Text, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
MessageBox.Show(web.Title);
}
I am getting exception on clientContext.ExecuteQuery() function.

Related

Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

While creating an application using Microsoft Graph - Insufficient privileges to complete the operation

I am trying to create an application in a directory using graph API but I am getting below error -
Exception in thread "main" com.microsoft.graph.http.GraphServiceException: Error code: Authorization_RequestDenied
Error message: Insufficient privileges to complete the operation.
POST https://graph.microsoft.com/v1.0/applications
SdkVersion : graph-java/v5.6.0
SdkVersion : graph-java/v5.6.0
[...]
403 : Forbidden
[...]
This is the code that I using to create a Graph Service Client which I will use to call the Graph APIs...
private static GraphServiceClient<Request> createGraphClient() {
ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId(clientId)
.clientSecret(clientSecret)
.tenantId(b2cDirectory)
.build();
TokenCredentialAuthProvider tokenCredentialAuthProvider =
new TokenCredentialAuthProvider(scopes, clientSecretCredential);
GraphServiceClient<Request> graphClient = GraphServiceClient.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
return graphClient;
}
The graph client is successfully being created and now when I am trying to create the application using below code I am getting error which I shared above...
private static void createApplication(GraphServiceClient<Request> graphClient) {
System.out.println("Creating application...");
Application application = new Application();
application.displayName = "Test v3";
application.publicClient = new PublicClientApplication();
String appId = graphClient.applications()
.buildRequest()
.post(application)
.appId;
System.out.println("App ID: " + appId);
}
I am very sure this has something with to do with giving permission to directory to allow graph to call and create Apps, but the portal.azure.com UI I am not able to find from where it is done...
Any suggestion please.
Go to Azure AD B2C then select a random App from the list and then go to API permission...
Select the one I showed in screen shot and click on "Grant admin..." and try recalling the API.

OData V4 to access secured URI

I need to develolp a WPF application that use the OData service of a Project Online Server. When I try to reference the OData service with ODataLib V4, it doesn't work because the OData service is secure.
Anyone know a workaround for this problem ?
I found the solution.
Extract the metadata of Project Online in xml file (https://[your pwa site]/_api/ProjectData/$metadata)
Change the extension of the xml file to .edmx
Execute DataSvcUtil in your Framework directory (DataSvcUtil /in:edmxfile.edmx /out:csfile.cs /language:CSharp)
Add the csfile.cs in your .Net Project
Add the following references in your project :
- Microsoft.SharePoint.Client
- Microsoft.SharePoint.Client.DocumentManagement
- Microsoft.SharePoint.Client.Publishing
- Microsoft.SharePoint.Client.Runtime
- Microsoft.SharePoint.Client.Runtime.Windows
- Microsoft.SharePoint.Client.Taxonomy
- Microsoft.SharePoint.Client.UserProfiles
- Microsoft.SharePoint.Client.WorkflowServices
- Microsoft.SharePoint.WorkflowServices.Activities
- Microsoft SharePoint Solutions Framework
Here, an example of the code :
private const string PSDATA = "https://[your pwa site]";
ProjectOData.ReportingData context =
new ProjectOData.ReportingData(new Uri(PSDATA + "/_api/ProjectData/", UriKind.Absolute)) { IgnoreMissingProperties = true };
var username = <username>;
var password = <password>;
var secureString = new System.Security.SecureString();
foreach (char c in password.ToCharArray())
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
SharePointOnlineCredentials credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, secureString);
var authenticationCookie = credentials.GetAuthenticationCookie(new Uri(PSDATA));
context.SendingRequest += delegate (object sender, SendingRequestEventArgs e)
{
e.RequestHeaders.Clear();
e.RequestHeaders.Add("Cookie", authenticationCookie);
};
var projectQuery1 = from p in context.Projects
select p;

How do i manage the SQL Server connections in asp.net core MVC mode?

I am working on a APP's server program which using asp.net core MVC mode. And in the XXXXcontrller i never use code like "Connection.open()" and "Connection.close()",a HTTP GET action is like this.
public async Task<IActionResult> register(string phoneNum, string password, string userType)
{
//从数据库里找到m.Id和 id相同的车,赋给dbCars
var dbCars = await _context.dbUsers.SingleOrDefaultAsync(m => m.UserName == phoneNum);
// var dbCars= _context.dbCars.Where(s => s.Id == id).FirstOrDefault<dbCars>();
if (dbCars == null)//如果为空,则注册
{
//注册新用户
dbCars = new dbUsers();
dbCars.UserName = phoneNum;
dbCars.Password = password;
dbCars.UserType = userType;
dbCars.IsVerified = true;
_context.Add(dbCars);
await _context.SaveChangesAsync();
//注册完成之后,把ID、用户类型和是否认证返回回去
List<string> userInfo = new List<string>();
userInfo.Add(dbCars.Id.ToString().Trim());
userInfo.Add(dbCars.UserType.ToString().Trim());
userInfo.Add(dbCars.IsVerified.ToString());
string json = JsonConvert.SerializeObject(userInfo);
return Ok(json);
}
else //如果不为空就代表注册过了
{
return Ok("0"); //返回1代表注册过了
}
}
I wondered how should i maintain the SQL Connections when many users access this service?? Should I close these connections manually? Or it can be done automatically by some magic?? If many users access this service, do my program breaked down??
I am confused, who can give me an answer??
if you are using Entity Framework or ORM you should see and set the connection string on the web.config or if it's on a separate layer you can see the settings on the app.config. If you run the application it will use the startup project of your application connectionstring app.config(windows application) or web.config (web application)

Google User Provisiong using Google Admin SDK c# -- Google.Apis.Admin.Directory.directory_v1.cs not found

I tried authenticating with Google Admin Api-sdk But We get some file missings error which should be created by the Dlls, we are using.
Even after adding all the recommended dlls after going through many article for the same, I din get over to this. Here is the code im using.
protected void Page_Load(object sender, EventArgs e)
{
const string serviceAccountEmail = "<id>#developer.gserviceaccount.com";
const string serviceAccountCertPath = #"E:\Test.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "admin#mydomain.com";
var certificate = new X509Certificate2(serviceAccountCertPath, serviceAccountCertPassword, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser },
User = userEmail
}.FromCertificate(certificate));
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "User Provisioning",
});
User newuserbody = new User();
UserName newusername = new UserName();
newuserbody.PrimaryEmail = "Harsh#test.com";
newusername.GivenName = "Harsh";
newusername.FamilyName = "Sharma";
newuserbody.Name = newusername;
newuserbody.Password = "test#123";
User results = service.Users.Insert(newuserbody).Execute();
}
}
}
I am using this code for new user provisioning but Google.Apis.Admin.Directory.directory_v1.cs not found while debugging due to this authentication got failed. Please anybody let me know to to get Google.Apis.Admin.Directory.directory_v1.cs file. As much i know i have already added all the dlls added.
The Namespaces i am using are as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;
using DotNetOpenAuth.GoogleOAuth2;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Responses;
As per the documentation, you need to download an extra NuGet package for each API you want to use. These packages contain the generated code for that particular API.
thanks all for replying,
I managed to run it successfully, I had all the reference, Code was upto the mark as well.
The Only problem was with the admin setting there in the google admin panel.
I manage to correct them as per my request to google API's and it worked fine.

Resources