Impersonate core service in Tridion 2011 SP1 HR1 - tridion

I am trying to impersonate the Core Service in Tridion 2011 SP1 HR1 and I get this error:
The message could not be processed because the action
'http://www.sdltridion.com/ContentManager/CoreService/2011/ISessionAwareCoreService/Impersonate' is invalid or unrecognized.
Why does this happen? I have to be blind to not see why it isn't working...
About the server: new installation of Tridion 2011 SP1 HR1
My code looks like this:
client = Client.GetCoreService();
if (string.IsNullOrEmpty(username)) username = HttpContext.Current.User.Identity.Name;
client.Impersonate(username);
and this is the GetCoreService method:
public static SessionAwareCoreServiceClient GetCoreService()
{
AppSettingsReader reader = new AppSettingsReader();
string coreServiceUrl = (string)reader.GetValue("CoreServiceEndPoint", typeof(string));
int dataSize = (int)reader.GetValue("DataSize", typeof(int));
var quotas = new System.Xml.XmlDictionaryReaderQuotas
{
MaxStringContentLength = dataSize,
MaxArrayLength = dataSize,
MaxBytesPerRead = dataSize
};
var httpBinding = new WSHttpBinding
{
MaxReceivedMessageSize = 10485760,
ReaderQuotas = quotas,
Security = { Mode = SecurityMode.Message, Transport = { ClientCredentialType = HttpClientCredentialType.Windows } }
};
var endpoint = new EndpointAddress(coreServiceUrl);
var result = new SessionAwareCoreServiceClient(httpBinding, endpoint);
return result;
}
extract from appsettings (replaced actual hostname with "hostname"):
<add key="CoreServiceEndPoint" value="http://hostname/WebServices/CoreService.svc/wsHttp_2010" />
<add key="DataSize" value="41943040" />

Take a look at this sample from an open source project for notification which does what you need
http://code.google.com/p/tridion-notification-framework/source/browse/NotificationService/NotificationService/CoreService/Client.cs
Here is the working line which impersonates
public static SessionAwareCoreServiceClient GetCoreService()
{
var result = GetNewClient<SessionAwareCoreServiceClient>();
result.Impersonate(ConfigurationManager.AppSettings.Get("adminUser"));
return result;
}
Also take a look at the way the client is created in the sample in the same CS file, and the App Settings. I think you are using an old endpoint address, it should be http://hostname/webservices/CoreService2011.svc/wsHttp rather than http://hostname/WebServices/CoreService.svc/wsHttp_2010

You are connecting to an old Core Service wsHttp endpoint.
If you are using the 2011 SP1 client, you need to connect to the following endpoint instead:
http://hostname/webservices/CoreService2011.svc/wsHttp

Related

EPPLUS package works fine locally but returns Internal server error when deployed to azure server

I have my web api that uploads and reads an excel file from the client app and then afterwards saves the data into the database, the application works perfect on locally server but the problem comes when the application is deployed to azure server it returns error 500 internal server error therefore i don't understand why this happens and and don't know how i can track to understand what might be the cause below are my code blocks.
My Interface Class
public interface UploadExcelInterface
{
Task UploadMultipleClients(Client obj);
}
My Service Implementation
public class UploadExcelService : UploadExcelInterface
{
private readonly DbContext _connect;
private readonly IHttpContextAccessor httpContextAccessor;
public UploadExcelService(DbContext _connect, IHttpContextAccessor httpContextAccessor)
{
this._connect = _connect;
this.httpContextAccessor = httpContextAccessor;
}
public async Task UploadMultipleClients(Client obj)
{
var file = httpContextAccessor.HttpContext.Request.Form.Files[0];
if (file != null && file.Length > 0)
{
var folderName = Path.Combine("Datas", "ClientUPloads");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
var fileName = Guid.NewGuid() + ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var clientsList = new List<Client>();
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
FileInfo excelFile = new FileInfo(Path.Combine(pathToSave, fileName));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(excelFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowcount; row++)
{
var Names = (worksheet.Cells[row,2].Value ?? string.Empty).ToString().Trim();
var Address = (worksheet.Cells[row,3].Value ?? string.Empty).ToString().Trim();
var Title = (worksheet.Cells[row,4].Value ?? string.Empty).ToString().Trim();
var Product = (worksheet.Cells[row,5].Value ?? string.Empty).ToString().Trim();
var Order = (worksheet.Cells[row,6].Value ?? string.Empty).ToString().Trim();
var Email = (worksheet.Cells[row,7].Value ?? string.Empty).ToString().Trim();
var Price = (worksheet.Cells[row,8].Value ?? string.Empty).ToString().Trim();
clientsList.Add(new Client
{
Names = Names,
Address = Address,
Title = Title,
Product = Product,
Order = Order,
Email = Email,
Price = Price,
}
}
//adding clients into the database
foreach (Client client in clientsList)
{
var exist = _connect.client.Any(x => x.Email == client.Email);
if (!exist)
{
await _connect.client.AddAsync(client);
}
}
await _connect.SaveChangesAsync();
}
}
}
My Controller Class
[HttpPost]
public async Task UploadMultipleClients([FromForm] Client obj)
{
await uploadExcelInterface.UploadMultipleClients(obj);
}
}
Please any help regarding this error that am getting from the server, and addition on that is it possible to get the data from the excel file without uploading it to server if yes how? because i tried adding the file to memory stream an reading it from memory but it appers not work, any suggestions thanks.
My answer may not help you solve the problem directly, but it can locate the error step by step. After we fix the error, we should be able to solve the problem in this thread.
Suggestions
Please make sure you have inclue EPPlus library in your deploy content.
Enabling ASP.NET Core stdout log (Windows Server)
Azure App Service - Configure Detailed Error Logging
Why
After tested, I am sure azure webapp can support EPPlus. For 500 error, as we don't have a more specific error message to refer to, we can't quickly locate the problem. Following the suggested method, you will surely see some useful information.
E.g:
The class library of EPPlus was not found.
Folders such as Datas are not created.
The database connection string, the test environment and the production environment may be different.
...

Can I able to use default proxy for cosmos db project

I have done a service using cosmos db and asp.net core .For WiFi it is working but when i try with default proxy it give the error.
SocketException: Resource temporarily unavailable
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
HttpRequestException: Resource temporarily unavailable
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
DocumentClient Create code example:
public async Task<IEnumerable<Product>> FetchProductListAsync(
Guid? itemId)
{
var feedOptions =
new FeedOptions
{
MaxItemCount = -1,
EnableCrossPartitionQuery = true
};
var query =
$"SELECT product.Id,product.Name,product.MethodOfPreparation,product.Addons,product.CurrentQuantity,product.Tag,product.Unit,product.Price FROM catalog join industry in catalog.Industy join category in industry.Category join Subcategory in category.Subcategory join product in Subcategory.Product where catalog.id = '" + itemId + "'";
var queryDefinition =
new SqlQuerySpec(query);
var orderDocumentQuery =
_docClient.CreateDocumentQuery<Product>(
UriFactory.CreateDocumentCollectionUri(
_azureCosmosDbOptions.Value.DatabaseId, "catalog"), queryDefinition, feedOptions)
.AsDocumentQuery();
var childrenSqlQuery = _docClient.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(_azureCosmosDbOptions.Value.DatabaseId, "catalog"), query).ToString();
Console.WriteLine(childrenSqlQuery);
Console.WriteLine(childrenSqlQuery);
var orderList =
new List<Product>();
while (orderDocumentQuery.HasMoreResults)
{
orderList.AddRange(
await orderDocumentQuery.ExecuteNextAsync<Product>());
Console.WriteLine(orderList);
}
return orderList;
}
I am using DucumentDb.Core 2.4.1,Please give me idea .
In node js sdk, you could set the ProxyUrl property directly.(How to use DocumentDB behind a Proxy in NodeJS)
However,it doesn't have such properties in the .NET sdk. You could try below configuration from this case:CosmosDB C# SDK ProyUrl missing
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
However,i noticed that it only supports .net,not for .net core,from this trace.So, please refer to this case:asp.net core defaultProxy

Is it possible in a .NET Core application to retrieve a certificate from AWS Certificate Manager and use it in a HttpClient post?

My .Net core application makes a post request to an external web service using HttpClient. The external web service requires a certificate to validate against.
The certificates are installed in AWS and I have an ARN that points to the certificate.
Is it possible to get the certificate programitically from AWS Certificate Manager and use this in my HtppClient, for example this is the code I would use normally to add a certificate but I need to get it from AWS.
private HttpClientHandler HttpClientHandler()
{
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
SslProtocols = SslProtocols.Tls12
};
handler.ClientCertificates.Add(new X509Certificate2("cert.crt")); //TODO: fetch from AWS.
return handler;
}
So, it's possible.
I installed AWSSDK.Core and AWSSDK.CertificateManager from NuGet.
Then, I created a credentials file for AWS, see instructions from Amazon
https://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html
Next, I used the AmazonCertificateManagerClient to get the certificate.
AmazonCertificateManagerClient client = new AmazonCertificateManagerClient();
var certificates = client.GetCertificateAsync(arn).Result;
I then converted the certificate from string to bytes and then add to the handler.
var handler = new HttpClientHandler{
ClientCertificateOptions = ClientCertificateOption.Manual,
SslProtocols = SslProtocols.Tls12
};
byte[] toBytes = Encoding.ASCII.GetBytes(certificates.Certificate);
var cert = new X509Certificate2(toBytes);
handler.ClientCertificates.Add(cert);
var httpClient = new HttpClient(handler);
Obviously, not production worthy code, hope it helps.
As mentioned by Zack the accepted answer does not work. It does retrieve a certificate out of ACM but it is not usable as a client certificate for HttpClient because it has no private key.
As far as I can tell there is no way to get the private key out of ACM so I ended up putting it in SecretsManager and doing something like:
var certManagerClient = new AmazonCertificateManagerClient();
var awsCert = certManagerClient.GetCertificateAsync(arn).Result;
byte[] awsBytes = Encoding.ASCII.GetBytes(awsCert.Certificate);
var cert = new X509Certificate2(awsBytes);
var secretsManagerClient = new AmazonSecretsManagerClient();
var privateKey = secretsManagerClient.GetSecretValueAsync(new GetSecretValueRequest { SecretId = secretId }).Result.SecretString;
byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
var privateKey = RSA.Create();
privateKey.ImportRSAPrivateKey(new ReadOnlySpan<byte>(privateKeyBytes), out _);
var certWithPrivateKey = cert.CopyWithPrivateKey(privateKey);
And then using certWithPrivateKey in my HttpClientHandler:
var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual };
handler.ClientCertificates.Add(certWithPrivateKey);
If you use the AWS SDK you can get certificates using the AmazonCertificateManagerClient. See the AWS SDK documentation for details. (select Amazon.CertificateManager > AmazonCertificateManagerClient)

How to invoke webservice from sql server 2008?

