Static variable Behaviour in Asp.Net - c#

I have a OperationHelper class which is as follows:
public class OperationHelper
{
/// <summary>
/// Gets or sets the Add Operation value
/// </summary>
public static bool AddOperation { get; set; }
/// <summary>
/// Gets or sets the Edit Operation value
/// </summary>
public static bool EditOperation { get; set; }
/// <summary>
/// Gets or sets the Delete Operation value
/// </summary>
public static bool DeleteOperation { get; set; }
/// <summary>
/// Gets or sets the Select Operation value
/// </summary>
public static bool SelectOperation { get; set; }
}
on each request this values are re-assigned. when i run this locally it works properly.
but when i published the code some values are not get assigned or not working as it should work.
So want to know the behavior of the static variable in Asp.Net with C#.
are static variable equal to global variable which is accessible to all user? If it is set by user A to true can user B get that value as True or it has different instance of the variable.

The behavior of static variables is that they are being created as soon as the code they belong to is reached. To solve your problem, consider a static constructor for your class to properly initialize all values to your desire
public class OperationHelper
{
/// <summary>
/// Gets or sets the Add Operation value
/// </summary>
public static bool AddOperation { get; set; }
/// <summary>
/// Gets or sets the Edit Operation value
/// </summary>
public static bool EditOperation { get; set; }
/// <summary>
/// Gets or sets the Delete Operation value
/// </summary>
public static bool DeleteOperation { get; set; }
/// <summary>
/// Gets or sets the Select Operation value
/// </summary>
public static bool SelectOperation { get; set; }
static OperationHelper() {
//initialize your static variables here
}
}
See here for a reference on static constructors.

So want to know the behavior of the static variable in Asp.Net with
C#.
are static variable equal to global variable which is accessible to
all user? If it is set by user A to true can user B get that value as
True or it has different instance of the variable.
The behavior is like that only if your run your site under one working process on your pool.
If your pool have more than one working process, then each process have their static values, and is unknown to you what process is given to each request, to each user. And process together they are not communicate.
So let say that you have a pool with 4 working process.
UserA ask for a page, Process 1 is replay and set a static value to A.
UserB ask for a page, Process 1 is replay and the static value is A.
UserA ask for a page, Process 2 is replay and the static value is not set.
and so on.
More on the subject:
Lifetime of ASP.NET Static Variable
Where are static variables stored in asp.net aspx page
Using static variables instead of Application state in ASP.NET
Static methods on ASP.NET web sites
Asp.net static object appears sometimes as non global

static variables are only created once. so userB will get same instance of the variable to answer your question.
More on this have been discussed here.

you need to consider session that will give you different value for each user accessing the site

Related

Is there any reason to use very simple properties over fields?

