ASP.NET / IIS loading X509Certificate.LoadCertificateFromFile - asp.net

I am trying to load a certificate in a class that is hosted in IIS.
The code that i used is:
X509Certificate2 privateCertificate = new X509Certificate2(#"C:\Temp\file.pfx", "mycertpass");
Later on in my code when privateCertificate is used it causes a problem on the production environment. This problem does not occur on the local environment, the exception is as follows:
Exception information:
Exception type: CryptographicException
Exception message: An internal error occurred.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
at Medapp.PaymentResponse.CreateRepository()
at Medapp.PaymentResponse.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I thought it might be a permission on folder problem however i have added "everyone" with full access temporarily and this did not solve the problem either.
Any ideas would be appreciated.

Make sure C:\Temp\file.pfx path is accesible. probably you want to test Server.MapPath("~/folder/" + filename).
Also check out the identity of your app pool and make sure that the Load user profile option is turned on, otherwise the crypto susbsystem won't work.
Try specifying X509KeyStorageFlags
var certificate = new X509Certificate2(KeyFilePath, KeyFilePassword,
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet |
X509KeyStorageFlags.Exportable);

Related

Executing an exe file on Plesk

I have created a web app using Asp.net and I have published my website on my domain(I'm using Plesk) and the website is functioning correctly. In one of my pages I execute an exe file in code behind which returns an output, which then will be printed in the page. It works correctly on local host, but on Plesk I get the error "This program is blocked by group policy". This is while I have set the CAS trust level to Full, I've enabled the "precompilie during publishing" option when I published the web app. I've erased the <system.codedom> tag in web.config, but the issue is still not fixed.
Here is the stack trace:
[Win32Exception (0x80004005): This program is blocked by group policy. For more information, contact your system administrator]
System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) +1889
System.Diagnostics.Process.Start() +119
Project.StyleSheets.Result.Page_Load(Object sender, EventArgs e) in E:\Soroush\Programming\Spark\Project\Project\Result.aspx.cs:24
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
Line 24 is the line at which I start the exe file, namely I execute the following code:
Process compiler = new Process();
compiler.StartInfo.FileName = Server.MapPath("~/Program/dist/News-Fetcher/News-Fetcher.exe");
compiler.StartInfo.Arguments = string.Format("{0}", Request.QueryString["search"]);
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
Line24: compiler.Start();
How can I solve his problem? Thanks!

The Security Support Provider Interface (SSPI) negotiation failed

I have error for my custom asp.net
my code asp code:
IServiceConfiguration<IOrganizationService> orgConfigInfo =
ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri("http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc"));
var creds = new ClientCredentials();
creds.UserName.UserName = "user";
creds.UserName.Password = "pass";
using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
using (context srv = new context(_service))
{
Account acc = new Account();
acc.thr_FirstName = firstname.Text;
acc.thr_LastName = lastname.Text;
acc.thr_NationalCode = nationalcode.Text;
acc.EMailAddress1 = email.Text;
acc.thr_Mobile = cellphone.Text;
acc.Telephone1 = tel.Text;
srv.AddObject(acc);
srv.SaveChanges();
alert.ForeColor = System.Drawing.Color.Green;
alert.Text = "با موفقیت ثبت شد";
}
}
and then when i run this code in my visual studio work correctly but when i run in iis i get this error
The Security Support Provider Interface (SSPI) negotiation failed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The Security Support Provider Interface (SSPI) negotiation failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The Security Support Provider Interface (SSPI) negotiation failed.]
System.ServiceModel.Security.WindowsSspiNegotiation.GetOutgoingBlob(Byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy) +6115112
System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState) +1325
System.ServiceModel.Security.IssuanceTokenProviderBase1.GetNextOutgoingMessage(Message incomingMessage, T negotiationState) +91
System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan timeout) +586
[SecurityNegotiationException: SOAP security negotiation with 'http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc' for target 'http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc' failed. See inner exception for more details.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14489026
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +622
Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request) +0
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request) +892
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) +254
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChange(OrganizationRequest request, IList`1 results) +43
[SaveChangesException: An error occured while processing this request.]
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) +1791
crm.Reg.submit_Click(Object sender, EventArgs e) +790
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
this error occurs due to the time zone as the server is hosted on some other region which has a different time zone then the local timezone where the web application is running.
to solve this problem server have to manage the offset of every timezone and the simplest way to do it tom manage the time in UTC format. to learn more about UTC click here

userprincipal.findbyidentity an operations error occurred

Okay so, I have been given the responsibility to migrate a website with multiple applications to another server. That migration went well (all applications working). However, the performance of that new server was sub par (whole other story). We decided to migrate it again. This time everything is working very well-- except one application.
It worked just fine on the first and second IIS servers, but is refusing to cooperate this time around.
I've mirrored all the config settings that I could find from the working server:
windows authentication enabled: check
Impersonation disabled: check
applicationpool settings match: check
I just don't know what I'm missing; why would it work on one server, but not the other.
An operations error occurred.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: An operations error occurred.
Source Error:
Line 9: Dim myUsername As String = Right(User.Identity.Name, Len(User.Identity.Name) - InStr(User.Identity.Name, "\"))
Line 10: Dim ctx = New PrincipalContext(ContextType.Domain)
Line 11: Dim myUser = UserPrincipal.FindByIdentity(ctx, myUsername)
Line 12: hfValid.Value = "false"
Line 13: For Each gp As GroupPrincipal In myUser.GetAuthorizationGroups
Source File: D:\mghnet1\isOnCall\Default.aspx.vb Line: 11
COMException (0x80072020): An operations error occurred
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +378142
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_AdsObject() +31
System.DirectoryServices.PropertyValueCollection.PopulateList() +26
System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +49
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +150
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +1114
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +112
System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +31
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) +14
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue) +73
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) +28
_Default.Page_Load(Object sender, EventArgs e) in D:\mghnet1\isOnCall\Default.aspx.vb:11
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Version Information: Microsoft .NET Framework Version:2.0.50727.5466; ASP.NET Version:2.0.50727.5456
Please help, none of the other forum posts I've found have posted solutions that work for me.

Getting Error Using Microsoft.AspNet.Membership.OpenAuth

I am getting an error using the RegisterExternalLogin control from the Visual Studio templates. After choosing login from Twitter, Twitter seems to process the login ok and then tries to load the response page and then the error occurs.
The error seems to be related to EntityFrameworks after the login method being called from the Microsoft.Aspnet.Membership.OpenAuth dll but that's about all I know.
Does anybody know how to resolve this?
Here is the error message:
[MissingMethodException: Method not found:
'System.Data.Objects.ObjectContext
System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()'.]
Microsoft.AspNet.Membership.OpenAuth.EFOpenAuthMembershipDatabase.EnsureDatabaseCreated(DbContext
db) +0
Microsoft.AspNet.Membership.OpenAuth.EFOpenAuthMembershipDatabase.GetMembershipUserName(String
providerName, String providerUserId, Boolean updateLastUsed) +221
Microsoft.AspNet.Membership.OpenAuth.OpenAuthManager.Login(HttpContextBase
context, String providerName, String providerUserId, Boolean
createPersistentCookie) +128
Microsoft.AspNet.Membership.OpenAuth.OpenAuth.Login(String
providerName, String providerUserId, Boolean createPersistentCookie)
+198 FinModelControls.Account.RegisterExternalLogin.ProcessProviderResult()
+594
Having similar exception, submitted a Conect bug.
https://connect.microsoft.com/VisualStudio/feedback/details/811035/microsoft-aspnet-membership-openauth-is-not-compatible-with-entity-framework-6
Solution: Make sure you're using latest v 2.0.0 Microsoft.AspNet.Membership.OpenAuth package, not 1.0.1.

Exception loading CustomMeta from Tridion Broker Service (2009 SP1)

I am trying to load some Custom Meta from a component which is published into the Tridion Broker.
This is 2009 SP1
I can see the component in the Custom_Meta table with a query like:
SELECT * FROM [Tridion_Broker].[dbo].[CUSTOM_META] WHERE ITEM_ID = 204221
However using the below code, I get a Java Runtime exception on the line where I do GetMeta. I have noticed that if my queryStringId is a proper TCM ID then it will throw the excpetion but if I just put the item Id it will return null.
string queryStringId = HttpUtility.UrlDecode(Request.QueryString["component_uri"]);
string pageId = ((BasePage) Page).PageTcmId;
int publicationId = int.Parse(pageId.Split(':')[1].Split('-')[0]);
using (var cmf = new ComponentMetaFactory(publicationId))
{
IComponentMeta cm = cmf.GetMeta(queryStringId);
if(cm != null)
{
VideoId = cm.CustomMeta.GetValue("video_url").ToString();
}
else
{
litMessage.Visible = true;
}
}
Stack trace:
[RuntimeException]
Codemesh.JuggerNET.NTypeValue.Throw(Int64 inst) +351
Codemesh.JuggerNET.JavaClass.ThrowTypedException(Int64 inst) +1278
Codemesh.JuggerNET.JavaMethod.CallObject(JavaProxy jpo, JavaMethodArguments args) +551
Codemesh.JuggerNET.JavaMethod.CallObject(JavaProxy jpo, Type declaredType, Boolean bLeaf, JavaMethodArguments jargs) +50
Com.Tridion.Meta.ComponentMetaFactory.GetMeta(Int32 componentId) +118
Tridion.ContentDelivery.Meta.ComponentMetaFactory.GetMeta(Int32 componentId) +16
ASP._controls_video_ascx.Page_Load(Object sender, EventArgs args) in c:\Inetpub\wwwroot\borland\us\_controls\Video.ascx:18
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Update
I have looked in the Broker log with the log enabled on "info" level and am seeing nothing after "Tridion Broker is enabled". Is this a configuration or DLL problem? It looks like the CD is not calling the service at all?
Update 2
I have tried a lot of things and still no help. It's like the code is not able to communicate with the JVM, however I can see the JVM being started in the event log.
Are you using Java 1.6? I think you may be using the JDBC driver is for Java 1.5, if so download the latest driver from here
Also double check all your bindings in broker config!
Typically when I had this kind of error, it was because one of the following:
the Java run-time was not installed or available to the web-app (from previous comments I see this is not the case for you). Have you checked the event viewer (either Tridion or Tridion Content Manager) for errors? Something like 'Unable to locate JVM'...
missing JAR - a Tridion or 3rd party JAR is missing from your classpath (which could be under your webroot/bin/lib);
configuration error (Tridion config is wrong, somewhere in webroot/bin/config);
missing license file (check the webroot/bin/config/cd_licenses.xml or maybe your config files point to another cd_licenses.xml, which might not be available or accessible to the web app app-pool user). A missing license is maybe the trickiest. All you see in the log is a subtle mention stating that due to missing/expired license, the Broker has reverted to 'file system'. This means no communication with the CD DB will be made -- for Custom meta this is a no go;
The last 3 errors will be somewhat present in a log file. So make sure you have the log level debug enabled and look for any stack traces in the cd_core and cd_broker logs.
Last but not least, make sure your website app-pool is unique to the Tridion website (do not reuse in other website). Check the .net version used (recommend 4.0) and check the user running it (recommend Network Service).

Resources