I am working on asp.net(4.0) web application for database i have SQL SERVER 2008. I have created one Web Service, its functionality is to insert data into database. I have deployed my Web Service on the local IIS, in browser its working fine mean it is inserting data in database but my task is to create a procedure that will pass parameters to the Web Service and then Web Service will insert that data. I have tried many thing for this but could complete this task. Any idea that how i can invoke Web Service from SQL SERVER.
I have tried many things like below link and similar techniques that are mention on this URL
http://www.sqlservergeeks.com/forums/microsoft-data-platform/sql-server-bi/9/sql-programming-calling-the-web-service-thru-sql
I have also tried end point but couldn't complete. Even HelloWork method is not getting called from SQL SERVER.
Web Service Name WebService1.asmx
Method public string SaveRecord(string a, string b, string c, string d)
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string SaveRecord(string userid, string fname, string lname, string email)
{
//here is my code to save records is database
return "";
}
It is possible to call web service from sql server through integration with SQLCLR. Below is code snippet of CLR trigger which received data about deleted records from DB and send it to remote through web service call.
[SqlTrigger(Name = "OnDelete", Target = "Contact1", Event = "FOR DELETE")]
public static void OnDelete()
{
string recid, accountno, address3;
recid = accountno = address3 = string.Empty;
var sqlContext = SqlContext.TriggerContext;
using (var connection = new SqlConnection("context connection=true"))
{
var command = new SqlCommand("SELECT recid, accountno, address3 FROM DELETED; ", connection);
connection.Open();
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
recid = reader[0].ToString();
accountno = reader[1].ToString();
address3 = reader[2].ToString();
}
}
}
if (!string.IsNullOrEmpty(address3))
{
var token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "organization";
using (var crmService = new CrmService())
{
crmService.Url = "http://domain:5555/MSCRMServices/2007/CrmService.asmx";
crmService.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
crmService.CrmAuthenticationTokenValue = token;
crmService.UnsafeAuthenticatedConnectionSharing = true;
crmService.PreAuthenticate = true;
crmService.Delete(EntityName.contact.ToString(), new Guid(address3));
}
}
}

How to create an exe for a web application?