I currently have this code written:
public class General
{
/// <summary>
/// Private variables.
/// </summary>
private const float fVersion = 1.3f;
private static bool bMonitoring = false;
/// <summary>
/// Retrieves the current version of the application.
/// </summary>
public static float Version
{
get
{
return fVersion;
}
}
/// <summary>
/// Are we monitoring performance?
/// </summary>
public static bool Monitoring
{
get
{
return bMonitoring;
}
set
{
bMonitoring = value;
}
}
}
In case I check for General.bMonitoring or General.Version often (maybe.. over 100 times a second!) and really care about performance: is it good practice to leave my class written like that, or should I simply delete these properties and make the fields public?
In this case if you aren't going to add some logic to the getter or setter then I would use static fields. Performance will be the same.
But if later you need extra logic when you set ot get values then it preffer to use properties because it allows for versioning and it gives you Encapsulation according to OOP principles. Don't care about performance
For Monitoring property you can use Auto-Implemented Property like
public static bool Monitoring { get; set; }
but in this case you need to implement a static constructor (thanks to #Mafii)
static General()
{
Monitoring = false;
}
or if you use C# 6.0 then just:
public static bool Monitoring { get; set; } = false;
Don't worry about performance. Property access is (and should be) very fast and compiler may inline them.
Property is preferred over field not because of performance, but because encapsulation and it will really helps when later you need for example checking or make property computed.
More by Jon Skeet http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

Trial experience of app is allowing unrestricted access - Windows Phone 8

I launched my first app yesterday to the store. The app has a trial version which simply restricts full access to the game.
I downloaded the trial and played for a while, no problems - good.
I then purchased the full version by from the store and started the app again only to find that it didnt release it's restrited areas - NOT good.
I have implemented the following code in the app to implement the restrictions:
/// <summary>
/// The TrialExperienceHelper class can serve as a convenient building-block in your app's trial experience implementation. It queries
/// the license as infrequently as possible, and caches the results, for maximum performance. When built in debug configuration, the class simulates the purchase
/// experience when the Buy method is called. To customize what happens in debug when Buy is called, initialize the simulatedLicMode and/or
/// simulatedLicModeOnPurchase fields to different values. A release build of this class will have access to a license only when the app is
/// published to the Windows Phone Store. For a release build not published to the Store, the value of the LicenseMode property will be
/// LicenseModes.MissingOrRevoked.
/// </summary>
public static class TrialExperienceHelper
{
#region enums
/// <summary>
/// The LicenseModes enumeration describes the mode of a license.
/// </summary>
public enum LicenseModes
{
Full,
MissingOrRevoked,
Trial
}
#endregion enums
#region fields
#if DEBUG
// Determines how a debug build behaves on launch. This field is set to LicenseModes.Full after simulating a purchase.
// Calling the Buy method (or navigating away from the app and back) will simulate a purchase.
internal static LicenseModes simulatedLicMode = LicenseModes.Trial;
#endif // DEBUG
private static bool isActiveCache;
private static bool isTrialCache;
#endregion fields
#region constructors
// The static constructor effectively initializes the cache of the state of the license when the app is launched. It also attaches
// a handler so that we can refresh the cache whenever the license has (potentially) changed.
static TrialExperienceHelper()
{
TrialExperienceHelper.RefreshCache();
PhoneApplicationService.Current.Activated += (object sender, ActivatedEventArgs e) => TrialExperienceHelper.
#if DEBUG
// In debug configuration, when the user returns to the application we will simulate a purchase.
OnSimulatedPurchase();
#else // DEBUG
// In release configuration, when the user returns to the application we will refresh the cache.
RefreshCache();
#endif // DEBUG
}
#endregion constructors
#region properties
/// <summary>
/// The LicenseMode property combines the active and trial states of the license into a single
/// enumerated value. In debug configuration, the simulated value is returned. In release configuration,
/// if the license is active then it is either trial or full. If the license is not active then
/// it is either missing or revoked.
/// </summary>
public static LicenseModes LicenseMode
{
get
{
#if DEBUG
return simulatedLicMode;
#else // DEBUG
if (TrialExperienceHelper.isActiveCache)
{
return TrialExperienceHelper.isTrialCache ? LicenseModes.Trial : LicenseModes.Full;
}
else // License is inactive.
{
return LicenseModes.MissingOrRevoked;
}
#endif // DEBUG
}
}
/// <summary>
/// The IsFull property provides a convenient way of checking whether the license is full or not.
/// </summary>
public static bool IsFull
{
get
{
return (TrialExperienceHelper.LicenseMode == LicenseModes.Full);
}
}
#endregion properties
#region methods
/// <summary>
/// The Buy method can be called when the license state is trial. the user is given the opportunity
/// to buy the app after which, in all configurations, the Activated event is raised, which we handle.
/// </summary>
public static void Buy()
{
MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;
marketplaceDetailTask.Show();
}
/// <summary>
/// This method can be called at any time to refresh the values stored in the cache. We re-query the application object
/// for the current state of the license and cache the fresh values. We also raise the LicenseChanged event.
/// </summary>
public static void RefreshCache()
{
TrialExperienceHelper.isActiveCache = CurrentApp.LicenseInformation.IsActive;
TrialExperienceHelper.isTrialCache = CurrentApp.LicenseInformation.IsTrial;
TrialExperienceHelper.RaiseLicenseChanged();
}
private static void RaiseLicenseChanged()
{
if (TrialExperienceHelper.LicenseChanged != null)
{
TrialExperienceHelper.LicenseChanged();
}
}
#if DEBUG
private static void OnSimulatedPurchase()
{
TrialExperienceHelper.simulatedLicMode = LicenseModes.Full;
TrialExperienceHelper.RaiseLicenseChanged();
}
#endif // DEBUG
#endregion methods
#region events
/// <summary>
/// The static LicenseChanged event is raised whenever the value of the LicenseMode property has (potentially) changed.
/// </summary>
public static event LicenseChangedEventHandler LicenseChanged;
#endregion events
}
Then in my code I'm using if's to determine what to allow with this:
if ((TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.Trial)||
(TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.MissingOrRevoked))
{
//Then add ad' etc
}
This call must be returning TRUE...!
For the life of me I can't see the mistake, maybe someone here more experienced can help? What have I done wrong here?

Cant access a public variable from a public class anywhere in my solution (VS, C'#)

i have taken over a project and I am struggling to access a public variable from a public class. (Strange).
I am relatively new to C# having only done some MVC, ASP.NET stuff so i dont know if im being a bit of a clown but:
public int AlertCount
{
get { return Convert.ToInt32(alertCountTextBlock.Text); }
set { alertCountTextBlock.Text = value.ToString(); }
}
/// <summary>
/// Property which represents the number of new alerts the project currently has
/// </summary>
public int NewAlertCount
{
get { return Convert.ToInt32(newAlertCountTextBlock.Text); }
set { newAlertCountTextBlock.Text = value.ToString(); }
}
These are the two variables i am trying to access from another class inside my solution (above)
namespace Intelligence_Gathering_System.Pages.Project.Controls
{
/// <summary>
/// UserControl which acts as a selection button for each project. It displays the projects name and
/// current alert item totals along with providing methods for sharing and selecting of the project
/// </summary>
public partial class ProjectHeaderControl
{
private readonly ProjectPage _parentReference; //Reference to the controls 'parent' Project Page
/// <summary>
/// Overloaded constructor which initialises the controls members
/// </summary>
/// <param name="projectName">The name of the project</param>
/// <param name="alertCount">The total number of Alert Items in the project</param>
/// <param name="newAlertCount">The total numebr of New Alert Items in the project</param>
/// <param name="parent">A reference to the controls 'parent' Project Page</param>
public ProjectHeaderControl(string projectName, int alertCount, int newAlertCount, ProjectPage parent)
{
this is the class structure (namespace, partial class and constructor) which the variables reside,
I am simply trying to call from another piece of code (within the same solution and project ) to alter a count to increment and decrement
I have tried inside the class i need to increment and decrement (there are multiple classes i need to do this) putting the full namespace path then the variable to pinpoint it exacty and the class. variable (example of one seen below)
int x = Intelligence_Gathering_System.Pages.Project.Controls.NewAlertCount;
or
int x = ProjectHeaderControl.NewAlertCount;
neither of them are working and im a bit baffled as to why.
Am i missing something obvious here or....
Is it syntax related due to C# i'm unsure.
Any help would be appreciated.
Regards
Jordan
NewAlertCount is a property in a class - but we can't tell what that class is. (Maybe it's ProjectHeaderControl - your description is somewhat hard to understand.)
Intelligence_Gathering_System.Pages.Project.Controls is a namespace. A namespace can't declare properties.
You need to specify the class which contains the properties - and they'll either need to be static properties, or you'll need to fetch the property from an instance of the class.

Return a string from a Service already running using Remoting

im trying to use .Net Remoting to get a value of a variable that i use in a thread of an windows service.
TcpChannel tcpChannel = new TcpChannel(9998);
ChannelServices.RegisterChannel(tcpChannel, false);
Type commonInterfaceType = typeof(MyNameSpace.Core.Engine);
RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
"CopyFilePercentage",
WellKnownObjectMode.SingleCall);
myEngine = Engine.EngineInstance;
myEngine.Start();
But it seams that every time that i use the Client to get that value, a new thread is created returning an empty string.
Any idea why is this happening or am I doing something wrong?
Thanks in advance,
Miguel de Sousa
WellKnownObjectMode.SingleCall creates a new instance of your class for each call. try WellKnownObjectMode.Singleton
EDIT
Maybe you should read about client activated objects. Turn your singleton object to a class factory and return a new instance of a real worker class(ofcourse inheriting from MarshalByRefObject) which will be used by the client.
so your client will be something like this
var worker = client.GetWorkerClass();
worker.GetSomeData();
and you will have one server object per connection (this may not be the correct terminology).
well i just used a Global Variable Class not really what I wanted but does the job.
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";
/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
return _globalValue;
}
set
{
_globalValue = value;
}
}
/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}

What am I doing wrong with my Workflow bookmark pick trigger?

I have a NativeActivity derived activity that I wrote that is to use bookmarks as a trigger for a pick branch. Using something I found on MSDN I tried writing this to trigger the branch. The branch contains activities that fire service callbacks to remote clients via send activities. If I set a delay for the trigger, callbacks fire to the clients successfully. If I use my code activity, the pick branch activities don't fire.
public sealed class UpdateListener : NativeActivity<ClientUpdate>
{
[RequiredArgument]
public InArgument<string> BookmarkName { get; set; }
protected override void Execute(NativeActivityContext context)
{
context.CreateBookmark(BookmarkName.Get(context),
new BookmarkCallback(this.OnResumeBookmark));
}
protected override bool CanInduceIdle
{
get { return true; }
}
public void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object obj )
{
Result.Set(context, (ClientUpdate)obj);
}
}
So it takes an arg to set the bookmark name for future bookmark references to execute the trigger. OnResumeBoookmark() takes in a ClientUpdate object that is passed by my application that is hosting the workflowapp. The activity is to return the object so the ClientUpdate can be passed to the workflow and have it sent to the remote clients via the send activity in the pick branch. In theory anyways.
For some reason it seems to be correct but feels wrong. I'm not sure if I should write the Activity in a different way to take care of what I need for my WF service.
I think your intentions would be a bit clearer if you created an extension (that implements IWorkflowInstanceExtension) to perform your action here.
For example:
public sealed class AsyncWorkExtension
: IWorkflowInstanceExtension
{
// only one extension per workflow
private WorkflowInstanceProxy _proxy;
private Bookmark _lastBookmark;
/// <summary>
/// Request the extension does some work for an activity
/// during which the activity will idle the workflow
/// </summary>
/// <param name="toResumeMe"></param>
public void DoWork(Bookmark toResumeMe)
{
_lastBookmark = toResumeMe;
// imagine I kick off some async op here
// when complete system calls WorkCompleted below
// NOTE: you CANNOT block here or you block the WF!
}
/// <summary>
/// Called by the system when long-running work is complete
/// </summary>
/// <param name="result"></param>
internal void WorkCompleted(object result)
{
//NOT good practice! example only
//this leaks resources search APM for details
_proxy.BeginResumeBookmark(_lastBookmark, result, null, null);
}
/// <summary>
/// When implemented, returns any additional extensions
/// the implementing class requires.
/// </summary>
/// <returns>
/// A collection of additional workflow extensions.
/// </returns>
IEnumerable<object> IWorkflowInstanceExtension
.GetAdditionalExtensions()
{
return new object[0];
}
/// <summary>
/// Sets the specified target
/// <see cref="WorkflowInstanceProxy"/>.
/// </summary>
/// <param name="instance">The target workflow instance to set.</param>
void IWorkflowInstanceExtension
.SetInstance(WorkflowInstanceProxy instance)
{
_proxy = instance;
}
}
Within the Activity, you'd use this thusly:
var ext = context.GetExtension<AsyncWorkExtension>();
var bookmark = context.CreateBookmark(BookmarkCallback);
ext.DoWork(bookmark);
return;
This way is much more explicit (instead of using the bookmark name to convey meaning to the "outside" world) and is much easier to extend if, say, you require to send out more information than a bookmark name.
Is there something actually resuming the bookmark here? If not the workflow will wait very patiently and nothing will happen.

Categories