I am using primavera webservices (version 6.2.1) to read data from a primavera database (sqlserver 2008R2) in a winform application (c#). I use http cookie container authentication mode. Before I moved my database to a new server I was able to login and read data from the primavera database successfully but when I moved DB (using backup and restore), I can still login to db but primavera webservices return null for any request.
This is my code to login:
AuthenticationService authService = new AuthenticationService( );
authService.CookieContainer = new System.Net.CookieContainer( );
authService.Url = _P6wsAuthenticationService;
Login loginObj = new Login( );
loginObj.UserName = pv_Username;
loginObj.Password = pv_Password;
loginObj.DatabaseInstanceId = 1;
loginObj.DatabaseInstanceIdSpecified = true;
loginObj.VerboseFaults = true;
loginObj.VerboseFaultsSpecified = true;
LoginResponse loginReturn = authService.Login( loginObj );
ReadDatabaseInstancesResponseDatabaseInstance[] readdbInstances = authService.ReadDatabaseInstances("");
cookieContainer = authService.CookieContainer;
When I run this code the loginresponse for new database is "true" and it shows the correct database instance information in "readdbInstances".
I run the following code to read some project info from DB:
ProjectPortBinding pbProject = new ProjectPortBinding( );
pbProject.CookieContainer = cookieContainer;
pbProject.Url = _P6wsProjectService;
ReadProjects readProject = new ReadProjects( );
Primavera.Ws.P6.Project.ProjectFieldType[] pfProject = new Primavera.Ws.P6.Project.ProjectFieldType[6];
pfProject[0] = Primavera.Ws.P6.Project.ProjectFieldType.ObjectId;
pfProject[1] = Primavera.Ws.P6.Project.ProjectFieldType.Id;
pfProject[2] = Primavera.Ws.P6.Project.ProjectFieldType.Name;
pfProject[3] = Primavera.Ws.P6.Project.ProjectFieldType.Status;
pfProject[4] = Primavera.Ws.P6.Project.ProjectFieldType.StartDate;
pfProject[5] = Primavera.Ws.P6.Project.ProjectFieldType.FinishDate;
readProject.Filter = pv_ProjectList.Equals( String.Empty ) ? String.Empty : "Id IN (" + pv_ProjectList + ")";
readProject.Field = pfProject;
Primavera.Ws.P6.Project.Project[] aProject = pbProject.ReadProjects( readProject );
it sends the request to the server but the message that I receive contains no project.
Before I moved the database I was able to read data with the same code. I changed database instance for primavera web services using its database configuration and I'm sure that it connects to the right DB, I'm just confusing why it cannot read the data from it. When I use the primavera client module to connect and read data from the new database it works fine and I can see all my projects.
Check the credentials that you are using in the user administrator front end, you will need to increase the permissions there on a module level or project level. Once you enable those you should see some data.
Kindly,
JK.
Related
From Azure DevOps portal, I can manually add file/ folder into repository irrespective of the fact that source code is cloned or not - Image for illustration.
However, I want to programmatically create a folder and a file inside that folder within a Repository from c# code in my ASP .NET core application.
Is there a Azure DevOps service REST API or any other way to do that? I'll use BASIC authentication through PAT token only.
Note : I'm restricted to clone the source code at local repository.
Early reply is really appreciated.
I tried HttpClient, GitHttpClient and LibGit2Sharp but failed.
Follow below steps in your C# code
call GetRef REST https://dev.azure.com/{0}/{1}/_apis/git/repositories/{2}/refs{3}
this should return the object of your repository branch which you can use to push your changes
Next, call Push REST API to create folder or file into your repository
https://dev.azure.com/{0}/{1}/_apis/git/repositories/{2}/pushes{3}
var changes = new List<ChangeToAdd>();
//Add Files
//pnp_structure.yml
var jsonContent = File.ReadAllText(#"./static-files/somejsonfile.json");
ChangeToAdd changeJson = new ChangeToAdd()
{
changeType = "add",
item = new ItemBase() { path = string.Concat(path, "/[your-folder-name]/somejsonfile.json") },
newContent = new Newcontent()
{
contentType = "rawtext",
content = jsonContent
}
};
changes.Add(changeJson);
CommitToAdd commit = new CommitToAdd();
commit.comment = "commit from code";
commit.changes = changes.ToArray();
var content = new List<CommitToAdd>() { commit };
var request = new
{
refUpdates = refs,
commits = content
};
var personalaccesstoken = _configuration["azure-devOps-configuration-token"];
var authorization = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken)));
_logger.LogInformation($"[HTTP REQUEST] make a http call with uri: {uri} ");
//here I making http client call
// https://dev.azure.com/{orgnizationName}/{projectName}/_apis/git/repositories/{repositoryId}/pushes{?api-version}
var result = _httpClient.SendHttpWebRequest(uri, method, data, authorization);
I have a .Net Standard client application running on UWP.
My client application contacts the server that generates a sas key like so:
var myPrivateStorageAccount = CloudStorageAccount.Parse(mystorageAccountKey);
var myPrivateTableClient = myPrivateStorageAccount.CreateCloudTableClient();
SharedAccessTablePolicy pol = new SharedAccessTablePolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(59),
Permissions = SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Add
};
CloudTable myPrivateTable = myPrivateTableClient.GetTableReference(tableName);
String sas = myPrivateTable.GetSharedAccessSignature(pol);
return sas;
My client application then runs the following:
StorageCredentials creds = new StorageCredentials(sas);
this.tableClient = new CloudTableClient(tableServiceURI, creds);
this.table = tableClient.GetTableReference(tableName);
TableQuery<DynamicTableEntity> projectionQuery = new TableQuery<DynamicTableEntity>().Select(new string[] { "DocumentName" }).Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, cc));
var res = await table.ExecuteQuerySegmentedAsync<DynamicTableEntity>(projectionQuery, null);
and gets the following error:
Server failed to authenticate the request. Make sure the value of
Authorization header is formed correctly including the signature. sr
is mandatory. Cannot be empty
but as this is tablestorage I dont think sr is required
and my SAS key looks fine to me:
?sv=2018-03-28&tn=MyTable&sig=RandomSig151235341543&st=2019-01-17T12%3A00%3A28Z&se=2019-01-17T12%3A59%3A28Z&sp=ra
so whats the problem here?
Ok so this is kind of stupid but I will post anyway.
I was sending the request to:
https://myaccount.blob.core.windows.net/
and should have been sending the request to:
https://myaccount.table.core.windows.net/
I am using Rotativa to generate a PDF from a view. It works on my localhost, but when I push to my server it does not work at all. The Server has Windows Authentication and Impersonate enabled which I need to have for this site.
This is the error I get when I try to run the code on the server
Qt: Could not initialize OLE (error 80070005) Error: Failed loading
page
https://api.mydomain.com/Reports/RedBluePDF?community=CommunityName&procedure=GetTasks
(sometimes it will work just to ignore this error with
--load-error-handling ignore) Exit with code 1 due to http error: 1003
Here is my code:
public byte[] getReportsPDF(string community, string procedure)
{
byte[] pdfBytes = new byte[] { };
RouteData route = new RouteData();
route.Values.Add("controller", "SiteSuperReports");
route.Values.Add("action", "RedBluePDF");
this.ControllerContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, this);
if (procedure == "GetProductionTasks")
{
var actionPDF = new Rotativa.ActionAsPdf("RedBluePDF", new { community = community, procedure = procedure })
{
PageSize = Size.A4,
PageOrientation = Rotativa.Options.Orientation.Landscape,
PageMargins = { Left = 1, Right = 1 }
};
try
{
pdfBytes = actionPDF.BuildFile(ControllerContext);
}
catch(Exception e)
{
Console.Write(e.Message.ToString());
}
}
return pdfBytes;
}
And here is RedBluePDF Method, this just returns a View:
public ActionResult RedBluePDF(string community, string procedure) {
return View();
}
What am I doing wrong and how come this is not working on my server, but is on my localhost? And How do I get it work on my server.
Try one of this solutions:
1- Go to IIS > Site > Authentication, click on "ASP.NET Impersonation" and DISABLE it.
2- If you're calling a script or a file or whatever, specify the used protocol:
src="//api.mydomain.com/?????
to:
src="http://api.mydomain.com/?????
3- In your Application Pool's configuration, under Process Model, there's an option "Load User Profile". It comes as False by default, set it as true.
I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!
I am trying to insert elements into a MongoLab database (Sandbox plan) using C# (by parsing a xml file, but that is not the relevant part).
var connectionString = "mongodb://user:pass#ds011111.mongolab.com:11111/db";
var server = client.GetServer();
var database = server.GetDatabase("mydb");
var elementCollection = database.GetCollection<Entity>("entities");
XmlDocument doc = new XmlDocument();
doc.LoadXml(elementxml);
XmlNodeList elementList = doc.GetElementsByTagName("element");
foreach (XmlNode element in elementList)
{
var t = new Entity();
t.Name = element.FirstChild.InnerText;
elementCollection.Insert(t); // this causes the error below
}
This is the message I get:
WriteConcern detected an error 'not authorized for insert on mydb.entities'. (Response
was { "err" : "not authorized for insert on mydb.entities", "code" : 16544, "n" : 0,
"lastOp" : { "$timestamp" : NumberLong(0) }, "connectionId" : 33932414, "ok" : 1.0 }).
If I run the same code on localhost, everything works as intended
If I insert an element using mongo/shell I get Cannot use commands write mode, degrading to compatability mode, but it works
Does this mean I cannot populate my mongolab database with data (from C#) because I do not have the right permissions as a Sandbox user? If that is the case, what are my options?
The problem seems to be that you're authenticating to the "db" database but trying to use the "mydb" database. Except for specially-privileged/admin users, most users only have access to one database, hence the not authorized error. We run all our databases with authentication on, while the MongoDB defaults, which you're likely using locally, require no authentication; that's why you're not seeing the issue locally.
You should be grabbing the DB to be used from the URI. Here's an example from our Language Center.
// Standard URI format: mongodb://[dbuser:dbpassword#]host:port/dbname
String uri = "mongodb://user:pass#host:port/db";
MongoUrl url = new MongoUrl(uri);
MongoClient client = new MongoClient(url);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(url.DatabaseName);
If that doesn't sort you out, try our connectivity troubleshooting guide. In particular, the next thing I'd look at is whether you're using the right credentials (see the section entitled "Check your database credentials").
Finally, please don't hesitate to contact us as support#mongolab.com if you continue to have issues or have any other questions.