Asp.NET MVC FileSystemWatcher does not work after close browser - c#

I created file system watcher in my mvc application. But there is one problem: when client closes browser and leave application for a long time file system watcher stops working. File watcher monitores a ftp directory, everyday at roughly 23:58 or 00-00 data refreshes. Here is the code of file system watcher and Global.asax.cs:
MonitorConfig.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KegokProj.Models;
using KegokProj.BLL;
using System.Web.Hosting;
namespace KegokProj.App_Start
{
public class MonitorConfig
{
public static void RegisterWatchers()
{
var fileWatcher = FileWatcher.ObserveFolderChanges(#"F:\ftp\data", "*.txt", TimeSpan.FromSeconds(1))
.Subscribe(fce =>
{
if (fce != null)
RecordEntry(fce.FileName);
});
}
private static void RecordEntry(string fileName)
{
BLogic bll = new BLogic();
bll.AddParamsByFileWatcher(fileName);
}
}
}
Global.asax.cs:
using FluentScheduler;
using KegokProj.App_Start;
using KegokProj.BLL;
using KegokProj.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
namespace KegokProj
{
public class MvcApplication : HttpApplication, IHttpHandler, IRequiresSessionState
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
MonitorConfig.RegisterWatchers();
}
}
}
FileWatcher class:
using KegokProj.BLL;
using KegokProj.Controllers;
using KegokProj.DAL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using System.Web.Hosting;
namespace KegokProj.Models
{
public class FileWatcher
{
public class FileChangedEvent
{
public string FullPath { get; private set; }
public string FileName { get; private set; }
public bool IsFileDeleted { get; private set; }
public bool IsFileChanged { get; private set; }
public FileChangedEvent(string path, string fileName, bool isFileDeleted = false, bool isFileChanged = false)
{
FullPath = path;
FileName = fileName;
IsFileDeleted = isFileDeleted;
IsFileChanged = isFileChanged;
}
}
public static IObservable<FileChangedEvent> ObserveFolderChanges(string path, string filter, TimeSpan throttle)
{
return Observable.Using(
() => new FileSystemWatcher(path, filter) { EnableRaisingEvents = true },
fileSystemWatcher => CreateSources(fileSystemWatcher)
.Merge()
.GroupBy(c => c.FullPath)
.SelectMany(fileEvents => fileEvents
.Throttle(throttle)
.Where(e => !e.IsFileChanged)));
}
private static IObservable<FileChangedEvent>[] CreateSources(FileSystemWatcher fileWatcher)
{
return new[]
{
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs >(handler => fileWatcher.Created += handler, handler => fileWatcher.Created -= handler)
.Select(ev => new FileChangedEvent(ev.EventArgs.FullPath, ev.EventArgs.Name)),
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs >(handler => fileWatcher.Deleted += handler, handler => fileWatcher.Deleted -= handler)
.Select(ev => new FileChangedEvent(ev.EventArgs.FullPath, ev.EventArgs.Name, true)),
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs >(handler => fileWatcher.Changed += handler, handler => fileWatcher.Changed -= handler)
.Select(ev => new FileChangedEvent(ev.EventArgs.FullPath, ev.EventArgs.Name)),
//The rename source needs to send a delete event for the old file name.
//Observable.Create<FileChangedEvent>(nameChangedObserver =>
//{
// return Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(handler => fileWatcher.Renamed += handler, handler => fileWatcher.Renamed -= handler)
// .Subscribe(ev =>
// {
// nameChangedObserver.OnNext(new FileChangedEvent(ev.EventArgs.FullPath, ev.EventArgs.Name));
// nameChangedObserver.OnNext(new FileChangedEvent(ev.EventArgs.OldFullPath, ev.EventArgs.Name, true));
// });
//}),
Observable.FromEventPattern<ErrorEventHandler, ErrorEventArgs >(handler => fileWatcher.Error += handler, handler => fileWatcher.Error -= handler)
.SelectMany(ev => Observable.Throw<FileChangedEvent>(ev.EventArgs.GetException()))
};
}
}
}

