C# Thread Safe Static Read Only Field?

Mar 2, 2010

I have the following code in my ASP.NET project

public sealed class IoC
{
private static readonly IDependencyResolver resolver =
Service.Get("IDependencyResolver") as IDependencyResolver;
static IoC()
{
}
private IoC()

[Code]....

View 2 Replies


Similar Messages:

C# - Creating Instances Of A Class Inside A Static PageMethod Thread Safe?

Dec 14, 2010

I am using jQuery to call PageMethods. For certain operations, the current user credentials must be validated and for other operations, I need to call other static methods. Here is some sample code:

Sample #1

[WebMethod]
public static void PostComment(string comment)
{
UserAuth auth = new UserAuth();
if (auth.isAuthenticated)
{
//Post comment here...
}
}

Sample #2

[WebMethod]
public static string GetComment(int commentId)
{
commentDto comment = //get comment data from the database...
string friendlyDate = ConvertFriendlyDate(comment.commentDate);
return friendlyDate + " " + comment.text;
}
public static string ConvertFriendlyDate(DateTime commentDate)
{
string friendlyDate = //call static utility method to convert date to friendly format
return friendlyDate;
}

Will I be safe using these kinds of operations? Am I better to drop page methods and just call a separate ASPX page for my AJAX requests?

View 4 Replies

C# - Is It Safe To Access .net Session Variables Through Static Properties Of A Static Object

May 10, 2010

Is it safe to access asp.net session variables through static properties of a static object?Here is what I mean:

public static class SessionHelper
{
public static int Age
{
get
{
[code]...

Is it possible that userA could access userB's session data this way?

View 2 Replies

Is It Safe To Use One Entity Framework Context Per Thread

Mar 30, 2011

Probably these are two questions in one, I am using one EF context per request, but I want to use one per thread, because I am going to make some complex task in another thread during the request. So, is it safe? If the answer is yes, how to do it? how to store objects in thread and get them back?

View 2 Replies

Security :: Thread Safe Custom Membership Provider

Feb 2, 2010

I just created a custom membership provider I would like to know if I can make calls to my data access layer and not put my data access code inside the membership methods will that prevent my custom membership provider from being thread safe, for example:

public override [Code]....
CreateUser(string username, string password, string email, out MembershipCreateStatus status){ // DB calls to my data layer}v.s.public override [Code]....
CreateUser(string username, string password, string email, out MembershipCreateStatus status){ // data access }

View 2 Replies

C# - How To Lock A Private Static Field Of A Class In One Static Method

Mar 26, 2011

I have a private static field in my Controller class in an MVC web application.

I have a static method in that controller that assigns some value to that static field, I want to apply lock on that static field until some other instance method in the controller uses the value stored in the static field and then releases it.

DETAILS:

I have a controller named BaseController having a static ClientId field as follows and two methods as follows:-

public static string ClientId = "";
static void OnClientConnected(string clientId, ref Dictionary<string, object> list)
{
list.Add("a", "b");
// I want the ClientId to be locked here, so that it can not be accessed by other requests coming to the server and wait for ClientId to be released:-
BaseController.clientId = clientId;
}
public ActionResult Handler()
{
if (something)
{
// use the static ClientId here
}
// Release the ClientId here, so it can now be used by other web requests coming to the server.
return View();
}

View 1 Replies

Thread Safety In Parameters Passed To A Static Method

Jan 10, 2011

Assuming a static method like below is called from ASP.NET page,can a different thread(b) overwrite the value of s1 after the first line is executed by thread(a)?If so, can assigning parameters to local variables before manipulation solve this?

public static string TestMethod(string s1, string s2, string s3)
{
s1 = s2 + s3;
....
...
return s1;
}

Is there are a simple way to recreate such thread safety related issues?

View 3 Replies

C# - Static Methods Updating A Dictionary<T,U> Is It Safe To Lock() On The Dictionary Itself

Dec 23, 2010

I have a class that maintains a static dictionary of cached lookup results from my domain controller - users' given names and e-mails.My code looks something like:

private static Dictionary<string, string> emailCache = new Dictionary<string, string>();
protected string GetUserEmail(string accountName)
{
if (emailCache.ContainsKey(accountName))
{
return(emailCache[accountName]);
}
lock(/* something */)
{
if (emailCache.ContainsKey(accountName))
[code]...

View 6 Replies

C# - Is It Safe To Use Server.Transfer() To Transfer A Request To A Static Image (.jpg - .png)?

Feb 8, 2011

I have a class which implements IHttpHandler that is designed to handle image resize requests. It handles Urls like so [URL] Currently the handler looks for myimg.jpg on disk, cuts a 100x100 thumbnail (if it isn't already present) and redirects the client to the thumbnail like so Response.RedirectPermanent("/some/virtualPath/to/thumbnail.jpg");

This has been working great, but I would like to avoid forcing the client to issue a second HTTP request. Is it safe to do the following? Server.Transfer("/some/virtualPath/to/thumbnail.jpg") All the MSDN documentation talks about using Server.Transfer() to redirect to an aspx page, so I'm not sure if this is the right thing to do or not.

View 1 Replies

Security :: Modifying IsLockedOut Field Via An Updatesql Is Safe?

Aug 23, 2010

Need lock some users when I want.and I read isLockedOut is readonly.

I found a field in aspnet_profile table namely IsLockedOut=true/false. If I modify the record via sql is it safe way ?this may be a source of some unexpected problems ?

View 4 Replies

Configuration :: Field Initializer Cannot Reference The Non-static Field?

Feb 3, 2011

when i am declaring my connection string i am getting error below is my connection string

[Code]....

the error is A field initializer cannot reference the non-static field, method, or property 'Default3.con1' .i am unable to type con1.

View 2 Replies

C# - Read A Value Being Manipulated In Different Thread?

Apr 15, 2010

I'm trying to read a static property from a static class, which is being modified from a different thread.

Basically I have this static class:

public static class Progress{
public static int currentProgress{get; set;}
}

and this thread manipulating the currentProgress:

private void Job(){
for(int i = 0; i<100; i++){
Progress.currentProgress = i;
Thread.Sleep(1000);
}
}

While this is running, I have a HttpHandler trying to access this progress (every few seconds), like so:

public void ProcessRequest(HttpContext context) {
context.Response.Write(Progress.currentProgress.toString());
context.Response.End();
}

But the currentProgress is set to it's initialvalue here, while the workThread is working, and only when done, is the currentProgress updated.

View 1 Replies

Cross-thread Operation Not Valid: Accessed From A Thread Other Than The Thread It Was Created On

Apr 2, 2010

I want to remove checked items from checklistbox (winform control) in class file method which i am calling asynchronously using deletegate. but it showing me this error message:-

Cross-thread operation not valid: Control 'checkedListBox1' accessed from a thread other than the thread it was created on.

i have tried invoke required but again got the same error. Sample code is below:

[code]....

View 1 Replies

Data Controls :: How To Make Bound Field And Template Field Read-Only In Edit Item Template Of GridView

Jul 31, 2013

i am implementing a update query module.i am displaying all fields from a table for a term searched. well now i am implementing update option for the record which are displayed, i have like 70 columns in my table, and i want to know how to restrict some selected fields to be only read only while the form can be updated ?Like if user select to update a record then some selected field such as "Timestamp, UID etc some selected fields" remains READ ONLY !

View 1 Replies

Static Field Initializer Runs Before Application_start, Sometimes?

Oct 29, 2010

I've got an ASP.NET web app that is starting to show some very strange behavior. Here's some example code:

// in Bar.cs
public class Bar {
public static Baz baz = Something.Step2();
}
// in Global.asax
public void Application_Start(...) {
Something.Step1();
}

The short version of the story is this: On some machines, Something.Step2 is executed before Something.Step1 and is throwing an unhandleable exception. On other machines, Step1 correctly executes before Step2. Global.asax and all the objects it uses do not refer to Bar at all.

When are static fields supposed to execute in relation to other programming elements? Why would two machines (both Win7 64-bit, both with .NET 4.0, same IIS version, etc) execute things in different orders? The order is consistent on each machine too. On my machine, it always executes Step2 before Step1, but on my coworker's machine it always executes Step1 before Step2.Update I've found the root cause why my static field is being accessed. Class "Bar" from my example is actually a custom authentication module, and is referenced in web.config as the Authentication handler under System.webServer. If I remove that line from web.config, my system calls Step1 first and never calls Step2 at all. My question changes subtly to: "Why does web.config cause my static initializers to fire, and why does it cause them to fire before Application_Start executes?"

View 1 Replies

C# - What Is The Life Span Of A Field In A Static Class

Feb 2, 2011

I have a simple web service, in it i have a static class which has a static collection to remember alive tokens.

I just want to make sure that the token collection lives until the next iisreset or the application pool recycles.

And what is the difference between remembering states in Application bag and static class?

View 1 Replies

Caching In .net - Error Like "An Object Reference Is Required For Non Static Field?

Feb 9, 2011

I m having a webService.

In that I m using Caching.

I have wrote following code to store datatable in cache.

using System.Web.Caching;

Cache.Insert("dt", dt, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);


It give me error like "An object Reference is required for non static field.

View 2 Replies

Web Forms :: Object Reference Is Required For Non-static Field / Method Or Property

May 7, 2015

I'm using jQuery and setInterval method in my asp.net web application.

I call the webservice every 5 seconds in order to check for DB changes. When i see a change, i want to change the photo of the linkButton that located on the master page, but i can to that due to static constrains.

An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Master.get'

my c# code is:

[WebMethod()]
public static bool checkDBChange(string userId) {
DBConnection dbConnection = new DBConnection();
if (dbConnection.isChanged(userId)) {
((Site1)Master).SetImageUrl = "~/Icons/a.ico";
}
return false;
}

The SetImageUrl is a setter in my master page that sets the new url to the linkButton. How I can implement it?

View 1 Replies

Visual Studio :: Debug A Multi Thread Program To See Local Variables Of Each Thread Using 2008

Jan 27, 2010

How can we debbug a multi-thread program to see local variables of each thread using visual studio 2008.

View 1 Replies

Architecture :: How Can Thread Update A Variable Shared With The Main Thread

Nov 24, 2010

I'm new to threading and have used it successfully, but limited. I can spawn a thread and have the main thread reference variables in the spawned thread, but I don't know how to allow the spawned thread to reference (and update) variables in the main thread.

Any example threading code I've seen on the web appears to be WAY more complicated than what I do, so I am unable to understand or integrate into my code.

Here is a quick example of how I use threading:

[code].....

View 3 Replies

AJAX :: Accessing Placeholder From Webmethod - An Object Reference Is Required For The Non-static Field

Mar 22, 2010

Aplogies if this has been discussed before but I couldn't find an answer.

I'm trying to use jquery/Ajax to access some webmethods in my codebehind. This is fine, but I would in my function like to reference a placeholder (phStory in the code below) on my page and also load a usercontrol into that placeholder.

Unfortunately I get the message: "An object reference is required for the non-static field, method, or property 'TestControls.phStory' " and similar for the usercontrol. Does anyone know how I can still access my placeholder and usercontrol from within this.

It has to be stati as it's a WebMethod but this then throws up these errors.

[code]....

View 4 Replies

CS0120 Error - An Object Reference Is Required For The Non-static Field, Method, Or Property?

Mar 24, 2010

I am getting a CS0120 error when trying turn a button visible after checking some variables. In plain english, If AmmohelpSession.UserActions contains AmmohelpEnums.UserAction.ArticleEdit then turn the Edit button visible. Here is my comparison:

[Code]....

In the code behind for AmmohelpSession, a public class AmmohelpSession which contains a private variable: private HashSet<UserAction> _userActions; has been stated. In that same file, there is a public function for the UserActions that does a get or set method.In the code behind for AmmohelpEnums, we are setting byte variables to specific actions. Mine would be something like:

[Code]....

Where is my error coming from ?????

View 1 Replies

C# - Static Vs Member Field Revisited / Want To Persist A Large Dictionary Of Strings Inside The Memory?

Feb 18, 2011

I need an advice on piece of functionality that I am ought to implement. The scenario is that we haven an HttpHandler which servers to intercept file uploads. In the handler, I need to persist a large dictionary of strings inside the memory. The dictionary might be as large as 100 entries. I am wondering whether it is safe to store that in a static variable, so that it is not initialized every time instance of the handler is created (there will be a lot of instance for sure). In general, what is the approach in such scenarios. Is it a generally better idea to use static fields, to persist data that will not be changed?

View 5 Replies

What Are The Differences Between Currently Executing .NET Thread And Win32 Thread

Mar 24, 2010

I am reading the Asp.net security documentation on msdn.I come across these tow terms and get really confused.

# WindowsIdentity = WindowsIdentity.GetCurrent()

which returns the identity of the security context of the currently executing Win32 thread.

# Thread = Thread.CurrentPrincipal

which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

View 1 Replies

C# - Lock Thread.sleep Not Working With .NET Thread?

Jun 25, 2010

I have a password page and when someone enters an incorrect password I want to simply foil a brute force attack by having

bool isGoodPassword = (password == expected_password);

lock (this)
{
if (!isGoodPassword)
Thread.Sleep(2000);
}
I would expect that this would allow all correct passwords without stalling, but if one user enters a bad password another successful password from a different user would also be blocked. However, the lock doesn't seem to lock across ASP.NET threads.

View 4 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved