Static Class Not maintaining its state C# - c#

My question here is why my feed_expiration_date datetime variable becomes null on each request only in server environment it works perfectly on local environment I have a web garden (8 process workers) on both local and server environment.
actually since I have 8 process worker so I have different process ID for example PID:1234 and initially it has the feed_expiration_date value set to some date and when user again request the page with in the expiration period time if the process gets same PID: 1234 then PID:1234 should hold its previous value. in my local it is working as expected but on the server environment it is not working any help would be highly appreciated
public static class CacheManager
{
public static ClientData ClientDataCache
{
get
{
return GetClientDataCacheByID(HostInstanceID);
}
}
public static ClientData GetClientDataCacheByID(int instance_id)
{
try
{
ClientData data = null;
if (instance_id != 0)
data = client_cache_data_dictionary.ContainsKey(instance_id) ? client_cache_data_dictionary[instance_id] : null;
if (data == null || data.GlobalSettingsCache == null || DateTime.UtcNow > data.date_cached.AddHours(1))
return GenerateClientData();
return data;
}
catch (Exception ex)
{
return null;
}
}
private static ClientData GenerateClientData()
{
lock (InstanceLocker)
{
ClientData data = null;
int instance_id = HostInstanceID;
if (instance_id != 0)
data = client_cache_data_dictionary.ContainsKey(instance_id) ? client_cache_data_dictionary[instance_id] : null;
if (data == null || data.GlobalSettingsCache == null || DateTime.UtcNow > data.date_cached.AddHours(1))
{
data = new ClientData(true);
if (data != null && data.InstanceID > 0)
{
int id = data.InstanceID;
HostInstanceID = id;
client_cache_data_dictionary[id] = data; // To prevent race conditions, this has to happen prior to client_data_cache_lock_dictionary[id] = new object();
client_data_cache_lock_dictionary[id] = new object(); // This has to happen 2nd, not first
if (Portals.Utils.IsEC2)
{
try
{
if (!global_cache_mgr_init)
{
GlobalCacheManager.GlobalCacheManager.Initialize(GlobalCacheManager.Enumerations.SystemLocations.AdminPortal, !Portals.Utils.IsEC2 ? "us-west-2" : null);
global_cache_mgr_init = true;
GlobalCacheManager.GlobalCacheManager.Start();
}
}
catch (Exception ex)
{
Emails.SendAdminEmail("Error Init/Start GCM on ClientCache.cs", ex.StackTrace);
}
}
}
Portals.Utils.LogErrorFeed("ReadGSFromDB","true PID: " + System.Diagnostics.Process.GetCurrentProcess().Id);
}
else
{
Portals.Utils.LogErrorFeed("ReadGSFromCache", "true PID: " + System.Diagnostics.Process.GetCurrentProcess().Id);
}
return data;
}
}
public class ClientData
{
public ClientData(bool initdata = false) {
if (initdata) IntializeClientData();
}
private List<SurveysAndFeaturesFeedResult> surveyAndFeaturesFeeds = null;
public DateTime date_cached { get; set; }
public DateTime? feed_expiration_date { get;set;}
private object surveys_features_generate_locker = new object();
public void GenerateSurveysAndFeaturesCache(bool force_refresh = false)
{
if(this.InstanceID != 0)
{
lock(surveys_features_generate_locker)
{
if (this.surveyAndFeaturesFeeds == null || force_refresh)
{
this.surveyAndFeaturesFeeds = CakeFeed.GetSurveysAndFeaturesFeedResult();
this.feed_expiration_date = DateTime.UtcNow.AddHours(this.global_settings.CakeFeedCacheDurationHoursCKM);
}
}
if(force_refresh && this.surveyAndFeaturesFeeds != null)
{
Portals.Utils.RefreshPortals();
}
}
}
public List<SurveysAndFeaturesFeedResult> SurveysAndFeaturesFeed
{
get
{
if(this.global_settings.EnablePresentIcon && (surveyAndFeaturesFeeds == null || feed_expiration_date == null || feed_expiration_date < DateTime.UtcNow))
{
GenerateSurveysAndFeaturesCache();
}
return (surveyAndFeaturesFeeds == null) ? new List<SurveysAndFeaturesFeedResult>() : surveyAndFeaturesFeeds.ToList();
}
}
}
}
And from handler.ashx I call this as CacheManager.ClientDataCache.SurveysAndFeaturesFeed.OrderByDescending(x=>x.PublishDate).ToList();