You need to host your filesystem watcher in a Windows Server or in an IIS Always-on website. IIS will automatically close your application pool thread, or create new parallel ones if the load requires it.
IIS Application Pool recycling reference https://learn.microsoft.com/en-us/iis/configuration/system.applicationhost/applicationpools/add/recycling/

Related

How to Retrieve data inside of the generated key that I just push

I'm trying to retrieve the data inside of the generated key from firebase real time database using C# language and the retrieve data will show in RecyclerViewer. I try everything but still not showing in RecyclerView.
This is my code
how to solve this?
THIS IS THE LISTENER:
using AdamsonsEDApp.Data_Models;
using AdamsonsEDApp.Helpers;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static AdamsonsEDApp.Listeners.StaffListeners;
namespace AdamsonsEDApp.Listeners
{
public class PackageInfoListeners : Java.Lang.Object, IValueEventListener
{
List<PackageInfo> packageinfoList = new List<PackageInfo>();
public event EventHandler<PackageInfoDataEventArgs> PackageInfoRetrieved;
public class PackageInfoDataEventArgs : EventArgs
{
public List<PackageInfo> PackageInfo { get; set; }
}
public void OnCancelled(DatabaseError error)
{
throw new NotImplementedException();
}
public void OnDataChange(DataSnapshot snapshot)
{
if (snapshot.Value != null)
{
var child = snapshot.Children.ToEnumerable<DataSnapshot>();
packageinfoList.Clear();
foreach (DataSnapshot infoData in child)
{
PackageInfo info = new PackageInfo();
info.packageinfoID = infoData.Key;
info.packageinfoName = infoData.Child("infoName").Value.ToString();
info.packageinfoQty = infoData.Child("infoQty").Value.ToString();
packageinfoList.Add(info);
}
PackageInfoRetrieved.Invoke(this, new PackageInfoDataEventArgs { PackageInfo = packageinfoList });
}
}
public void Create()
{
DatabaseReference infoRef = AppDataHelper.GetDatabase().GetReference("packageinfo");
infoRef.AddValueEventListener(this);
}
}
}
This is the Activit
using AdamsonsEDApp.Adapters;
using AdamsonsEDApp.Data_Models;
using AdamsonsEDApp.Fragments;
using AdamsonsEDApp.Listeners;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdamsonsEDApp.Resources.activities
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = false)]
public class eventpackageinfo_activity : AppCompatActivity
{
string packageinfoname, packageinfoqty;
TextView infonameText, infoqtyText;
ImageView /*removeButton,*/ backpackageButton/*, searchButton*/;
//EditText searchText;
RecyclerView packageinfoRecyclerView;
Button addinclusionsButton;
AddPackageInfoFragment addpackageinfoFragment;
PackageInfoAdapter packageinfoadapter;
List<PackageInfo> packageinfoList;
PackageInfoListeners infoListeners;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.eventpackageinfos);
infonameText = (TextView)FindViewById(Resource.Id.infonameText);
infoqtyText = (TextView)FindViewById(Resource.Id.infoqtyText);
addinclusionsButton = (Button)FindViewById(Resource.Id.addinclusionsButton);
backpackageButton = (ImageView)FindViewById(Resource.Id.backpackageButton);
packageinfoRecyclerView = (RecyclerView)FindViewById(Resource.Id.packageinfoRecyclerView);
backpackageButton.Click += BackpackageButton_Click;
addinclusionsButton.Click += AddinclusionsButton_Click;
RetrieveData();
}
private void AddinclusionsButton_Click(object sender, EventArgs e)
{
}
private void BackpackageButton_Click(object sender, EventArgs e)
{
Intent infointent = new Intent(this, typeof(eventpackage_activity));
StartActivity(infointent);
}
private void SetupPackageInfoRecyclerView()
{
packageinfoRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(packageinfoRecyclerView.Context));
PackageInfoAdapter packageinfoadapter = new PackageInfoAdapter(packageinfoList);
packageinfoRecyclerView.SetAdapter(packageinfoadapter);
}
public void RetrieveData()
{
infoListeners = new PackageInfoListeners();
infoListeners.Create();
infoListeners.PackageInfoRetrieved += InfoListeners_PackageInfoRetrieved;
}
private void InfoListeners_PackageInfoRetrieved(object sender, PackageInfoListeners.PackageInfoDataEventArgs e)
{
packageinfoList = e.PackageInfo;
SetupPackageInfoRecyclerView();
}
}
}
Are you sure you're listening to the correct path in the database? Your code attaches a listener to:
DatabaseReference infoRef = AppDataHelper.GetDatabase().GetReference("packageinfo");
But your screenshot shows a node named eventpackage under the root.

C# Windows Service with multiple timers from file

I have multiple "jobs" with timers in a file.
I want to use all of them but when i start the service i see that only the last timer in the configuration is working
How can i do have multiple timers created based on a List that can change over time (yes i can restart the service when i change the list but i don't want to write a timer foreach
Here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using InserterService.Dao;
namespace InserterService
{
public partial class InserterService : ServiceBase
{
public InserterService()
{
InitializeComponent();
}
class CustomTimer : System.Timers.Timer
{
public Configurazione configurazione;
}
protected override void OnStart(string[] args)
{
//** CARICA CONFIGURAZIONI **//
// PER OGNI CONFIGURAZIONE DEFINISCO IL TIMER
List<Configurazione> Configurazioni = new List<Configurazione>();
Configurazioni = ModulReader.GetModulCopyDirectory();
int i = 0;
foreach (var item in Configurazioni )
{
i++;
string data = string.Format("CONFIGURAZIONE {0}",i.ToString());
string folder = #"C:\temp\OUT\";
// Filename
string fileName = "Test.txt";
// Fullpath. You can direct hardcode it if you like.
string fullPath = folder + fileName;
File.AppendAllText(fullPath, data);
var timer = new CustomTimer
{
Interval = Int32.Parse(item.TIMER.Trim()),
configurazione = item
};
timer.Elapsed += Lavorazione;
timer.Start();
}
}
public void Lavorazione(object sender, ElapsedEventArgs e)
{
Configurazione configurazione = ((CustomTimer)sender).configurazione;
string data = configurazione.DATA;
string folder = #"C:\temp\OUT\";
// Filename
string fileName = "Test.txt";
// Fullpath. You can direct hardcode it if you like.
string fullPath = folder + fileName;
File.AppendAllText(fullPath, data);
}
protected override void OnStop()
{
}
}
}

Xamarin SQLite Database Check

I am new to Xamarin. I want to confirm if the database is created and if the data is being inserted to the SQLite database. Thank you for the help
Questions:
1. How to check if database exist/created or not?
2. How to check if the user are inserted successfully or it failed?
3. Where do these file go in my phone?
Below is my code:
App.xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TBSMobileApplication.Views;
using TBSMobileApplication.Data;
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace TBSMobileApplication
{
public partial class App : Application
{
static TokenDatabaseController tokenDatabase;
static UserDatabaseController userDatabase;
public App ()
{
InitializeComponent();
MainPage = new LoginPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
public static UserDatabaseController UserDatabase
{
get
{
if(userDatabase == null)
{
userDatabase = new UserDatabaseController();
}
return userDatabase;
}
}
public static TokenDatabaseController TokenDatabase
{
get
{
if (tokenDatabase == null)
{
tokenDatabase = new TokenDatabaseController();
}
return tokenDatabase;
}
}
}
}
LoginPage.xaml.cs (Basically this is my Code behind in my login page)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBSMobileApplication.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TBSMobileApplication.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage ()
{
InitializeComponent ();
}
void LoginProcedure(object sender, EventArgs e)
{
User user = new User(entUser.Text, entPassword.Text);
if (user.CheckInformation())
{
//DisplayAlert("Login Message", "Login Success", "Ok");
try
{
App.UserDatabase.SaveUser(user);
DisplayAlert("Database Message", "User Saved", "Ok");
}
catch(Exception ex)
{
DisplayAlert("Message", ex.Message, "Ok");
}
}
else
{
DisplayAlert("Login Message", "Login Failed", "Ok");
}
}
}
}
ISQLite.cs (This is where you get the connection to the database)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Data
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
User.cs (This is where the parameters of the User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Models
{
public class User
{
[PrimaryKey, AutoIncrement]
public int ContactID { get; set; }
[Unique]
public string UserID { get; set; }
public string UserPassword { get; set; }
public User() { }
public User(string Username, string Password)
{
this.UserID = Username;
this.UserPassword = Password;
}
public bool CheckInformation()
{
if(!this.UserID.Equals("") || !this.UserPassword.Equals(""))
{
return true;
}
else
{
return false;
}
}
}
}
SQLite_Android.cs (This is where I created the database)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using TBSMobileApplication.Data;
using TBSMobileApplication.Droid.Data;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace TBSMobileApplication.Droid.Data
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.SQLiteConnection GetConnection()
{
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, DBFileName);
var conn = new SQLite.SQLiteConnection(path);
return conn;
}
}
}
UserDatabaseController.cs (This is where I control User table like adding, deleting or getting data from User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using TBSMobileApplication.Models;
using Xamarin.Forms;
namespace TBSMobileApplication.Data
{
public class UserDatabaseController
{
static object locker = new object();
SQLiteConnection database;
public UserDatabaseController()
{
database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<User>();
}
public User GetUser()
{
lock (locker)
{
if(database.Table<User>().Count() == 0)
{
return null;
}
else
{
return database.Table<User>().First();
}
}
}
public int SaveUser(User user)
{
lock (locker)
{
if (user.ContactID != 0)
{
database.Update(user);
return user.ContactID;
}
else
{
return database.Insert(user);
}
}
}
public int DeleteUser(int contactid)
{
lock (locker)
{
return database.Delete<User>(contactid);
}
}
}
}
Starting with part 3 of your question - where is the database file? - it's here:
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
That equates to:
/data/data/[your.package.name]/files/backend.db3
For the first part of your question, to check whether the database has been created, just check whether the file exists:
public static bool DBExists()
{
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, "backend.db3");
return File.Exists(path);
}
Accessing the file there is somewhere between difficult and impossible without a rooted device. You're not supposed to be able to access files there - only your app can access them. It's a safety measure.
Your application doesn't have any trouble accessing the database file, though, so you can implement a method in your application to copy it somewhere more accessible (e.g. the Downloads directory).
Put this in your Android project:
public static void CopyDBToDownloadsDirectory()
{
var path = System.IO.Path.Combine(
Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath,
"backend.db3");
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var safePath = Path.Combine(DocumentPath, "backend.db3");
File.Copy(safePath, path, true);
}
Call it to create a copy of the database you can readily access on the phone's built-in file browser.
So, for part 2 of the question, whether a transaction succeeded or failed, you can either run queries against your database in code to check, or open a copy of the database file in a GUI and browse the data.