I had developed a web application using Visual studio 2012 (ASP.Net 4.5 - C#) and a web service. Both are laying in a single solution. I need to convert my solution to an EXE file (Creating EXE for my web application). What i need exactly is, if run my setup file, it should host my web application and web service in IIS. Kindly provide the steps to solve me the problem.
Quiet a late answer:
I cannot post the whole project here but i'll post the flow chart here and you may try it.
All the steps in the flowchart here should be controlled programmatically.
1. Steps in starting the application.
NOTE: Please ignore the third layer (Is website added) if you are using a local database(.mdf)
The connection string to be used for a local database:
public string ConnectionString =
"Data Source=(local);Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True";
But still remember that you need dotnet framework to be installed inorder to run your application. don't worry as you can set the pre-requisites in your application setup project.
All the codes for the flowchart process below.
Is IIS Installed:
NOTE: I am posting the code for IIS 7 and above.
public bool IsIISInstalled()
{
return Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp",
"VersionString", null) != null;
}
Install IIS
public int InstallIIS()
{
string DISM_CMD_CODE = "START /WAIT DISM /Online /Enable-Feature /FeatureName:IIS-ApplicationDevelopment /FeatureName:IIS-ASP /FeatureName:IIS-ASPNET /FeatureName:IIS-BasicAuthentication /FeatureName:IIS-CGI /FeatureName:IIS-ClientCertificateMappingAuthentication /FeatureName:IIS-CommonHttpFeatures /FeatureName:IIS-CustomLogging /FeatureName:IIS-DefaultDocument /FeatureName:IIS-DigestAuthentication /FeatureName:IIS-DirectoryBrowsing /FeatureName:IIS-FTPExtensibility /FeatureName:IIS-FTPServer /FeatureName:IIS-FTPSvc /FeatureName:IIS-HealthAndDiagnostics /FeatureName:IIS-HostableWebCore /FeatureName:IIS-HttpCompressionDynamic /FeatureName:IIS-HttpCompressionStatic /FeatureName:IIS-HttpErrors /FeatureName:IIS-HttpLogging /FeatureName:IIS-HttpRedirect /FeatureName:IIS-HttpTracing /FeatureName:IIS-IIS6ManagementCompatibility /FeatureName:IIS-IISCertificateMappingAuthentication /FeatureName:IIS-IPSecurity /FeatureName:IIS-ISAPIExtensions /FeatureName:IIS-ISAPIFilter /FeatureName:IIS-LegacyScripts /FeatureName:IIS-LegacySnapIn /FeatureName:IIS-LoggingLibraries /FeatureName:IIS-ManagementConsole /FeatureName:IIS-ManagementScriptingTools /FeatureName:IIS-ManagementService /FeatureName:IIS-Metabase /FeatureName:IIS-NetFxExtensibility /FeatureName:IIS-ODBCLogging /FeatureName:IIS-Performance /FeatureName:IIS-RequestFiltering /FeatureName:IIS-RequestMonitor /FeatureName:IIS-Security /FeatureName:IIS-ServerSideIncludes /FeatureName:IIS-StaticContent /FeatureName:IIS-URLAuthorization /FeatureName:IIS-WebDAV /FeatureName:IIS-WebServer /FeatureName:IIS-WebServerManagementTools /FeatureName:IIS-WebServerRole /FeatureName:IIS-WindowsAuthentication /FeatureName:IIS-WMICompatibility /FeatureName:WAS-ConfigurationAPI /FeatureName:WAS-NetFxEnvironment /FeatureName:WAS-ProcessModel /FeatureName:WAS-WindowsActivationService";
string command = DISM_CMD_CODE;
ProcessStartInfo pStartInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
Process p = new Process();
p.StartInfo = pStartInfo;
//p.WaitForExit();
p.Start();
return 1;
}
Is Website added
public bool IsWebsiteAddedInIIS(string WebsiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == WebsiteName);
if (site == null)
{
//No site added
return false;
}
else
{
//site added
return true;
}
}
public int CreateNewWebsite(string SiteName, string PublishedFilesPath)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site == null)
{
serverManager.Sites.Add(SiteName, "http", "*:8080:", PublishedFilesPath);
serverManager.CommitChanges();
return 1;
}
else
{
return 2;
}
}
public void StartWebsite(string SiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site != null)
{
site.Stop();
site.Start();
}
}
public void StopWebsite(string SiteName)
{
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
if (site != null)
{
site.Stop();
}
}
Get website URL
public string GetWebsiteURL(string SiteName)
{
//string SiteUrl = "";
//ServerManager serverManager = new ServerManager();
//var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
//var siteBindings = site.GetCollection("bindings");
//string protocol = (string)siteBindings["protocol"];
//string bindingInfo = (string)siteBindings["bindingInformation"];
//if (protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
//{
// string[] parts = bindingInfo.Split(':');
// if (parts.Length == 3)
// {
// //Get the port in use HERE !!!
// string port = parts[1];
// SiteUrl = "localhost:" + port;
// }
//}
//return SiteUrl;
int port = 0;
string SiteUrl = "";
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites.FirstOrDefault(s => s.Name == SiteName);
foreach (Binding binding in site.Bindings)
{
port = binding.EndPoint.Port;
SiteUrl = "localhost:" + port + "/index.aspx";
break;
}
return SiteUrl;
}
Init Browsing the website
You have to install Cefsharp chromium browser to your windows forms
Install-Package CefSharp.WinForms -Version 75.1.143
public void InitBrowser(string Address)
{
Cef.Initialize(new CefSettings());
browser = new ChromiumWebBrowser(Address);
Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
Thank you..
Maybe you need to create a web setup project. "A Web setup project provides the
highest level of flexibility for deploying a website. Although Web Setup Projects are more
complex for the developer, they allow you to generate an MSI package, precompile a website,
and perform virtually any setup task that your application might require.
Many websites do not require custom configuration. In these cases, you can simply build
your MSI file and be ready to deploy. However, more complex scenarios include dependencies
(such as particular operating system versions or service packs), custom registry entries,
or administrator configuration. Web Setup Projects allow you to deploy websites that meet
these requirements."
Check the book "MCTS Self-Paced Training Kit (Exam 70-515) - Web Applications Development with Microsoft .NET Framework 4" at the chapter 8 "Debugging and deploying".
Hope this helps.

Resources