Related

I got connection error it does not read data from database

In Xamarin forms, I tried to make a login form using MVVM. When I write the code there is no error but it does not give the desired output.
public Command Login
{
get
{
return new Command(() =>
{
var d = database.loggin(Usernamelogin, Passwordlogin);
if (d != null)
{
if (d.UserName == Usernamelogin && d.Password == Passwordlogin)
{
App.Current.MainPage.DisplayAlert("Notification", "Successfully Login", "Okay");
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "Error Login", "Okay");
}
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "No data", "Okay");
}
});
}
}
this is login command
public Register_person loggin(string mail,string pass )
{
return Conn.Table<Register_person>().FirstOrDefault(t => (t.Email == mail && t.Password == pass));
}
I only get the display message when the database is null statement. I cannot find why.
public ICommand Login { get; set; }
then add a constructor
public LoginViewModel()
{
Login = new Command(Login_Clicked);
}
then create a method Login_Clicked
private void Login_Clicked()
{
database = new Database();
var Logindata = database.GetUsername(_usernamelogin);
if (string.IsNullOrWhiteSpace(_usernamelogin) || string.IsNullOrWhiteSpace(_passwordlogin))
{
// your code
}
else
{
if (Logindata != null)
{
if (Logindata.UserName == _usernamelogin && Logindata.Password == _passwordlogin)
{
// your code
}
else
{
// your code
}
}
else
{
// your code
}
}
}
linc query
return Conn.Table<your Table name>().FirstOrDefault(t => t.Email == mail);
I extract email in the table

WPF singelton intance gives null exception, before singelton value is set

I have created a Singelton
static readonly License_plateRequests _instance = new License_plateRequests();
private License_plateRequests()
{
}
public static License_plateRequests instance
{
get { return _instance; }
}
public License_plate license_plateFirst { get; set; }
I run a clickevent in a page, to run some code where i set the singelton value. Its my first application in WPF so, i dont know if the patteren is right.
private async void enterButton_Click(object sender, RoutedEventArgs e)
{
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Denmark-icon.png")
{
nationality = "DK";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Germany-icon.png")
{
nationality = "GER";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Norway-icon.png")
{
nationality = "NOR";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Sweden-icon.png")
{
nationality = "SWE";
}
if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/United-Kingdom-flat-icon.png")
{
nationality = "GB";
}
var data = await loginRequest.LoginAsync();
var token = await loginRequest.ParkingToken(data.jwt);
var licenseplate = await licensePlate.LicensePlate(token, nationality, numberplateInput.Content.ToString());
var parkings = await licensePlate.getParkingById(token, licenseplate.id);
try
{
foreach (var parking in parkings)
{
if (parking == null)
{
parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
NavigationService.Navigate(new RegistredPage());
}
else if (parking.time_end == 0)
{
NavigationService.Navigate(paymentPage, licenseplate);
licensePlate.license_plateFirst.country.alpha2 = nationality;
}
else
{
parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
NavigationService.Navigate(new RegistredPage());
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
Then i navigate by NavigationService to the next page PaymentPage.
I get a nullpointer Exception in PaymentPage.
public partial class PaymentPage : Page
{
License_plateRequests licensePlate = License_plateRequests.instance;
public PaymentPage()
{
InitializeComponent();
System.Diagnostics.Debug.WriteLine(licensePlate.license_plateFirst.country.alpha2);
}
}
I get the null pointer when i try to run the application. I havent set the value yet, so offcourse
licensePlate.license_plateFirst.country.alpha2
gives me null. But i havent loaded that page yet, and i havent set the value.
How can i handle this, so i can get the value when the page is first loaded?

WPF MVVM Control that connects to Web API

I have an ASP.NET Web API with SQL Database / Entity Framework that I will be using as the server side of an application that I am building. The client side will be WPF for now. I am having some trouble determining the best method for the MVVM controls to access the data from the server. All of the tutorials and courses I have done for MVVM connect directly to a local database, and they update when the control is loaded. What I want is a constant loop where the API is called once per minute and the data in the control automatically refreshed at that point. I have this working for the two main controls (ran into a problem updating the collection from a different thread and had to use App.Current.Dispatcher.Invoke), however I am not sure if I am keeping to best practice running the API calls directly from the view model. Also, I need to be able to share data between the view models.
ScheduledForwardsViewModel has data that ActiveForwardsViewModel needs, and ActiveForwardsViewModel has data that CreateForwardsViewModel needs. The ActiveForward for each entry needs to be able to see the scheduled date for each corresponding scheduled item so it can find the next event and display the time left until that event occurs in the ActiveForwardsView. The CreateForwardView simply needs access to the AllUsers,AllGroups,AllContacts observable collections created during the ActiveForwards data manipulation so it can use that data in the drop down fields when scheduling a new forward. I haven't been able to get the dropdowns to work yet. I do have access to the info I need from ScheduledForwardsView using a static object, but I feel like there may be a better way. I would prefer to refrain from making multiple calls to the API for the same data when part of my app already has the data I need.
Basic Layout:
MainWindow
CreateForwardView (with view model)
[Drop down boxes to select user and schedule forward]
[Buttons, etc.]
[TabControl]
[TabItem: Active Forwards]
ActiveForwardsView (with view model)
[TabItem: Scheduled Forwards]
ScheduledForwardsView (with view model)
[EndTabControl]
The ActiveForwardsViewModel is below. The ScheduledForwardsViewModel is essentially the same thing, but it calls a different API method and contains a static object that I am using in ActiveForwardsViewModel (see the part where I wait for ScheduledForwardsViewModel to complete 1 run before I continue with UpdateUserObjects). That didn't seem like the right way to do it, but I set it up that way just so I could move onto other things.
public class ActiveForwardsViewModel : INotifyPropertyChanged
{
private CancellationToken updater = default(CancellationToken);
private AppLog log;
private FFObject _selectedObject;
private ObservableCollection<FFObject> _activeForwards;
public ObservableCollection<FFObject> ActiveForwards
{
get { return _activeForwards; }
set
{
if (_activeForwards != value)
{
_activeForwards = value;
PropertyChanged(this, new PropertyChangedEventArgs("ActiveForwards"));
}
}
}
public ObservableCollection<FFObject> AllUsers { get; set; }
public ObservableCollection<FFObject> AllGroups { get; set; }
public ObservableCollection<FFObject> AllContacts { get; set; }
public ObservableCollection<FFObject> AllObjects { get; set; }
public bool Running = false;
public bool FirstRunComplete = false;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ActiveForwardsViewModel()
{
if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
{
updater.ThrowIfCancellationRequested();
return;
}
ActiveForwards = new ObservableCollection<FFObject>();
AllUsers = new ObservableCollection<FFObject>();
AllGroups = new ObservableCollection<FFObject>();
AllContacts = new ObservableCollection<FFObject>();
AllObjects = new ObservableCollection<FFObject>();
StartUpdater(updater);
RemoveForwardCommand = new RelayCommand(OnRemove, CanRemove);
}
public async Task StartUpdater(CancellationToken token = default(CancellationToken))
{
while (!token.IsCancellationRequested)
{
Running = true;
await this.Update();
FirstRunComplete = true;
try
{
await Task.Delay(TimeSpan.FromMinutes(1), token);
}
catch (TaskCanceledException)
{
Running = false;
break;
}
}
}
private List<FFObject> UpdateAllObjectList(string strJson)
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<List<FFObject>>(strJson);
//return AllObjects;
}
public string GetString(string method)
{
using (var client = new WebClient())
{
var url = string.Format("https://mywebapi.domain.com/api/{0}", method);
return client.DownloadString(url);
}
}
public async Task Update()
{
Func<string, List<FFObject>> getUsersJson = UpdateAllObjectList;
await Task<string>.Factory.StartNew(() => GetString("Users"))
.ContinueWith(antecendent => getUsersJson(antecendent.Result))
.ContinueWith(antecendent => UpdateUserObjects(antecendent.Result));
}
private void CheckRemoved(List<FFObject> all)
{
List<FFObject> RemoveObjects = new List<FFObject>();
foreach (var obj in ActiveForwards)
{
var newObj = all.FirstOrDefault(i => i.ID == obj.ID);
if (newObj == null)
{
RemoveObjects.Add(obj);
}
else
{
if (!(bool) newObj.IsForwarded)
{
RemoveObjects.Add(obj);
}
}
}
foreach (var obj in RemoveObjects)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
ActiveForwards.Remove(obj);
});
}
}
private void UpdateUserObjects(List<FFObject> all)
{
Debug.WriteLine("Starting UpdateUserObject");
if (all != null)
{
AllObjects = new ObservableCollection<FFObject>(all);
CheckRemoved(all);
var x = 0;
while (!ScheduledForwardsViewModel.RunOnce && x < 5)
{
System.Threading.Thread.Sleep(1000);
x++;
}
foreach (var obj in all)
{
if (obj.ObjectType.ToLower() == "user")
{
var existing = AllUsers.FirstOrDefault(i => i.DistinguishedName == obj.DistinguishedName);
if (existing != null)
{
existing.ForwardedTo = obj.ForwardedTo;
existing.ForwardedToAd = obj.ForwardedToAd;
existing.ForwardedToDn = obj.ForwardedToDn;
existing.ForwardedToPk = obj.ForwardedToPk;
existing.ForwardedToDisplay = obj.ForwardedToDisplay;
existing.IsForwarded = obj.IsForwarded;
existing.DeliverAndRedirect = obj.DeliverAndRedirect;
existing.IsScheduled = obj.IsScheduled;
existing.TimeLeft = obj.TimeLeft;
}
else
{
//AllUsers.Add(obj);
App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE
{
AllUsers.Add(obj);
});
}
if (obj.IsForwarded ?? false)
{
existing = ActiveForwards.FirstOrDefault(i => i.DistinguishedName == obj.DistinguishedName);
obj.TimeLeft = "";
var now = DateTime.Now;
var TimeRemaining = new TimeSpan?();
foreach (var schedule in ScheduledForwardsViewModel.ScheduledForwards)
{
if (schedule.DistinguishedName == obj.DistinguishedName)
{
if (schedule.StopJobStatus == "Scheduled")
{
if (TimeRemaining == null)
{
TimeRemaining = schedule.StopTime - now;
}
else
{
if (schedule.StopTime - now < TimeRemaining)
{
TimeRemaining = schedule.StopTime - now;
}
}
}
}
}
if (TimeRemaining != null)
{
var remaining = (TimeSpan)TimeRemaining;
var min = new int();
if (remaining.Seconds > 30)
{
min = remaining.Minutes + 1;
}
double m = remaining.Minutes / (double)60;
double hm = remaining.Hours + m;
double h = hm / 24;
double dh = remaining.Days + h;
if (remaining.Days > 0)
{
var daysleft = Math.Round(dh, 2);
var quarterRound = Math.Round(dh * 4, MidpointRounding.ToEven) / 4;
obj.TimeLeft = quarterRound + "d";
}
else if (remaining.Hours > 0)
{
var hoursleft = Math.Round(hm, 2);
var quarterRound = Math.Round(hm * 4, MidpointRounding.ToEven) / 4;
obj.TimeLeft = quarterRound + "h";
obj.TimeLeft = remaining.Hours + "h" + remaining.Minutes + "m";
}
else
{
if (min == 0)
{
obj.TimeLeft = "< 30s";
}
else
{
obj.TimeLeft = min + "m";
}
}
}
if (existing != null)
{
existing.ForwardedTo = obj.ForwardedTo;
existing.ForwardedToAd = obj.ForwardedToAd;
existing.ForwardedToDn = obj.ForwardedToDn;
existing.ForwardedToPk = obj.ForwardedToPk;
existing.ForwardedToDisplay = obj.ForwardedToDisplay;
existing.IsForwarded = obj.IsForwarded;
existing.DeliverAndRedirect = obj.DeliverAndRedirect;
existing.IsScheduled = obj.IsScheduled;
existing.TimeLeft = obj.TimeLeft;
}
else
{
//ActiveForwards.Add(obj);
App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE
{
ActiveForwards.Add(obj);
});
}
}
}
else if (obj.ObjectType.ToLower() == "group")
{
if (obj.IsForwarded ?? false)
{
var existing = AllGroups.FirstOrDefault(i => i.DistinguishedName == obj.DistinguishedName);
if (existing != null)
{
existing.ForwardedTo = obj.ForwardedTo;
existing.ForwardedToAd = obj.ForwardedToAd;
existing.ForwardedToDn = obj.ForwardedToDn;
existing.ForwardedToPk = obj.ForwardedToPk;
existing.ForwardedToDisplay = obj.ForwardedToDisplay;
existing.IsForwarded = obj.IsForwarded;
existing.DeliverAndRedirect = obj.DeliverAndRedirect;
existing.IsScheduled = obj.IsScheduled;
existing.TimeLeft = obj.TimeLeft;
}
else
{
//AllGroups.Add(obj);
App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE
{
AllGroups.Add(obj);
});
}
}
}
else if (obj.ObjectType.ToLower() == "contact")
{
if (obj.IsForwarded ?? false)
{
var existing = AllContacts.FirstOrDefault(i => i.DistinguishedName == obj.DistinguishedName);
if (existing != null)
{
existing.ForwardedTo = obj.ForwardedTo;
existing.ForwardedToAd = obj.ForwardedToAd;
existing.ForwardedToDn = obj.ForwardedToDn;
existing.ForwardedToPk = obj.ForwardedToPk;
existing.ForwardedToDisplay = obj.ForwardedToDisplay;
existing.IsForwarded = obj.IsForwarded;
existing.DeliverAndRedirect = obj.DeliverAndRedirect;
existing.IsScheduled = obj.IsScheduled;
existing.TimeLeft = obj.TimeLeft;
}
else
{
//AllContacts.Add(obj);
App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE
{
AllContacts.Add(obj);
});
}
}
}
else
{
throw new NotImplementedException();
}
}
}
RunOnce = true;
}