NSubstitute Checking received calls don't work

Hey guys im new with the NSubstitute framework. I'm trying to test some of my classes, but when i use NSubstitute to check received calls it says received no matching calls.
I'm trying to test if the method Tick() is receiving update() from track class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ATM_System.Event;
using ATM_System.EventDetection;
using ATM_System.Region;
using ATM_System.Track;
namespace ATM_System
{
public class ATM
{
private List<ITrack> _tracks;
private IRegion _region;
private List<IEventDetection> _eventdetects;
private List<IEvent> _events;
public ATM()
{
_tracks = new List<ITrack>();
_region = new Region.Region(100000,100000); //could be changed by user
_events = new List<IEvent>();
_eventdetects = new List<IEventDetection>();
}
public void Tick()
{
// update track positions
foreach (var track1 in _tracks)
{
track1.update();
}
//check for events
foreach (var detector in _eventdetects)
{
_events.AddRange(detector.DetectEvent(_tracks));
}
//handle events and output
foreach (var event1 in _events)
{
event1.HandleEvent();
event1.LogEvent();
}
}
public void IncomingTrack(ITrack track)
{
//add incoming track
_tracks.Add(track);
}
}
}
TEST FILE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ATM_System.Event;
using ATM_System.EventDetection;
using ATM_System.Track;
using NUnit.Framework;
using NSubstitute;
namespace ATM_System.Tests.Unit
{
[TestFixture]
class ATMUnitTests
{
private ATM _uut;
private ITrack _track;
private IEvent _event;
private IEventDetection _eventDetection;
[SetUp]
public void Setup()
{
_track = Substitute.For<ITrack>();
_event = Substitute.For<IEvent>();
_eventDetection = Substitute.For<IEventDetection>();
_uut = new ATM();
}
[Test]
public void Tick_UpdateTracks_TracksUpdated()
{
_uut.Tick();
_track.Received().update();
}
}
}
You forgot to include _track in notification receivers. It simply hasn't subscribed to event and as a result is not notified. To fix simply call your IncomingTrack method:
[Test]
public void Tick_UpdateTracks_TracksUpdated()
{
_uut.IncomingTrack(_track);
_uut.Tick();
_track.Received().update();
}

Altering multiple databases with NHibernate

I'm having trouble with the copying entities between multiple databases. I can't seem to get my head around this issue and really need some help with the implementation.
My current implementation is described here:
Http module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ISMSControl.Infrastructure.Sessions;
using NHibernate;
using NHibernate.Context;
namespace ISMSControl.Infrastructure.Modules
{
public class SessionModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OpenSession;
context.EndRequest += CloseSession;
}
private void CloseSession(object sender, EventArgs e)
{
ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.GetCurrentSession().SessionFactory);
if (session != null)
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Rollback();
else
session.Flush();
session.Close();
}
}
private void OpenSession(object sender, EventArgs e)
{
ManagedWebSessionContext.Bind(HttpContext.Current,
SessionManager.GetCurrentSession());
}
public void Dispose()
{
}
}
}
SessionManager implemenation
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using ISMSControl.Infrastructure.Mappings;
using NHibernate;
using NHibernate.Cache;
namespace ISMSControl.Infrastructure.Sessions
{
public sealed class SessionManager
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;
static SessionManager()
{
sessionFactory = CreateSessionFactory("source");
}
private static ISessionFactory CreateSessionFactory(string connectionStringName)
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(c => c.FromConnectionStringWithKey(connectionStringName)))
.CurrentSessionContext("managed_web")
.Cache(c =>
{
c.UseQueryCache();
c.ProviderClass<HashtableCacheProvider>();
})
.Diagnostics(d =>
{
d.Enable();
d.OutputToConsole();
})
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<StandardMapping>())
.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static void CloseSessionFactory(string sessionFactoryName = null)
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
Repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using ISMSControl.Domain;
using ISMSControl.Domain.Contracts;
using ISMSControl.Infrastructure.Sessions;
using NHibernate;
using NHibernate.Context;
namespace ISMSControl.Infrastructure.Repositories
{
public class StandardRepository : IStandardRepository
{
public void SaveOrUpdate(Standard standard)
{
var session = SessionManager.GetCurrentSession();
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(standard);
transaction.Commit();
}
}
public IEnumerable<Standard> RetrieveList()
{
return SessionManager.GetCurrentSession().CreateCriteria<Standard>().List<Standard>();
}
public void CopyTo(string database, Standard standard)
{
//how do i implement this method, so it will copy the standard entity to the other database?
}
}
}
The problem is that i'm getting all these different kind of errors like, "The session is closed.", "The entity belows to another transaction or something". "Illegal attempt to associate a collection with two open sessions".
I really hope that someone can help me out our point me in the right direction by sharing a
Tutorial
Example
etc.
CopyTo implemenation
public void CopyTo(string sessionFactoryName, Standard standard)
{
//gets a new session for the destination database from the destination sessionfactory.
using (var destinationSession = SessionFactoryContainer.Current.Get(sessionFactoryName).OpenSession())
{
//error: no persister for...
var newStandard = new Standard();
newStandard.Code = standard.Code;
newStandard.Description = standard.Description;
newStandard.Explanation = standard.Explanation;
destinationSession.Save(newStandard);
}
}
In your "CopyTo" method, you have to create a session on the second database, deep clone the second parameter of your method and then attach the cloned object to the session you opened.

Categories

Resources