Hello i have problem accessing HttpContext.Current.Application From global.asax its seems to be null every time i try to access it.
How can i to this?
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["Actions"] = "hello";
HttpContext.Current.Application.UnLock();
Thanks
In Global.asax, you're not in an actual request, so there's no current request nor context you can go by. However, the Global class is a subclass of HttpApplication, so just use 'this', like:
this["Actions"]
From MSDN
To get the HttpApplication object for the current HTTP request, use ApplicationInstance. (ASP.NET uses ApplicationInstance instead of Application as a property name to refer to the current HttpApplication instance in order to avoid confusion between ASP.NET and classic ASP. In classic ASP, Application refers to the global application state dictionary.)
You need to turn on access to the Application instance object in your web.config file like so:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
Be sure to include a reference to System.Web.
Related
I'm want to be able to set the caller ID on my
XrmServiceContext : Microsoft.Xrm.Client.CrmOrganizationServiceContext
Context that has been generated for crm using svcutil.exe.
As far as I can tell I cant do this on an existing connection and I need to first create an instance of OrganizationServiceProxy set the CallerID and then pass it as a paramater to a new XrmServiceContext which I can then use instead.
However I'm kind of stuck on how I go from a CrmOrganizationServiceContext to having a OrganizationServiceProxy
The program is a separate .Net4.5 application
Any helpful tips or links?
Edit: Found this page just after posting this: http://msdn.microsoft.com/en-us/library/gg695810.aspx
So it may be as simple as:
var connection = new CrmConnection("Xrm");
connection.CallerId = uide;
_serviceContext = new XrmServiceContext(connection);
Edit 2: It was not as simple as that.
Doing this resulted in no change of what data I received.
CrmConnection connection = new CrmConnection("Xrm");
connection.CallerId = Guid.NewGuid();//u.Id;
_serviceContext = new XrmServiceContext(connection);
It compiles and dosen't crash but I was suspicious when I used the id of a user with very low privledges but still got all data back, I then tried generating a new Guid for every instance of the XrmServiceContext but I am still getting everything back. So I am guessing it is not being used.. or I am missing something else.
Edit 3
Doing a WhoAmIRequest after the CallerID has been set still returns the same user that is set in the connection string.
Edit 4
Seems my problems are Cache related.
In my implementation I need to first make a call to the service context to figure out the Guid of the user I want to impersonate. This call is made without CallerID set. If I skip this initial query and just set a specific Guid from the beginning the CallerID works. I'm guessing this is because the service context has cached my original CallerId or something similar.
Now I just have to figure out how to clear the cache in CRM 2013 SDK.
Edit 5
By turning of the cache completly using this guide: http://msdn.microsoft.com/en-us/library/gg695805.aspx I have gotten it to work. I would however prefer if I could just clear it out at the one point I need to instead of disabling it completly.
If someone can show me how to empty the service context cache using code I will mark that as the correct solution
There is a method that can be used when dealing with your "_serviceContext"
You should be able to use: _serviceContext.ClearChanges(); This clears all tracking of a particular entity within the Cache. See the Public Methods Section
The problem is related to the default instanceMode that is defined in the web.config under the microsoft.xrm.client section.
By default, the setting is set to PerRequest
PerRequest – returns the same first instance in the context of a Web
request, for example. one instance for each HttpContext instance.
So, in this case, when you do the initial call to work out which user you want to set the CallerId to, the instance is being 'cached' (for lack of a better word) and on subsequest calls within the same request, this instance is being returned, even if you are creating a new XrmServiceContext
The solution is to change the instanceMode to PerInstance
PerInstance – returns a new instance on each call.
Modify your web.config so that the instanceMode attribute is specified correctly
<microsoft.xrm.client>
<contexts>
<add name="Xrm" type="Xrm.XrmServiceContext, Xrm" serviceName="Xrm" />
</contexts>
<services>
<add name="Xrm" type="Microsoft.Xrm.Client.Services.OrganizationService, Microsoft.Xrm.Client" instanceMode="PerInstance" />
</services>
</microsoft.xrm.client>
Found this information in the article posted by JensB in his 5th edit: http://msdn.microsoft.com/en-us/library/gg695805.aspx
I created a WCF Data Service inside a Windows Service and tried to access the HttpContext.
I added this to my config file:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
However, when I try to access it, it is null.
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
base.OnStartProcessingRequest(args);
HttpContext httpContext = HttpContext.Current;
File.AppendAllText(#"c:\Temp\ERROR.log",
httpContext != null
?"HTTPCONTEXT IS NOT NULL"
:"HTTPCONTEXT IS NULL");
}
What else should I set?
I found the answer, I'm afraid so:
The disabled ASP.NET HTTP features are:
HttpContext.Current: This is always null in this mode. For ASMX services, this is a ThreadStatic property that is stored in the Thread Local Store (TLS). WCF provides a counterpart to this feature: OperationContext.Current.
Source: http://blogs.msdn.com/b/wenlong/archive/2006/01/23/516041.aspx
I'm working on a Asp.Net 3.5 Web Application which requires Async Web service calls.
Here is some code. I have written the code for Async calling using delegates but somehow my HttpContext.Current.Session is null. To make sure, I even tried passing HttpContext.
static HttpContext httpContext;
public void AsyncGetUser()
{
httpContext = HttpContext.Current;//not getting Session as null here
GetUserDelegate delegate = new GetUserDelegate(InvokeWrapperMethod);
IAsyncResult async = delegate.BeginInvoke(httpContext,new AsyncCallback(CallbackMethod), null);
}
static void CallbackMethod(IAsyncResult ar)
{
AsyncResult result = (AsyncResult)ar;
GetUserDelegate caller = (GetUserDelegate)result.AsyncDelegate;
caller.EndInvoke(ar);
}
private static void InvokeWrapperMethod(HttpContext hc)
{
HttpContext.Current = hc; //getting Session as null here
UserInfo userInfo = Service.GetUserInfo();
SetInSession(USER_INFO, userInfo);
}
I have tried <modules runAllManagedModulesForAllRequests="true"> and
<system.webServer>
<modules>
<remove name="Session"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
as this SO question suggested but didn't work. I would appreciate if you guys could give some pointers. Thanks.
This can occur in ASP.NET apps using the async/await (TAP) pattern. To solve this, you need to add this to your appSettings section in web.config.
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
This may require .NET 4.5, I note you are not using this version but I add this answer here for others that have upgraded projects and are hitting this issue with their TAP code.
your web service should use , IRequiresSessionState marker interface to enable session.
I ended up with the decision to refactor the whole project.
It might be that you're using delegates to get the 'handy' BeginInvoke method. This is inefficient since behind the scenes, its using a load of Reflection. If the background work is always significant then this overhead gets amortised, but its its sometimes just a few reads, then it'll take longer than doing it on the original thread.
You could install RX for 3.5 and use the 'mini TPL' to get at Tasks. This in itself could solve the problem (the issue might be the way in which that delegate.BeginInvoke is written), else try passing the context in as the state instance.
I know you've refactored out of the problem (probably a good thing) but I add this answer for completeness having looked more at what you were originally doing.
I'm writing an ASP.NET C# web site that needs to access data from a database and show it to the user for viewing and editing. The specific data it accesses is based on the user who logs in, and I need for multiple users to be able to use the site simultaneously, viewing and editing different data as they do so. I stumbled upon the concept of Session States, and after a lot of reading and not as much understanding. I've come across a problem.
In my default page, I do this to create a Session variable:
Session.Add("UserData",userdata);
I have also tried this:
Session["UserData"] = userdata;
Then in a later page, I do this to try to call it:
object myobject = Session["UserData"];
This gives me an error, saying that Session["UserData"] is not set to an instance of an object. This is the method everyone seems to be using, is there something I'm missing?
My site is configured on IIS to have the Session State Mode set to "In Process", but most people seem to set this manually using their web.config file. However, when I try to do this in my web.config file I am always greeted with "unrecognized configuration section". My compiler doesn't know what this is:
<sessionstate mode="inproc"/>
EDIT, more detailed code:
MyClass userdata = new MyClass();
userdata.name = "myname";
userdata.number = 5;
Session["UserData"] = userdata;
later...
MyClass mydata = (MyClass)(Session["UserData"]);
This returns the error that Session["UserData"] is null.
The fact that you can't set the session mode in the web.config is a red flag to me of something weird and smelly going on. So ...
Check that the session mode is under the system.web element of the web.config otherwise it won't be valid.
Check that enableSessionState hasn't been set to false in either the web.config or the page directive
Try to rule out IIS. If possible convert your website to a web app and run through visual studio so it starts with it's own built in web server. What happens then? Is the Session state back?
It should n't make a difference but if you are not doing the test in Page_Load then just try it there - just in case you are doing these tests somewhere unusual.
Whatever the answer is to this when we know it will be headachingly obvious. I'm geninuely looking forward to finding out what it is. Good luck
Session variables are good to manage multiple users on your website, but to initialize them you should use the Global.asax file in your web application. This file has two methods specifically for Session variables, Session_Start and Session_End. To initialize your Session variable you would use code liked the following in Global.asax:
void Session_Start(object sender, EventArgs e)
{
// initialize session variable
Session["MySessionVar"] = 1;
}
Also you may have to cast the value of your session variable if you are doing operations on it like +, for example if you have a session variable holding an integer value, you may have to do like the following:
Session["MySessionVar"] = ((int) Session["MySessionVar]) + 1;
Also, if you try to use your session variable outside of a method like Page_Load or other method, like trying to use it as a property of the System.Web.UI.Page class in your C# code behind file, that may not work, you can only use your session variables within a method.
I would search for any calls to Session.Clear or Session.Abandon to see if your session is being purged in between those two actions.
You could also hook up to the Session_End event and see if that gets hit sometime in between the two calls.
Where you have
Session.Add("UserData",userdata);
you want to check the value you need to cast the object with (string) like this
string userdata= (string)(Session["UserData"]);
you could then run a check to see
if(string.IsNullOrEmpty(userdata))
but not sure how you are initializing and assigning a a value to userdata
Does it complain the your myobject is null or that Session is null? When you try to retrieve the value you are doing this from the method of what class?
Yet another question - by any chance are you trying to access it in a parallel thread?
I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?
This can now be done purely in markup. Just add an applicationName attribute to the errorLog element in the <elmah> section of the web.config file. Example:
<errorLog type="Elmah.SqlErrorLog, Elmah"
connectionStringName="connectionString" applicationName="myApp" />
I've tested this and it works both when logging an exception and when viewing the log via Elmah.axd.
In the case of the OP, one would imagine it can be set programatically too but I didn't test that. For me and I imagine for most scenarios the markup approach is sufficient.
By default, Elmah uses the AppPool's application GUID as the default application name. It uses this as the key to identify the errors in the Elmah_Error table when you look at the web interface that's created through it's HTTP Module.
I was tasked to explore this option for my company earlier this year. I couldn't find a way to manipulate this by default since Elmah pulls the application name from HttpRuntime.AppDomainAppId in the ErrorLog.cs file. You could manipulate it by whatever key you want; however, that is the AppPool's GUID.
With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName. What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:
public virtual string ApplicationName
{
get
{
if (_applicationName == null) { _applicationName = HttpRuntime.AppDomainAppId; }
return _applicationName;
}
set { _applicationName = value; }
}
What you will probably need to do is adjust this differently and set the ApplicationName not to HttpRuntime.AppDomainAppId but, instead, a value pulled from the web.config. All in all, it's possible. The way I did it enhanced the ErrorLog.Log(ex) method so I could use Elmah has a callable framework beyond web applications. Looking back I wish I did the app/web.config approach instead.
One thing to keep in mind when changing the application name in Elmah. The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.