Constraint Violation When Creating AD User Object with account management extension class attributes

I'm creating a WCF service to retrieve and update/create AD Person objects, and have run into a snag. I created an extension class to manage extended attributes (delivered schema attributes, but not in the default account management class attribute set). I have no problem retrieving or updating these extended attributes, but when I try to create a new person object in AD, I receive a constraint violation
System.DirectoryServices.DirectoryServicesCOMException: A constraint violation occurred.
I'm currently testing this in debug mode in Visio 2013 on a Windows 8.1 desktop. Code below. Any hints or insight anyone can offer is most appreciated.
Hopefully the code below is documented well enough and makes sense. Thanks in advance!
Update: I should have been more clear. The reason I am pretty sure it is the extension attributes is when I comment out those lines in the calling code (now commented in code section below) that set those attributes it will create the object without errors.
This is my calling code:
....other code.....
PrincipalContext pc = null;
try {
pc = new PrincipalContext(ContextType.Domain, MyProject.ADAccountService.Properties.Settings.Default.Domain, MyProject.ADAccountService.Properties.Settings.Default.PeopleDN, MyProject.ADAccountService.Properties.Settings.Default.AdminAcct, MyProject.ADAccountService.Properties.Settings.Default.AdminPW);
}
catch (Exception e) {
defaultLogger.Warn(MyProject.ADAccountService.App_GlobalResources.Messages.PrincipalContextCreateFail, e);
// Application.Exit();
}
....other code looking for whether ADObject already exists...
// Create the new UserPrincipal object
if (!newADPerson.personExists) {
using (ADeXt userNew = new ADeXt(pc)) {
string randomPassword = System.Web.Security.Membership.GeneratePassword(20, 4);
if (newADPerson.officePhone != null && newADPerson.officePhone.Length > 0) { userNew.VoiceTelephoneNumber = newADPerson.officePhone; }
if (newADPerson.department != null && newADPerson.department.Length > 0) { userNew.department = newADPerson.department; } //offending codeline
if (newADPerson.title != null && newADPerson.title.Length > 0) { userNew.title = newADPerson.title; } //offending codeline
if (newADPerson.faxNumber != null && newADPerson.faxNumber.Length > 0) { userNew.facsimileTelephoneNumber = newADPerson.faxNumber; } //offending codeline
if (newADPerson.officeLocation != null && newADPerson.officeLocation.Length > 0) { userNew.physicalDeliveryOfficeName = newADPerson.officeLocation; } //offending codeline
if (newADPerson.isEmployee) {
//if an employee and (newADPerson.script == null) use default value from global project settings
userNew.ScriptPath = newADPerson.script ?? MyProject.ADAccountService.Properties.Settings.Default.defaultScript;
}
if (newADPerson.lastName != null && newADPerson.lastName.Length > 0) { userNew.Surname = newADPerson.lastName; }
if (newADPerson.firstName != null && newADPerson.firstName.Length > 0) { userNew.GivenName = newADPerson.firstName; }
if (newADPerson.emplID != null) { userNew.EmployeeId = newADPerson.emplID; }
if (newADPerson.displayName != null && newADPerson.displayName.Length > 0) { userNew.DisplayName = newADPerson.displayName; }
userNew.SamAccountName = AccountID;
userNew.Name = AccountID;
userNew.UserPrincipalName = AccountID + MyProject.ADAccountService.Properties.Settings.Default.ExchangeAddress;
try {
userNew.Save();
userNew.SetPassword(randomPassword);
}
catch (Exception e) {
pc.Dispose();
}
}
}
Extension class code:
namespace MyProject.ADAccountService.Classes {
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class ADeXt : UserPrincipal {
public ADeXt(PrincipalContext context)
: base(context) {
}
public ADeXt(
PrincipalContext context,
string Container, //new constructor parameter added resolving issue
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
public static new ADeXt FindByIdentity(PrincipalContext context, string identityValue) {
return (ADeXt)FindByIdentityWithType(context, typeof(ADeXt), identityValue);
}
[DirectoryProperty("physicalDeliveryOfficeName")]
public string physicalDeliveryOfficeName {
get {
object[] result = this.ExtensionGet("physicalDeliveryOfficeName");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("physicalDeliveryOfficeName", value);
}
}
[DirectoryProperty("department")]
public string department {
get {
object[] result = this.ExtensionGet("department");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("department", value);
}
}
[DirectoryProperty("title")]
public string title {
get {
object[] result = this.ExtensionGet("title");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("title", value);
}
}
[DirectoryProperty("facsimileTelephoneNumber")]
public string facsimileTelephoneNumber {
get {
object[] result = this.ExtensionGet("facsimileTelephoneNumber");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("facsimileTelephoneNumber", value);
}
}
}
}
Thanks Marc, that hint helped me solve. added new parameter for the container in the extension constructor and that did the trick.
Changed the constructor in the extension class to add the default container. New constructor now lists like this:
public ADeXt(
PrincipalContext context,
**string Container,**
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
For anyone looking into this error. It could mean a lot of things, the first Google results will show that it has something to do with the PDC Emulator or replicating.
In my case it was due to too many characters for the employeeID (16 max). Sometimes it is initials (6 max) or samAccountName (19 max). Just peel of fields until it works as a starting point.

Entity framework error as"New transaction is not allowed because there are other threads running in the session

We are using entity framework codefirst approach
I am new to entity framework and I am facing error while trying to do "New transaction is not allowed because there are other threads running in the session.
public class DatabaseBackup : IDataBackup
{
private readonly IMonarchDbContext m_db;
public DatabaseBackup(IMonarchDbContext podb)
{
if (podb == null)
throw new ArgumentNullException("podb");
m_db = podb;
}
public DBBackupHistory GetLatestBackupHistory(DBBackupFrequency backupFrequency = DBBackupFrequency.Periodic)
{
DBBackupHistory result = null;
// get the backup history of the given backuptype and populate the objects
var configId = m_db.DBBackupConfigurations.Where(c => c.ScheduleType == (int)backupFrequency && c.BackupStatus == 1).Distinct().Select(c => c.ConfigurationId).DefaultIfEmpty(-1).First();
if (configId > 0)
{
result = m_db.DBBackupHistorys.Where(b => b.Status == 1 && b.ConfigurationId == configId).OrderByDescending(lb => lb.BackupDatetime).FirstOrDefault();
}
return result;
}
public IEnumerable<DBBackupConfiguration> GetAllConfiguration()
{
var result = m_db.DBBackupConfigurations.Where(c => c.BackupStatus == 1).OrderByDescending(c => c.ConfigurationId);
return result;
}
public void Backup(DBBackupConfiguration config, int fileIndex)
{
Console.WriteLine("Running DB Backup type {0} to device {1}", (DBBackupType)config.BackupType, fileIndex);
m_db.StoredProc.SPBackup(config, fileIndex);
}
I am calling the below methods in another class as follows
private readonly IDataBackup m_dataBackup;
public int PerformBackup(int defaultPollIntervalInMinutes = 15)
{
// polling interval in Minutes
int pollInterval = defaultPollIntervalInMinutes;
int fileIndex = getCurrentDumpFileIndex();
// check for the backup configuration
var configurations = m_dataBackup.GetAllConfiguration();
foreach (var config in configurations)
{
var lastBackup = m_dataBackup.GetLatestBackupHistory(DBBackupFrequency.Weekly);
if (lastBackup == null)
{
m_dataBackup.Backup(config, fileIndex + 1);
break;
}
Here is the Db Context class is as below
public class MonarchDbContext:DbContext,IMonarchDbContext
{
private IStoredProcedure m_storedProc;
private static object m_dbIntializerSet;
public MonarchDbContext(string nameOrConnectionString)
: base( nameOrConnectionString )
{
//-- Set the DB initializer only once.
System.Threading.LazyInitializer.EnsureInitialized( ref m_dbIntializerSet,()=>{
Database.SetInitializer<MonarchDbContext>(null);
//-- Give debug builds a chance to overwrite the above.
_SetInitializerForDebugBuilds();
return new object();
});
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
var csb = new SqlConnectionStringBuilder( this.Database.Connection.ConnectionString );
csb.MultipleActiveResultSets = true;
this.Database.Connection.ConnectionString = csb.ToString();
var objectContext = ( this as IObjectContextAdapter ).ObjectContext;
objectContext.CommandTimeout = 3600;
}
#region Public "Tables"
public IDbSet<DBBackupConfiguration> DBBackupConfigurations { get; set; }
public IDbSet<DBBackupHistory> DBBackupHistorys { get; set; }
public IStoredProcedure StoredProc
{
get
{
return System.Threading.LazyInitializer.EnsureInitialized(ref m_storedProc, () => new BackupStoredProc(this.Database));
}
}
#endregion
please let me know how can i solve the issue.
I found the issue
I need to add toList() at the end of the Linq code and it just worked for me.
public IEnumerable<DBBackupConfiguration> GetAllConfiguration()
{
var result = m_db.DBBackupConfigurations.Where(c => c.BackupStatus == 1).OrderByDescending(c => c.ConfigurationId).ToList();
return result;
}
Just add the List to Ienumerbale types

Categories